from io import BytesIO import openpyxl import datetime import jdatetime from itertools import chain from django.db.models import Case, When from django.db.models import Value import requests from oauth2_provider.models import AccessToken from rest_framework.throttling import AnonRateThrottle, UserRateThrottle from rest_framework.views import APIView from rest_framework.response import Response from deposit_id import wage_counting_type from general_urls import base_url_for_sms_report from panel.CityOperator.serializers import CityOperatorForSubSectorTransactionsSerializer, \ CityOperatorForSubSectorSerializer, CityOperatorForSubSectorSerializerForExcel from panel.KillHouse.helpers import get_difference_carcasses_weight, get_kill_house_finance_info, \ get_difference_carcasses_percent from panel.ProvinceOperator.serializers import \ GuildsPosMachineForTransactionsSerializer, PosMachineTransactionsForInspectionSerializer, \ TotalWageInformationSerializer, CityGuildForSubSectorSerializerForExcel, InProvinceAllocationSerializer, \ StewardFreeSaleBarInformationSerializer, RealGuildsForDashboardSerializer, \ GuildsPosMachineForTransactionsNewSerializer from panel.VetFarm.serializers import VetForSubSectorSerializer, VetForSubSectorSerializerForExcel from panel.helper import build_query from panel.helper_excel import Alignment_CELL, create_header, create_header_freez, excel_description, \ create_value, merge_cells, cell_color_changer, get_kill_house_finance_info_by_date, \ get_kill_house_distribution_info, get_kill_house_distribution_out_province_info, \ all_get_kill_house_distribution_info, GREEN_CELL, VERY_LIGHT_GREEN_CELL, LIGHT_GREEN_CELL, \ RED_CELL, convert_str_to_date from django.http import HttpResponse, QueryDict from openpyxl import Workbook from openpyxl.styles import PatternFill, Alignment, Font from openpyxl.utils import get_column_letter from django.db.models import Q, Sum, F, Count, Avg from panel.KillHouse.serializers import \ KillHouseForNewWageInormationSerializer, KillHouseFreeSaleBarInformationSerializer, \ KillHouseForPerformanceDashboardSerializer, KillHouseForProvinceWareHouseDashboardSerializer, \ KillRequestForDirectBuyingSerializer, ReturnProvinceKillRequestSerializer from panel.ReportingPanel.helper import poultry_request_new_fields from panel.convert_date import convert_to_shamsi from panel.filterset import KillHouseFilterSet, KillHouseRequestFilterSet, InternalTransactionFilterSet, \ PoultryRequestFilterSet, OutProvincePoultryRequestBuyerFilterSet, ChainCompanyFilterSet, ChainAllocationFilterSet, \ StewardAllocationDashboardFilterSet, KillHouseFreeSaleBarInformationFilterSet, \ StewardFreeSaleBarInformationFilterSet, KillRequestFilterSet, ReturnProvinceKillRequestFilterSet, \ GuildsForPostationFilterSet from panel.helper_excel import shamsi_date from panel.models import ProvinceKillRequest, \ ChainAllocation, KillHouseFreeBarInformation, InternalTransaction, ChainCompany, \ KillHousePercentage, KillHouseRequest, PoultryRequest, KillHouseVet, VetCheckRequest, \ KillHouseAssignmentInformation, VetFarm, Poultry, CityOperator, OutProvincePoultryRequestBuyer, Vet, \ PoultryHatching, KillHouseFreeSaleBarInformation, WageType, PercentageOfWageType, KillHouseWareHouse, \ StewardAllocation, RolesProducts, Guilds, SubSectorPercentageOfWageType, SubSectorTransactions, \ StewardFreeBarInformation, StewardFreeSaleBarInformation, PosMachineTransactions, CityGuild, TotalWageInformation, \ BarDifferenceRequest, BarDocumentStatus, KillRequest, POSTransactions, POSMachine, PosSegmentation, \ ProductsTransactions, WarehouseArchive from authentication.models import ( SystemUserProfile, City, ) from panel.models import ( KillHouse, ) def kill_house_total_transactions_wage_payid_super_admin_excel(request): filterset_class = KillHouseFilterSet filterset_fields = [ 'name', 'kill_house_operator__user__fullname', 'kill_house_operator__user__mobile', 'system_address__city__name', ] date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None kill_house_list = [] excel_options = [ 'ردیف', 'تاریخ پرداخت', 'نوع پرداخت', 'نام پرداخت کننده', 'تلفن پرداخت کننده', 'شماره درخواست', 'شماره پیگیری', 'کد سفارش', 'شماره کارت', 'مبلغ تراکنش(ریال)', 'سهم اتحادیه(ریال)', 'سهم شرکت(ریال)', 'سهم اصناف(ریال)', 'سهم دامپزشک(ریال)', ] output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) sheet_name = 'اطلاعات کلی' worksheet = workbook.create_sheet(sheet_name) if sheet_name == 'اطلاعات کلی': worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') if 'date1' in request.GET: from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) worksheet['B2'] = f'اطلاعات کلی تعرفه {from_date_1} تا {from_date_2}' merge_range1 = 'B2:C2' worksheet.merge_cells(merge_range1) worksheet['B2'].font = Font(color="C00000", bold=True) worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['B5'] = f'جزئیات {from_date_1} تا {from_date_2}' worksheet['B5'].font = Font(color="C00000", bold=True) worksheet['B5'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) else: # worksheet['B2'] = 'اطلاعات کلی تعرفه(از 1403/01/01 به بعد)' worksheet['B2'].font = Font(color="C00000") worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = 'B2:C2' worksheet.merge_cells(merge_range1) worksheet['B5'] = f'جزئیات' worksheet['B5'].font = Font(color="C00000", bold=True) worksheet['B5'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['C9'] = 'اتحادیه' worksheet['C9'].font = Font(color="C00000") worksheet['C9'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['C9'].fill = PatternFill(start_color="EEEAF2", fill_type="solid") worksheet['C9'].border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) worksheet['C10'] = 'شرکت' worksheet['C10'].font = Font(color="C00000") worksheet['C10'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['C10'].fill = PatternFill(start_color="EEEAF2", fill_type="solid") worksheet['C10'].border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) worksheet['C11'] = 'صنف' worksheet['C11'].font = Font(color="C00000") worksheet['C11'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['C11'].fill = PatternFill(start_color="EEEAF2", fill_type="solid") worksheet['C11'].border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) worksheet['C12'] = 'دامپزشک' worksheet['C12'].font = Font(color="C00000") worksheet['C12'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['C12'].fill = PatternFill(start_color="EEEAF2", fill_type="solid") worksheet['C12'].border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) header_list1 = [ 'کل تعرفه (ریال)', 'کل تعرفه پرداخت شده (ریال)', 'تخفیف (ریال)', 'کل تعرفه پرداخت نشده (ریال)', ] header_list2 = [ 'کل وزن زنده کشتار داخل استان(کیلوگرم)', 'وزن لاشه کشتار داخل استان(کیلوگرم)', 'وزن توزیع لاشه کشتار داخل استان(کیلوگرم)', 'تعرفه توزیع لاشه کشتار داخل استان(ریال)', 'وزن توزیع لاشه به خارج استان(کیلوگرم)', 'تعرفه توزیع لاشه به خارج استان(ریال)', 'وزن لاشه ورودی به استان(کیلوگرم)', 'تعرفه لاشه ورودی به استان(ریال)', 'وزن مرغ زنده ورودی به استان(کیلوگرم)', 'تعرفه مرغ زنده ورودی به استان(ریال)', ] header_list = [ 'ردیف', 'ماهیت', 'خریدار', 'کل تعرفه(ریال)', 'کل تعرفه پرداخت شده(ریال)', 'تخفیف(ریال)', 'کل تعرفه پرداخت نشده(ریال)', 'کل وزن زنده کشتار داخل استان(کیلوگرم)', 'کل وزن لاشه کشتار داخل استان(کیلوگرم)', 'کل توزیع لاشه داخل استان(کیلوگرم)', 'تعرفه لاشه داخل استان(ریال)', 'وزن توزیع لاشه به خارج استان(کیلوگرم)', 'تعرفه توزیع لاشه به خارج استان(ریال)', 'وزن لاشه ورودی به استان(کیلوگرم)', 'تعرفه لاشه ورودی به استان(ریال)', 'وزن مرغ زنده ورودی به استان(کیلوگرم)', 'تعرفه مرغ زنده ورودی به استان(ریال)', ] for col_num, option in enumerate(header_list, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=14, column=col_num, value=option) if option in ['کل تعرفه پرداخت نشده(ریال)']: cell.fill = PatternFill(start_color="76933C", fill_type="solid") else: cell.fill = PatternFill(start_color="31869B", fill_type="solid") cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.font = Font(size=10, bold=True, color='FFFFFF') worksheet.row_dimensions[13].height = 45 worksheet.column_dimensions[col_letter].width = 27 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) header_list5 = [ 'سهم', 'تعرفه توزیع لاشه داخل استان(ریال)', 'تعرفه توزیع لاشه خارج استان(ریال)', 'تعرفه لاشه ورودی به استان(ریال)', 'تعرفه مرغ زنده ورودی به استان(ریال)', 'تعرفه کل(ریال)', 'تعرفه پرداخت شده(ریال)', 'تعرفه پرداخت نشده(ریال)', ] create_header(worksheet, header_list5, 3, 8, height=35, width=18, border_style='thin') create_header(worksheet, header_list1, 4, 3, height=35, width=18, border_style='thin') create_header(worksheet, header_list2, 3, 5, height=35, width=18, border_style='thin') wage_type = WageType.objects.filter(en_name='province-kill-request').first() percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0, trash=False) for percentage_wage_type in percentages_wage_type: if percentage_wage_type.share_type.en_name == 'union': union_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name == 'company': company_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name == 'guilds': guilds_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name in ['city', 'wallet']: pass else: other_wage_percent = percentage_wage_type.percent / 100 type = 'total_wage_amount' share_type = 'amount' kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id') total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_buying_live_weight_amount = total_wage_type.filter(en_name='live-buy', trash=False).first().amount free_buying_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-buy', trash=False).first().amount free_sell_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount if 'date1' in request.GET: province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user__in=kill_houses, trash=False, archive_wage=False, return_to_province=False, state__in=('pending', 'accepted'), first_car_allocated_quantity=0, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2).order_by( 'id') kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q( Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False, trash=False, calculate_status=True, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2 ) chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2, trash=False, state='accepted') kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(date__date__gte=date1, date__date__lte=date2, kill_house__in=kill_houses, archive_wage=False, calculate_status=True, trash=False) kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(date__date__gte=date1, date__date__lte=date2, kill_house__in=kill_houses, archive_wage=False, calculate_status=True, trash=False) slaughter_transactions = InternalTransaction.objects.filter(date__date__gte=date1, date__date__lte=date2, kill_house__in=kill_houses, status='completed', trash=False) off = kill_houses.aggregate(total=Sum('off'))[ 'total'] or 0 total_paid_wage = slaughter_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 total_province_live_weight = province_kill_requests.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 total_province_live_weight += kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 total_out_selling_province_carcasses_weight = \ kill_house_free_sale_bar_info.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0 total_province_carcasses_weight = total_province_live_weight * 0.75 total_out_carcasses_buying_for_pure_province_carcasses_weight = \ kill_house_free_bar_info.aggregate(total=Sum('weight_of_carcasses'))['total'] or 0 total_pure_province_carcasses_weight = total_province_carcasses_weight - get_difference_carcasses_weight( kill_houses) total_out_live_buying_province_carcasses_weight = \ kill_house_free_bar_info.filter(buy_type='live').aggregate(total=Sum('live_weight'))['total'] or 0 total_out_carcasses_buying_province_carcasses_weight = \ kill_house_free_bar_info.filter(buy_type='carcass').aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 total_pure_province_carcasses_price = total_pure_province_carcasses_weight * province_live_wage_amount total_out_selling_province_carcasses_price = total_out_selling_province_carcasses_weight * free_sell_carcesses_weight_amount total_out_live_buying_province_carcasses_price = total_out_live_buying_province_carcasses_weight * free_buying_live_weight_amount total_out_carcasses_buying_province_carcasses_price = total_out_carcasses_buying_province_carcasses_weight * free_buying_carcesses_weight_amount total_price = total_pure_province_carcasses_price + total_out_selling_province_carcasses_price + total_out_live_buying_province_carcasses_price + total_out_carcasses_buying_province_carcasses_price percentages_wage_type = PercentageOfWageType.objects.filter(trash=False) union_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='union').first().percent / 100 company_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='company').first().percent / 100 guilds_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='guilds').first().percent / 100 other_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='other').first().percent / 100 union_free_buying_live_percent = percentages_wage_type.filter(wage_type__en_name='live-buy', share_type__en_name='union').first().percent / 100 union_free_buying_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-buy', share_type__en_name='union').first().percent / 100 company_free_buying_live_percent = percentages_wage_type.filter(wage_type__en_name='live-buy', share_type__en_name='company').first().percent / 100 company_free_buying_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-buy', share_type__en_name='company').first().percent / 100 guilds_free_buying_live_percent = percentages_wage_type.filter(wage_type__en_name='live-buy', share_type__en_name='guilds').first().percent / 100 guilds_free_buying_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-buy', share_type__en_name='guilds').first().percent / 100 other_free_buying_live_percent = percentages_wage_type.filter(wage_type__en_name='live-buy', share_type__en_name='other').first().percent / 100 other_free_buying_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-buy', share_type__en_name='other').first().percent / 100 union_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='union').first().percent / 100 company_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='company').first().percent / 100 guilds_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='guilds').first().percent / 100 other_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='other').first().percent / 100 union_province_kill_request_wage = total_pure_province_carcasses_price * union_province_kill_request_percent union_free_buying_live_wage = total_out_live_buying_province_carcasses_price * union_free_buying_live_percent union_free_buying_carcasses_wage = total_out_carcasses_buying_province_carcasses_price * union_free_buying_carcasses_percent union_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * union_free_sell_carcasses_percent union_total_wage = union_province_kill_request_wage + union_free_buying_live_wage + union_free_buying_carcasses_wage + union_free_sell_carcasses_wage union_total_paid_wage = slaughter_transactions.aggregate(total=Sum('union_share'))['total'] or 0 union_total_unpaid_wage = union_total_wage - union_total_paid_wage company_province_kill_request_wage = total_pure_province_carcasses_price * company_province_kill_request_percent company_free_buying_live_wage = total_out_live_buying_province_carcasses_price * company_free_buying_live_percent company_free_buying_carcasses_wage = total_out_carcasses_buying_province_carcasses_price * company_free_buying_carcasses_percent company_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * company_free_sell_carcasses_percent company_total_wage = company_province_kill_request_wage + company_free_buying_live_wage + company_free_buying_carcasses_wage + company_free_sell_carcasses_wage company_total_paid_wage = slaughter_transactions.aggregate(total=Sum('company_share'))['total'] or 0 # company_total_pure_paid_wage = company_total_paid_wage - (company_total_paid_wage * 0.08)) company_total_unpaid_wage = company_total_wage - company_total_paid_wage guilds_province_kill_request_wage = total_pure_province_carcasses_price * guilds_province_kill_request_percent guilds_free_buying_live_wage = total_out_live_buying_province_carcasses_price * guilds_free_buying_live_percent guilds_free_buying_carcasses_wage = total_out_carcasses_buying_province_carcasses_price * guilds_free_buying_carcasses_percent guilds_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * guilds_free_sell_carcasses_percent guilds_total_wage = guilds_province_kill_request_wage + guilds_free_buying_live_wage + guilds_free_buying_carcasses_wage + guilds_free_sell_carcasses_wage guilds_total_paid_wage = slaughter_transactions.aggregate(total=Sum('guilds_share'))['total'] or 0 guilds_total_unpaid_wage = guilds_total_wage - guilds_total_paid_wage other_province_kill_request_wage = total_pure_province_carcasses_price * other_province_kill_request_percent other_free_buying_live_wage = total_out_live_buying_province_carcasses_price * other_free_buying_live_percent other_free_buying_carcasses_wage = total_out_carcasses_buying_province_carcasses_price * other_free_buying_carcasses_percent other_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * other_free_sell_carcasses_percent other_total_wage = other_province_kill_request_wage + other_free_buying_live_wage + other_free_buying_carcasses_wage + other_free_sell_carcasses_wage other_total_paid_wage = slaughter_transactions.aggregate(total=Sum('other_share'))['total'] or 0 other_total_unpaid_wage = other_total_wage - other_total_paid_wage else: kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id') province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user__in=kill_houses, trash=False, archive_wage=False, return_to_province=False, state__in=('pending', 'accepted'), first_car_allocated_quantity=0).order_by('id') kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q( Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False, trash=False, calculate_status=True ) kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house__in=kill_houses, archive_wage=False, calculate_status=True, trash=False) kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter( kill_house__in=kill_houses, archive_wage=False, calculate_status=True, trash=False) slaughter_transactions = InternalTransaction.objects.filter( kill_house__in=kill_houses, status='completed', trash=False) off = kill_houses.aggregate(total=Sum('off'))[ 'total'] or 0 total_paid_wage = slaughter_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 total_province_live_weight = province_kill_requests.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 total_province_live_weight += kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 total_out_selling_province_carcasses_weight = \ kill_house_free_sale_bar_info.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0 total_province_carcasses_weight = total_province_live_weight * 0.75 total_out_carcasses_buying_for_pure_province_carcasses_weight = \ kill_house_free_bar_info.aggregate(total=Sum('weight_of_carcasses'))['total'] or 0 total_pure_province_carcasses_weight = total_province_carcasses_weight - get_difference_carcasses_weight( kill_houses) total_out_live_buying_province_carcasses_weight = \ kill_house_free_bar_info.filter(buy_type='live').aggregate(total=Sum('live_weight'))['total'] or 0 total_out_carcasses_buying_province_carcasses_weight = \ kill_house_free_bar_info.filter(buy_type='carcass').aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 total_pure_province_carcasses_price = total_pure_province_carcasses_weight * province_live_wage_amount total_out_selling_province_carcasses_price = total_out_selling_province_carcasses_weight * free_sell_carcesses_weight_amount total_out_live_buying_province_carcasses_price = total_out_live_buying_province_carcasses_weight * free_buying_live_weight_amount total_out_carcasses_buying_province_carcasses_price = total_out_carcasses_buying_province_carcasses_weight * free_buying_carcesses_weight_amount total_price = total_pure_province_carcasses_price + total_out_selling_province_carcasses_price + total_out_live_buying_province_carcasses_price + total_out_carcasses_buying_province_carcasses_price percentages_wage_type = PercentageOfWageType.objects.filter(trash=False) union_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='union').first().percent / 100 company_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='company').first().percent / 100 guilds_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='guilds').first().percent / 100 other_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='other').first().percent / 100 union_free_buying_live_percent = percentages_wage_type.filter(wage_type__en_name='live-buy', share_type__en_name='union').first().percent / 100 union_free_buying_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-buy', share_type__en_name='union').first().percent / 100 company_free_buying_live_percent = percentages_wage_type.filter(wage_type__en_name='live-buy', share_type__en_name='company').first().percent / 100 company_free_buying_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-buy', share_type__en_name='company').first().percent / 100 guilds_free_buying_live_percent = percentages_wage_type.filter(wage_type__en_name='live-buy', share_type__en_name='guilds').first().percent / 100 guilds_free_buying_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-buy', share_type__en_name='guilds').first().percent / 100 other_free_buying_live_percent = percentages_wage_type.filter(wage_type__en_name='live-buy', share_type__en_name='other').first().percent / 100 other_free_buying_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-buy', share_type__en_name='other').first().percent / 100 union_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='union').first().percent / 100 company_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='company').first().percent / 100 guilds_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='guilds').first().percent / 100 other_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='other').first().percent / 100 union_province_kill_request_wage = total_pure_province_carcasses_price * union_province_kill_request_percent union_free_buying_live_wage = total_out_live_buying_province_carcasses_price * union_free_buying_live_percent union_free_buying_carcasses_wage = total_out_carcasses_buying_province_carcasses_price * union_free_buying_carcasses_percent union_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * union_free_sell_carcasses_percent union_total_wage = union_province_kill_request_wage + union_free_buying_live_wage + union_free_buying_carcasses_wage + union_free_sell_carcasses_wage union_total_paid_wage = slaughter_transactions.aggregate(total=Sum('union_share'))['total'] or 0 union_total_unpaid_wage = union_total_wage - union_total_paid_wage company_province_kill_request_wage = total_pure_province_carcasses_price * company_province_kill_request_percent company_free_buying_live_wage = total_out_live_buying_province_carcasses_price * company_free_buying_live_percent company_free_buying_carcasses_wage = total_out_carcasses_buying_province_carcasses_price * company_free_buying_carcasses_percent company_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * company_free_sell_carcasses_percent company_total_wage = company_province_kill_request_wage + company_free_buying_live_wage + company_free_buying_carcasses_wage + company_free_sell_carcasses_wage company_total_paid_wage = slaughter_transactions.aggregate(total=Sum('company_share'))['total'] or 0 # company_total_pure_paid_wage = company_total_paid_wage - (company_total_paid_wage * 0.08)) company_total_unpaid_wage = company_total_wage - company_total_paid_wage guilds_province_kill_request_wage = total_pure_province_carcasses_price * guilds_province_kill_request_percent guilds_free_buying_live_wage = total_out_live_buying_province_carcasses_price * guilds_free_buying_live_percent guilds_free_buying_carcasses_wage = total_out_carcasses_buying_province_carcasses_price * guilds_free_buying_carcasses_percent guilds_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * guilds_free_sell_carcasses_percent guilds_total_wage = guilds_province_kill_request_wage + guilds_free_buying_live_wage + guilds_free_buying_carcasses_wage + guilds_free_sell_carcasses_wage guilds_total_paid_wage = slaughter_transactions.aggregate(total=Sum('guilds_share'))['total'] or 0 guilds_total_unpaid_wage = guilds_total_wage - guilds_total_paid_wage other_province_kill_request_wage = total_pure_province_carcasses_price * other_province_kill_request_percent other_free_buying_live_wage = total_out_live_buying_province_carcasses_price * other_free_buying_live_percent other_free_buying_carcasses_wage = total_out_carcasses_buying_province_carcasses_price * other_free_buying_carcasses_percent other_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * other_free_sell_carcasses_percent other_total_wage = other_province_kill_request_wage + other_free_buying_live_wage + other_free_buying_carcasses_wage + other_free_sell_carcasses_wage other_total_paid_wage = slaughter_transactions.aggregate(total=Sum('other_share'))['total'] or 0 other_total_unpaid_wage = other_total_wage - other_total_paid_wage values_list = [ total_price, total_paid_wage, off, total_price - (total_paid_wage + off) ] create_value(worksheet, values_list, 4, 4, border_style='thin') values_list2 = [ total_province_live_weight, total_province_carcasses_weight, total_pure_province_carcasses_weight, total_pure_province_carcasses_price, total_out_selling_province_carcasses_weight, total_out_selling_province_carcasses_price, total_out_carcasses_buying_province_carcasses_weight, total_out_carcasses_buying_province_carcasses_price, total_out_live_buying_province_carcasses_weight, total_out_live_buying_province_carcasses_price, ] create_value(worksheet, values_list2, 6, 3, border_style='thin') values_union = [ union_province_kill_request_wage, union_free_sell_carcasses_wage, union_free_buying_carcasses_wage, union_free_buying_live_wage, union_total_wage, union_total_paid_wage, union_total_unpaid_wage, ] create_value(worksheet, values_union, 9, 4, border_style='thin') values_company = [ company_province_kill_request_wage, company_free_sell_carcasses_wage, company_free_buying_carcasses_wage, company_free_buying_live_wage, company_total_wage, company_total_paid_wage, company_total_unpaid_wage, ] create_value(worksheet, values_company, 10, 4, border_style='thin') values_guild = [ guilds_province_kill_request_wage, guilds_free_sell_carcasses_wage, guilds_free_buying_carcasses_wage, guilds_free_buying_live_wage, guilds_total_wage, guilds_total_paid_wage, guilds_total_unpaid_wage, ] create_value(worksheet, values_guild, 11, 4, border_style='thin') values_others = [ other_province_kill_request_wage, other_free_sell_carcasses_wage, other_free_buying_carcasses_wage, other_free_buying_live_wage, other_total_wage, other_total_paid_wage, other_total_unpaid_wage, ] create_value(worksheet, values_others, 12, 4, border_style='thin') l = 15 m = 1 kill_houses = KillHouse.objects.filter(trash=False).exclude(out_province=True).order_by('id') if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=kill_houses ) ).filter(): ps = filterset_class(data=query, queryset=kill_houses) kill_houses = ps.filter() else: kill_houses = kill_houses all_finance_info_total_price = 0 all_total_paid_wage = 0 all_off = 0 all_unpaid = 0 finance_info_total_province_live_weight = 0 finance_info_total_province_carcasses_weight = 0 finance_info_total_pure_province_carcasses_price = 0 finance_info_total_out_selling_province_carcasses_weight = 0 finance_info_total_out_selling_province_carcasses_price = 0 finance_info_total_out_carcasses_buying_province_carcasses_weight = 0 finance_info_total_out_carcasses_buying_province_carcasses_price = 0 finance_info_total_out_live_buying_province_carcasses_weight = 0 finance_info_total_out_live_buying_province_carcasses_price = 0 finance_info_total_pure_province_carcasses_weight = 0 for obj in kill_houses: killer = 'کشتارگاه' if obj.killer == False else 'کشتارکن' if obj.killer == True and obj.type == 'exclusive': parent = KillHousePercentage.objects.get(kill_house=obj, trash=False) killer_type = f'کشتارکن اختصاصی {parent.kill_house_for_killer.name}' elif obj.killer == True and obj.type == 'public': killer_type = 'کشتارکن عمومی' else: killer_type = 'کشتارگاه' total_paid_wage = 0 if 'date1' in request.GET: finance_info = get_kill_house_finance_info_by_date(obj, date1, date2) else: finance_info = get_kill_house_finance_info(obj) slaughter_transactions = InternalTransaction.objects.filter( kill_house=obj, status='completed', trash=False) total_paid_wage += slaughter_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 if 'date1' in request.GET: province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=obj, state__in=('pending', 'accepted'), trash=False, return_to_province=False, first_car_allocated_quantity=0, archive_wage=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2 ).exclude(union_share=0, company_share=0, guilds_share=0).only( 'total_killed_weight', 'union_share', 'company_share', 'guilds_share', 'total_wage_amount', 'total_killed_quantity') freezing_province_kill_requests = province_kill_requests.filter( province_request__poultry_request__freezing=True).only('total_killed_weight', 'union_share', 'company_share', 'guilds_share', 'total_wage_amount', 'total_killed_quantity') kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killer=obj) & Q(killhouse_user=obj)) | Q( Q(killer__isnull=True) & Q(killhouse_user=obj)) | Q( Q(killer__isnull=True) | Q(killer=obj)), archive_wage=False, trash=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2 ).select_related('province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent', 'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent', 'province_kill_request__company_share_percent', 'accepted_real_quantity', 'accepted_real_quantity') kill_house_requests = kill_house_requests.filter(Q(killer=obj) | Q(killhouse_user=obj)).select_related( 'province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent', 'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent', 'province_kill_request__company_share_percent', 'accepted_real_quantity') freezing_kill_house_requests = kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=True).select_related( 'province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent', 'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent', 'province_kill_request__company_share_percent', 'accepted_real_quantity') free_bars = KillHouseFreeBarInformation.objects.filter(date__date__gte=date1, date__date__lte=date2, kill_house=obj, archive_wage=False, trash=False).only('live_weight', 'union_share', 'weight_of_carcasses', 'company_share', 'guilds_share', 'total_wage_amount') free_bars_live = free_bars.filter(buy_type='live', trash=False).only('live_weight', 'union_share', 'weight_of_carcasses', 'company_share', 'guilds_share', 'total_wage_amount') free_bars_carcases = free_bars.filter(buy_type='carcass', trash=False).only('live_weight', 'union_share', 'weight_of_carcasses', 'company_share', 'guilds_share', 'total_wage_amount' ) slaughter_transactions = InternalTransaction.objects.filter(date__date__gte=date1, date__date__lte=date2, kill_house=obj, status='completed', trash=False).only('union_share', 'company_share', 'guilds_share', 'amount') else: province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=obj, state__in=('pending', 'accepted'), trash=False, return_to_province=False, first_car_allocated_quantity=0, archive_wage=False, ).exclude(union_share=0, company_share=0, guilds_share=0).only( 'total_killed_weight', 'union_share', 'company_share', 'guilds_share', 'total_wage_amount', 'total_killed_quantity') freezing_province_kill_requests = province_kill_requests.filter( province_request__poultry_request__freezing=True).only('total_killed_weight', 'union_share', 'company_share', 'guilds_share', 'total_wage_amount', 'total_killed_quantity') kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killer=obj) & Q(killhouse_user=obj)) | Q( Q(killer__isnull=True) & Q(killhouse_user=obj)) | Q( Q(killer__isnull=True) | Q(killer=obj)), archive_wage=False, trash=False ).select_related('province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent', 'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent', 'province_kill_request__company_share_percent', 'accepted_real_quantity', 'accepted_real_quantity') kill_house_requests = kill_house_requests.filter(Q(killer=obj) | Q(killhouse_user=obj)).select_related( 'province_kill_request').only( 'accepted_real_weight', 'province_kill_request__union_share_percent', 'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent', 'province_kill_request__company_share_percent', 'accepted_real_quantity') freezing_kill_house_requests = kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=True).select_related( 'province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent', 'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent', 'province_kill_request__company_share_percent', 'accepted_real_quantity') free_bars = KillHouseFreeBarInformation.objects.filter(kill_house=obj, archive_wage=False, trash=False).only('live_weight', 'union_share', 'weight_of_carcasses', 'company_share', 'guilds_share', 'total_wage_amount') free_bars_live = free_bars.filter(buy_type='live', trash=False).only('live_weight', 'union_share', 'weight_of_carcasses', 'company_share', 'guilds_share', 'total_wage_amount') free_bars_carcases = free_bars.filter(buy_type='carcass', trash=False).only('live_weight', 'union_share', 'weight_of_carcasses', 'company_share', 'guilds_share', 'total_wage_amount' ) slaughter_transactions = InternalTransaction.objects.filter( kill_house=obj, status='completed', trash=False).only('union_share', 'company_share', 'guilds_share', 'amount') all_finance_info_total_price += finance_info['total_price'] all_total_paid_wage += total_paid_wage all_off += obj.off all_unpaid += finance_info['total_price'] - (total_paid_wage + obj.off) finance_info_total_province_live_weight += finance_info['total_province_live_weight'] finance_info_total_province_carcasses_weight += finance_info['total_province_carcasses_weight'] finance_info_total_pure_province_carcasses_weight += finance_info['total_pure_province_carcasses_weight'] finance_info_total_pure_province_carcasses_price += finance_info['total_pure_province_carcasses_price'] finance_info_total_out_selling_province_carcasses_weight += finance_info[ 'total_out_selling_province_carcasses_weight'] finance_info_total_out_selling_province_carcasses_price += finance_info[ 'total_out_selling_province_carcasses_price'] finance_info_total_out_carcasses_buying_province_carcasses_weight += finance_info[ 'total_out_carcasses_buying_province_carcasses_weight'] finance_info_total_out_carcasses_buying_province_carcasses_price += finance_info[ 'total_out_carcasses_buying_province_carcasses_price'] finance_info_total_out_live_buying_province_carcasses_weight += finance_info[ 'total_out_live_buying_province_carcasses_weight'] finance_info_total_out_live_buying_province_carcasses_price += finance_info[ 'total_out_live_buying_province_carcasses_price'] values_list3 = [ m, killer_type, killer + '(' + obj.name + ')', finance_info['total_price'], total_paid_wage, obj.off, finance_info['total_price'] - (total_paid_wage + obj.off), finance_info['total_province_live_weight'], finance_info['total_province_carcasses_weight'], finance_info['total_pure_province_carcasses_weight'], finance_info['total_pure_province_carcasses_price'], finance_info['total_out_selling_province_carcasses_weight'], finance_info['total_out_selling_province_carcasses_price'], finance_info['total_out_carcasses_buying_province_carcasses_weight'], finance_info['total_out_carcasses_buying_province_carcasses_price'], finance_info['total_out_live_buying_province_carcasses_weight'], finance_info['total_out_live_buying_province_carcasses_price'], ] create_value(worksheet, values_list3, l, 1, border_style='thin') l += 1 m += 1 if slaughter_transactions: if obj not in kill_house_list: kill_house_list.append(obj) list2 = [ 'مجموع==>', '', '', all_finance_info_total_price, all_total_paid_wage, all_off, all_unpaid, finance_info_total_province_live_weight, finance_info_total_province_carcasses_weight, finance_info_total_pure_province_carcasses_weight, finance_info_total_pure_province_carcasses_price, finance_info_total_out_selling_province_carcasses_weight, finance_info_total_out_selling_province_carcasses_price, finance_info_total_out_carcasses_buying_province_carcasses_weight, finance_info_total_out_carcasses_buying_province_carcasses_price, finance_info_total_out_live_buying_province_carcasses_weight, finance_info_total_out_live_buying_province_carcasses_price, ] create_value(worksheet, list2, l, 1, border_style='thin', color='yellow') for kill_house in kill_house_list: sheet_name = kill_house.name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') worksheet.column_dimensions[col_letter].width = 20.01 worksheet.row_dimensions[2].height = 27 worksheet.freeze_panes = worksheet['A3'] max_col = worksheet.max_column range_str = f'A2:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str l = 1 m = 1 if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() kill_house = KillHouse.objects.get(id=kill_house.id, trash=False) transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).exclude(guilds_share=0, company_share=0, union_share=0).order_by('id') else: kill_house = KillHouse.objects.get(key=kill_house.key, trash=False) transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), status='completed', trash=False).exclude(guilds_share=0, company_share=0, union_share=0).order_by('id') for transaction in transactions: if transaction.kill_house != None: fullname = transaction.kill_house.kill_house_operator.user.fullname mobile = transaction.kill_house.kill_house_operator.user.mobile else: fullname = transaction.chain_company.user.fullname mobile = transaction.chain_company.user.mobile date = convert_to_shamsi( datetime=transaction.date ) type = 'دستی' if transaction.transaction_type == 'wage-gateway-manual' else 'آنلاین' if request.GET['role'] == 'ProvinceOperator': amout = transaction.union_share elif request.GET['role'] == 'Company': amout = transaction.company_share elif request.GET['role'] == 'Guilds': amout = transaction.guilds_share else: amout = transaction.amount list1 = [ m, date, type, fullname, mobile, transaction.orderId, transaction.saleReferenceId, transaction.orderId, transaction.cardHolderPan, amout, transaction.union_share, transaction.company_share, transaction.guilds_share, transaction.other_share, ] l += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values m += 1 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 kill_house_total_transactions_wage_payid_excel(request): filterset_class = KillHouseFilterSet filterset_fields = [ 'name', 'kill_house_operator__user__fullname', 'kill_house_operator__user__mobile', 'system_address__city__name', ] date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None kill_house_list = [] excel_options = [ 'ردیف', 'ماهیت تراکنش', 'نوع تراکنش', 'تاریخ پرداخت', 'شماره پیگیری', 'شماره درخواست', 'پرداخت کننده', 'تلفن پرداخت کننده', 'شماره کارت', 'مبلغ کل', 'سهم اتحادیه(ریال)', 'سهم صنف(ریال)', 'سهم شرکت(ریال)', 'سهم دامپزشک(ریال)', ] output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) sheet_name = 'اطلاعات کلی' worksheet = workbook.create_sheet(sheet_name) if sheet_name == 'اطلاعات کلی': worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') if 'date1' in request.GET: from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) worksheet['B2'] = f'اطلاعات کلی تعرفه {from_date_1} تا {from_date_2}' merge_range1 = 'B2:C2' worksheet.merge_cells(merge_range1) worksheet['B2'].font = Font(color="C00000", bold=True) worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['B5'] = f'جزئیات ' worksheet['B5'].font = Font(color="C00000", bold=True) worksheet['B5'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) else: # worksheet['B2'] = 'اطلاعات کلی تعرفه(از 1403/01/01 به بعد)' worksheet['B2'].font = Font(color="C00000") worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = 'B2:C2' worksheet.merge_cells(merge_range1) worksheet['B5'] = f'جزئیات' worksheet['B5'].font = Font(color="C00000", bold=True) worksheet['B5'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = 'B8:C8' worksheet.merge_cells(merge_range1) worksheet['B8'] = 'پرداختی های کشتارگاه ها' worksheet['B8'].font = Font(color="C00000", bold=True) worksheet['B8'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) header_list1 = [ 'کل وزن', 'کل تعرفه (ریال)', 'کل تعرفه پرداخت شده (ریال)', 'کل تعرفه پرداخت نشده (ریال)', ] header_list2 = [ 'وزن کشتار روزانه (کیلوگرم)', 'تعرفه کشتار روزانه (ریال)', 'وزن منجمد (کیلوگرم)', 'تعرفه منجمد (ریال)', 'وزن زنجیره ها (کیلوگرم)', 'تعرفه زنجیره ها (ریال)', 'وزن مرغ زنده آزاد', 'تعرفه مرغ زنده آزاد', 'وزن لاشه آزاد', 'تعرفه لاشه آزاد', ] header_list = [ 'ردیف', 'خریدار', 'نام و نام خانوادگی مالک', 'تلفن مالک', 'شهر', 'تعداد تراکنش ', 'سهم شما از واریزی(ریال)', ] for col_num, option in enumerate(header_list, 4): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=8, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="31869B", fill_type="solid") cell.font = Font(size=10, bold=True, color='FFFFFF') worksheet.row_dimensions[8].height = 45 worksheet.column_dimensions[col_letter].width = 27 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) for col_num, option in enumerate(header_list1, 4): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='FFFFFF') worksheet.row_dimensions[2].height = 35 worksheet.column_dimensions[col_letter].width = 18 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) for col_num, option in enumerate(header_list2, 3): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=5, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='FFFFFF') worksheet.row_dimensions[5].height = 35 worksheet.column_dimensions[col_letter].width = 18 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) total_weight = 0 total_wage = 0 total_paid_wage = 0 union_total_paid_wage = 0 company_total_paid_wage = 0 guilds_total_paid_wage = 0 freezing_province_kill_requests_total_wage = 0 freezing_province_kill_requests_total_weight = 0 free_bars_live_total_wage = 0 free_bars_live_total_weight = 0 free_bars_carcases_total_wage = 0 free_bars_carcases_total_weight = 0 role = request.GET['role'] user = SystemUserProfile.objects.get(key=request.GET['key']) if role == 'KillHouse': kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first() province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=kill_house, state__in=('pending', 'accepted'), trash=False, return_to_province=False, first_car_allocated_quantity=0, archive_wage=False, ) freezing_province_kill_requests = province_kill_requests.filter( province_request__poultry_request__freezing=True) kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user=kill_house) & Q(killer=kill_house)) | Q( Q(killhouse_user=kill_house) & Q(killer__isnull=True)) | Q( Q(killhouse_user=kill_house) | Q(killer=kill_house)), archive_wage=False, trash=False ) freezing_kill_house_requests = kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=True) free_bars = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house, archive_wage=False, trash=False) free_bars_live = free_bars.filter(buy_type='live', trash=False) free_bars_carcases = free_bars.filter(buy_type='carcass', trash=False) province_kill_requests_total_wage = \ province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate( total=Sum('total_wage_amount'))[ 'total'] or 0 freezing_province_kill_request_total_wage = \ freezing_province_kill_requests.aggregate(total=Sum('total_wage_amount'))['total'] or 0 total_wage += province_kill_requests_total_wage + freezing_province_kill_request_total_wage province_kill_requests_total_weight = \ province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 freezing_province_kill_request_total_weight = \ freezing_province_kill_requests.aggregate(total=Sum('total_killed_weight'))['total'] or 0 total_weight += province_kill_requests_total_weight + freezing_province_kill_request_total_weight kill_house_reqest_total_wage = \ kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[ 'total'] or 0 freezing_kill_house_reqest_total_wage = \ freezing_kill_house_requests.aggregate( total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[ 'total'] or 0 total_wage += kill_house_reqest_total_wage + freezing_kill_house_reqest_total_wage kill_house_reqest_total_weight = kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 freezing_kill_house_reqest_total_weight = \ freezing_kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[ 'total'] or 0 total_weight += kill_house_reqest_total_weight + freezing_kill_house_reqest_total_weight free_bars_live_total_wage = free_bars_live.aggregate(total=Sum('total_wage_amount'))[ 'total'] or 0 total_wage += free_bars_live_total_wage free_bars_live_total_weight = free_bars_live.aggregate(total=Sum('live_weight'))[ 'total'] or 0 total_weight += free_bars_live_total_weight free_bars_carcases_total_wage = free_bars_carcases.aggregate(total=Sum('total_wage_amount'))[ 'total'] or 0 total_wage += free_bars_carcases_total_wage free_bars_carcases_total_weight = free_bars_carcases.aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 total_weight += free_bars_carcases_total_weight slaughter_transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), status='completed', trash=False) total_paid_wage += slaughter_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 elif role == 'ChainCompany': chain_company = ChainCompany.objects.get(user=user, trash=False) chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company, state='accepted', trash=False) chain_allocations_total_wage = chain_allocations.aggregate(total=Sum('total_wage_amount'))[ 'total'] or 0 total_wage += chain_allocations_total_wage chain_allocations_total_weight = chain_allocations.aggregate(total=Sum('weight'))[ 'total'] or 0 total_weight += chain_allocations_total_weight chain_company_transactions = InternalTransaction.objects.filter(chain_company=chain_company, status='completed', trash=False) total_paid_wage += chain_company_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 else: if role == 'ProvinceOperator': type = 'union_share' share_type = 'union_share' province_kill_requests = ProvinceKillRequest.objects.filter( state__in=('pending', 'accepted'), trash=False, first_car_allocated_quantity=0, return_to_province=False, archive_wage=False, union_share__gt=0) freezing_province_kill_requests = province_kill_requests.filter( province_request__poultry_request__freezing=True) kill_house_requests = KillHouseRequest.objects.filter(trash=False, archive_wage=False, province_kill_request__union_share__gt=0) freezing_kill_house_requests = kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=True) chain_allocations = ChainAllocation.objects.filter(union_share__gt=0, state='accepted', trash=False) free_bars = KillHouseFreeBarInformation.objects.filter(union_share__gt=0, archive_wage=False, trash=False) province_kill_requests_total_wage = \ province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate( total=Sum(type))[ 'total'] or 0 province_kill_requests_total_wage += \ kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=False).aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__union_share_percent') / 100)))[ 'total'] or 0 freezing_province_kill_requests_total_wage = freezing_province_kill_requests.aggregate(total=Sum(type))[ 'total'] or 0 freezing_province_kill_requests_total_wage += \ freezing_kill_house_requests.aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__union_share_percent') / 100)))[ 'total'] or 0 elif role == 'Guilds': type = 'guilds_share' share_type = 'guilds_share' province_kill_requests = ProvinceKillRequest.objects.filter( state__in=('pending', 'accepted'), trash=False, first_car_allocated_quantity=0, return_to_province=False, archive_wage=False, guilds_share__gt=0) freezing_province_kill_requests = province_kill_requests.filter( province_request__poultry_request__freezing=True) kill_house_requests = KillHouseRequest.objects.filter(trash=False, archive_wage=False, province_kill_request__guilds_share__gt=0) freezing_kill_house_requests = kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=True) chain_allocations = ChainAllocation.objects.filter(guilds_share__gt=0, state='accepted', trash=False) free_bars = KillHouseFreeBarInformation.objects.filter(guilds_share__gt=0, archive_wage=False, trash=False) province_kill_requests_total_wage = \ province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate( total=Sum(type))[ 'total'] or 0 province_kill_requests_total_wage += \ kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=False).aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__guilds_share_percent') / 100)))[ 'total'] or 0 freezing_province_kill_requests_total_wage = freezing_province_kill_requests.aggregate(total=Sum(type))[ 'total'] or 0 freezing_province_kill_requests_total_wage += \ freezing_kill_house_requests.aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__guilds_share_percent') / 100)))[ 'total'] or 0 elif role == 'Company': type = 'company_share' share_type = 'company_share' province_kill_requests = ProvinceKillRequest.objects.filter( state__in=('pending', 'accepted'), trash=False, first_car_allocated_quantity=0, return_to_province=False, archive_wage=False, company_share__gt=0) freezing_province_kill_requests = province_kill_requests.filter( province_request__poultry_request__freezing=True) kill_house_requests = KillHouseRequest.objects.filter(trash=False, archive_wage=False, province_kill_request__company_share__gt=0) freezing_kill_house_requests = kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=True) chain_allocations = ChainAllocation.objects.filter(company_share__gt=0, state='accepted', trash=False) free_bars = KillHouseFreeBarInformation.objects.filter(company_share__gt=0, archive_wage=False, trash=False) province_kill_requests_total_wage = \ province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate( total=Sum(type))[ 'total'] or 0 province_kill_requests_total_wage += \ kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=False).aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__company_share_percent') / 100)))[ 'total'] or 0 freezing_province_kill_requests_total_wage = freezing_province_kill_requests.aggregate(total=Sum(type))[ 'total'] or 0 freezing_province_kill_requests_total_wage += \ freezing_kill_house_requests.aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__company_share_percent') / 100)))[ 'total'] or 0 else: type = 'total_wage_amount' share_type = 'amount' province_kill_requests = ProvinceKillRequest.objects.filter( state__in=('pending', 'accepted'), trash=False, archive_wage=False, first_car_allocated_quantity=0, return_to_province=False).exclude(union_share=0, company_share=0, guilds_share=0) freezing_province_kill_requests = province_kill_requests.filter( province_request__poultry_request__freezing=True) kill_house_requests = KillHouseRequest.objects.filter(trash=False, archive_wage=False).exclude( province_kill_request__union_share=0, province_kill_request__company_share=0, province_kill_request__guilds_share=0) freezing_kill_house_requests = kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=True) chain_allocations = ChainAllocation.objects.filter(trash=False, state='accepted') free_bars = KillHouseFreeBarInformation.objects.filter(archive_wage=False, trash=False) total_slaughter_transactions = InternalTransaction.objects.filter(payer_type='kill_house', status='completed', trash=False) total_chain_company_transactions = InternalTransaction.objects.filter(payer_type='chain_company', status='completed', trash=False) union_province_kill_request_total_weight = \ province_kill_requests.filter(union_share__gt=0, province_request__poultry_request__freezing=False).aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 freezing_union_province_kill_request_total_weight = \ freezing_province_kill_requests.filter(union_share__gt=0).aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 union_province_kill_request_total_weight += \ kill_house_requests.filter(province_kill_request__union_share__gt=0, province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 freezing_union_province_kill_request_total_weight += \ freezing_kill_house_requests.filter(province_kill_request__union_share__gt=0).aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 union_province_kill_request_total_wage = \ province_kill_requests.filter(union_share__gt=0, province_request__poultry_request__freezing=False).aggregate( total=Sum('union_share'))[ 'total'] or 0 union_province_kill_request_total_wage += \ kill_house_requests.filter(province_kill_request__union_share__gt=0, province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__union_share_percent') / 100)))[ 'total'] or 0 freezing_union_province_kill_request_total_wage = \ freezing_province_kill_requests.filter(union_share__gt=0).aggregate(total=Sum('union_share'))[ 'total'] or 0 freezing_union_province_kill_request_total_wage += \ freezing_kill_house_requests.filter(province_kill_request__union_share__gt=0).aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__union_share_percent') / 100)))[ 'total'] or 0 union_chain_allocation_total_weight = \ chain_allocations.filter(union_share__gt=0).aggregate(total=Sum('weight'))[ 'total'] or 0 union_chain_allocation_total_wage = \ chain_allocations.filter(union_share__gt=0).aggregate(total=Sum('union_share'))[ 'total'] or 0 union_kill_house_free_live_bar_total_weight = \ free_bars.filter(buy_type='live', union_share__gt=0).aggregate(total=Sum('live_weight'))[ 'total'] or 0 union_kill_house_free_live_bar_total_wage = \ free_bars.filter(buy_type='live', union_share__gt=0).aggregate(total=Sum('union_share'))[ 'total'] or 0 union_kill_house_free_carcases_bar_total_weight = \ free_bars.filter(buy_type='carcass', union_share__gt=0).aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 union_kill_house_free_carcases_bar_total_wage = \ free_bars.filter(buy_type='carcass', union_share__gt=0).aggregate(total=Sum('union_share'))[ 'total'] or 0 union_total_paid_wage += \ total_slaughter_transactions.filter(union_share__gt=0).aggregate(total=Sum('union_share'))[ 'total'] or 0 union_total_paid_wage += \ total_chain_company_transactions.filter(union_share__gt=0).aggregate(total=Sum('union_share'))[ 'total'] or 0 union_total_weight = union_province_kill_request_total_weight + freezing_union_province_kill_request_total_weight + union_chain_allocation_total_weight + union_kill_house_free_live_bar_total_weight + union_kill_house_free_carcases_bar_total_weight union_total_wage = union_province_kill_request_total_wage + freezing_union_province_kill_request_total_wage + union_chain_allocation_total_wage + union_kill_house_free_live_bar_total_wage + union_kill_house_free_carcases_bar_total_wage union_total_unpaid_wage = union_total_wage - union_total_paid_wage company_province_kill_request_total_weight = \ province_kill_requests.filter(company_share__gt=0, province_request__poultry_request__freezing=False).aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 company_province_kill_request_total_weight += \ kill_house_requests.filter(province_kill_request__company_share__gt=0, province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 freezing_company_province_kill_request_total_weight = \ freezing_province_kill_requests.filter(company_share__gt=0).aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 freezing_company_province_kill_request_total_weight += \ freezing_kill_house_requests.filter(province_kill_request__company_share__gt=0).aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 company_province_kill_request_total_wage = \ province_kill_requests.filter(company_share__gt=0, province_request__poultry_request__freezing=False).aggregate( total=Sum('company_share'))[ 'total'] or 0 company_province_kill_request_total_wage += \ kill_house_requests.filter(province_kill_request__company_share__gt=0, province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__company_share_percent') / 100)))[ 'total'] or 0 freezing_company_province_kill_request_total_wage = \ freezing_province_kill_requests.filter(company_share__gt=0).aggregate(total=Sum('company_share'))[ 'total'] or 0 freezing_company_province_kill_request_total_wage += \ freezing_kill_house_requests.filter(province_kill_request__company_share__gt=0).aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__company_share_percent') / 100)))[ 'total'] or 0 company_chain_allocation_total_weight = \ chain_allocations.filter(company_share__gt=0).aggregate(total=Sum('weight'))[ 'total'] or 0 company_chain_allocation_total_wage = \ chain_allocations.filter(company_share__gt=0).aggregate(total=Sum('company_share'))[ 'total'] or 0 company_kill_house_free_live_bar_total_weight = \ free_bars.filter(buy_type='live', company_share__gt=0).aggregate(total=Sum('live_weight'))[ 'total'] or 0 company_kill_house_free_live_bar_total_wage = \ free_bars.filter(buy_type='live', company_share__gt=0).aggregate(total=Sum('company_share'))[ 'total'] or 0 company_kill_house_free_carcases_bar_total_weight = \ free_bars.filter(buy_type='carcass', company_share__gt=0).aggregate( total=Sum('weight_of_carcasses'))[ 'total'] or 0 company_kill_house_free_carcases_bar_total_wage = \ free_bars.filter(buy_type='carcass', company_share__gt=0).aggregate(total=Sum('company_share'))[ 'total'] or 0 company_total_paid_wage += \ total_slaughter_transactions.filter(company_share__gt=0).aggregate(total=Sum('company_share'))[ 'total'] or 0 company_total_paid_wage += \ total_chain_company_transactions.filter(company_share__gt=0).aggregate(total=Sum('company_share'))[ 'total'] or 0 company_total_weight = company_province_kill_request_total_weight + freezing_company_province_kill_request_total_weight + company_chain_allocation_total_weight + company_kill_house_free_live_bar_total_weight + company_kill_house_free_carcases_bar_total_weight company_total_wage = company_province_kill_request_total_wage + freezing_company_province_kill_request_total_wage + company_chain_allocation_total_wage + company_kill_house_free_live_bar_total_wage + company_kill_house_free_carcases_bar_total_wage company_total_unpaid_wage = company_total_wage - company_total_paid_wage guilds_province_kill_request_total_weight = \ province_kill_requests.filter(guilds_share__gt=0, province_request__poultry_request__freezing=False).aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 guilds_province_kill_request_total_weight += \ kill_house_requests.filter(province_kill_request__guilds_share__gt=0, province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 freezing_guilds_province_kill_request_total_weight = \ freezing_province_kill_requests.filter(guilds_share__gt=0).aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 freezing_guilds_province_kill_request_total_weight += \ freezing_kill_house_requests.filter(province_kill_request__guilds_share__gt=0).aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 guilds_province_kill_request_total_wage = \ province_kill_requests.filter(guilds_share__gt=0, province_request__poultry_request__freezing=False).aggregate( total=Sum('guilds_share'))[ 'total'] or 0 guilds_province_kill_request_total_wage += \ kill_house_requests.filter(province_kill_request__guilds_share__gt=0, province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__guilds_share_percent') / 100)))[ 'total'] or 0 freezing_guilds_province_kill_request_total_wage = \ freezing_province_kill_requests.filter(guilds_share__gt=0).aggregate(total=Sum('guilds_share'))[ 'total'] or 0 freezing_guilds_province_kill_request_total_wage += \ freezing_kill_house_requests.filter(province_kill_request__guilds_share__gt=0).aggregate(total=Sum( F('accepted_real_weight') * F('province_kill_request__wage') * ( F('province_kill_request__guilds_share_percent') / 100)))[ 'total'] or 0 guilds_chain_allocation_total_weight = \ chain_allocations.filter(guilds_share__gt=0).aggregate(total=Sum('weight'))[ 'total'] or 0 guilds_chain_allocation_total_wage = \ chain_allocations.filter(guilds_share__gt=0).aggregate(total=Sum('guilds_share'))[ 'total'] or 0 guilds_kill_house_free_live_bar_total_weight = \ free_bars.filter(buy_type='live', guilds_share__gt=0).aggregate(total=Sum('live_weight'))[ 'total'] or 0 guilds_kill_house_free_live_bar_total_wage = \ free_bars.filter(buy_type='live', guilds_share__gt=0).aggregate(total=Sum('guilds_share'))[ 'total'] or 0 guilds_kill_house_free_carcases_bar_total_weight = \ free_bars.filter(buy_type='carcass', guilds_share__gt=0).aggregate( total=Sum('weight_of_carcasses'))[ 'total'] or 0 guilds_kill_house_free_carcases_bar_total_wage = \ free_bars.filter(buy_type='carcass', guilds_share__gt=0).aggregate(total=Sum('guilds_share'))[ 'total'] or 0 guilds_total_paid_wage += \ total_slaughter_transactions.filter(guilds_share__gt=0).aggregate(total=Sum('guilds_share'))[ 'total'] or 0 guilds_total_paid_wage += \ total_chain_company_transactions.filter(guilds_share__gt=0).aggregate(total=Sum('guilds_share'))[ 'total'] or 0 guilds_total_weight = guilds_province_kill_request_total_weight + freezing_guilds_province_kill_request_total_weight + guilds_chain_allocation_total_weight + guilds_kill_house_free_live_bar_total_weight + guilds_kill_house_free_carcases_bar_total_weight guilds_total_wage = guilds_province_kill_request_total_wage + freezing_guilds_province_kill_request_total_wage + guilds_chain_allocation_total_wage + guilds_kill_house_free_live_bar_total_wage + guilds_kill_house_free_carcases_bar_total_wage guilds_total_unpaid_wage = guilds_total_wage - guilds_total_paid_wage province_kill_requests_total_wage = \ province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate( total=Sum(type))[ 'total'] or 0 province_kill_requests_total_wage += \ kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[ 'total'] or 0 freezing_province_kill_requests_total_wage = freezing_province_kill_requests.aggregate(total=Sum(type))[ 'total'] or 0 freezing_province_kill_requests_total_wage += \ freezing_kill_house_requests.aggregate( total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[ 'total'] or 0 free_bars_live = free_bars.filter(buy_type='live', trash=False) free_bars_carcases = free_bars.filter(buy_type='carcass', trash=False) total_wage += province_kill_requests_total_wage + freezing_province_kill_requests_total_wage province_kill_requests_total_weight = \ province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 province_kill_requests_total_weight += kill_house_requests.filter( province_kill_request__province_request__poultry_request__freezing=False).aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 freezing_province_kill_requests_total_weight = \ freezing_province_kill_requests.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 freezing_province_kill_requests_total_weight += \ freezing_kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[ 'total'] or 0 total_weight += province_kill_requests_total_weight + freezing_province_kill_requests_total_weight chain_allocations_total_wage = chain_allocations.aggregate(total=Sum(type))[ 'total'] or 0 total_wage += chain_allocations_total_wage chain_allocations_total_weight = chain_allocations.aggregate(total=Sum('weight'))[ 'total'] or 0 total_weight += chain_allocations_total_weight free_bars_live_total_wage = free_bars_live.aggregate(total=Sum(type))[ 'total'] or 0 total_wage += free_bars_live_total_wage free_bars_live_total_weight = free_bars_live.aggregate(total=Sum('live_weight'))[ 'total'] or 0 total_weight += free_bars_live_total_weight free_bars_carcases_total_wage = free_bars_carcases.aggregate(total=Sum(type))[ 'total'] or 0 total_wage += free_bars_carcases_total_wage free_bars_carcases_total_weight = free_bars_carcases.aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 total_weight += free_bars_carcases_total_weight slaughter_transactions = InternalTransaction.objects.filter(payer_type='kill_house', status='completed', trash=False) total_paid_wage += slaughter_transactions.aggregate(total=Sum(share_type))[ 'total'] or 0 chain_company_transactions = InternalTransaction.objects.filter(payer_type='chain_company', status='completed', trash=False) total_paid_wage += chain_company_transactions.aggregate(total=Sum(share_type))[ 'total'] or 0 values_list = [ total_weight, total_wage, total_paid_wage, total_wage - total_paid_wage, ] for item in range(len(values_list)): cell = worksheet.cell(row=3, column=item + 4, value=values_list[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) values_list2 = [ province_kill_requests_total_weight, province_kill_requests_total_wage, freezing_province_kill_requests_total_weight, freezing_province_kill_requests_total_wage, chain_allocations_total_weight, chain_allocations_total_wage, free_bars_live_total_weight, free_bars_live_total_wage, free_bars_carcases_total_weight, free_bars_carcases_total_wage, ] for item in range(len(values_list2)): cell = worksheet.cell(row=6, column=item + 3, value=values_list2[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) l = 9 m = 1 if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if request.GET['role'] == 'ProvinceOperator': kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter( date__date__gte=date1, date__date__lte=date2, status='completed', payer_type='kill_house', union_share__gt=0, trash=False).values( 'kill_house'), trash=False) elif request.GET['role'] == 'Company': kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter( date__date__gte=date1, date__date__lte=date2, status='completed', payer_type='kill_house', company_share__gt=0, trash=False).values( 'kill_house'), trash=False) elif request.GET['role'] == 'Guilds': kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter( date__date__gte=date1, date__date__lte=date2, status='completed', payer_type='kill_house', guilds_share__gt=0, trash=False).values( 'kill_house'), trash=False) else: kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter( date__date__gte=date1, date__date__lte=date2, payer_type='kill_house', status='completed', trash=False).values( 'kill_house'), trash=False) else: if request.GET['role'] == 'ProvinceOperator': kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter( status='completed', payer_type='kill_house', union_share__gt=0, trash=False).values( 'kill_house'), trash=False) elif request.GET['role'] == 'Company': kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter( status='completed', payer_type='kill_house', company_share__gt=0, trash=False).values( 'kill_house'), trash=False) elif request.GET['role'] == 'Guilds': kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter( status='completed', payer_type='kill_house', guilds_share__gt=0, trash=False).values( 'kill_house'), trash=False) else: kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter( status='completed', payer_type='kill_house', trash=False).values( 'kill_house'), trash=False) if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=kill_houses ) ).filter(): ps = filterset_class(data=query, queryset=kill_houses) kill_houses = ps.filter() else: kill_houses = kill_houses for obj in kill_houses: if 'date1' in request.GET: transactions = InternalTransaction.objects.filter( Q(kill_house=obj) | Q(parent_kill_house=obj), date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).order_by('id') else: transactions = InternalTransaction.objects.filter( Q(kill_house=obj) | Q(parent_kill_house=obj), status='completed', trash=False).order_by('id') total_paid_wage = 0 role = request.GET['role'] if role in ['KillHouse', 'SuperAdmin', 'AdminX', 'Supporter']: wage_type = 'amount' transactions = transactions elif role == 'ProvinceOperator': wage_type = 'union_share' transactions = transactions.filter( union_share__gt=0, ).order_by('id') elif role == 'Company': wage_type = 'company_share' transactions = transactions.filter( company_share__gt=0, ).order_by('id') elif role == 'Guilds': wage_type = 'guilds_share' transactions = transactions.filter( guilds_share__gt=0, ).order_by('id') else: transactions = transactions wage_type = 'wallet_share' if transactions: if obj not in kill_house_list: kill_house_list.append(obj) total_paid_wage += transactions.aggregate(total=Sum(wage_type))[ 'total'] or 0 killer = 'کشتارگاه' if obj.killer == False else 'کشتارکن' values_list3 = [ m, killer + '(' + obj.name + ')', obj.kill_house_operator.user.fullname, obj.kill_house_operator.user.mobile, obj.kill_house_operator.user.city.name, len(transactions), total_paid_wage, ] for item in range(len(values_list3)): cell = worksheet.cell(row=l, column=item + 4, value=values_list3[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_list3[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) l += 1 m += 1 for kill_house in kill_house_list: sheet_name = kill_house.name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') create_header_freez(worksheet, excel_options, 1, 6, 7, height=22, width=20.01) l = 5 m = 1 header_list = [ 'تعداد کل تراکنش ها', 'مبلغ کل تراکنش(ریال)', 'سهم کل اتحادیه(ریال)', 'سهم کل صنف(ریال)', 'سهم کل شرکت(ریال)', 'سهم کل دامپزشک(ریال)', ] create_header(worksheet, header_list, 5, 2, height=20) user = SystemUserProfile.objects.get(key=request.GET['key']) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if request.GET['role'] == 'KillHouse': kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first() transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).exclude(guilds_share=0, company_share=0, union_share=0).order_by('id') elif request.GET['role'] == 'ChainCompany': chain_company = ChainCompany.objects.get(user=user, trash=False) transactions = InternalTransaction.objects.filter( chain_company=chain_company, date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).exclude(guilds_share=0, company_share=0, union_share=0).order_by('id') else: if request.GET['role'] == 'ProvinceOperator': transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), date__date__gte=date1, date__date__lte=date2, union_share__gt=0, status='completed', trash=False).order_by('id') elif request.GET['role'] == 'Company': transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), date__date__gte=date1, date__date__lte=date2, company_share__gt=0, status='completed', trash=False).order_by('id') elif request.GET['role'] == 'Guilds': transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), date__date__gte=date1, date__date__lte=date2, guilds_share__gt=0, status='completed', trash=False).order_by('id') elif request.GET['role'] == 'SuperAdmin': transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).exclude(guilds_share=0, company_share=0, union_share=0).order_by('id') else: transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).order_by('id') else: if request.GET['role'] == 'KillHouse': kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first() transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), status='completed', trash=False).order_by('id') elif request.GET['role'] == 'ChainCompany': chain_company = ChainCompany.objects.get(user=user, trash=False) transactions = InternalTransaction.objects.filter( chain_company=chain_company, status='completed', trash=False).order_by('id') else: if request.GET['role'] == 'ProvinceOperator': transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), union_share__gt=0, status='completed', trash=False).order_by('id') elif request.GET['role'] == 'Company': transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), company_share__gt=0, status='completed', trash=False).order_by('id') elif request.GET['role'] == 'Guilds': transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), guilds_share__gt=0, status='completed', trash=False).order_by('id') elif request.GET['role'] == 'SuperAdmin': transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), status='completed', trash=False).exclude(guilds_share=0, company_share=0, union_share=0).order_by('id') else: transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), status='completed', trash=False).order_by('id') for transaction in transactions: if transaction.kill_house: killer_type = 'کشتارگاه' if transaction.kill_house.killer == False else 'کشتارکن' elif transaction.chain_company: killer_type = 'شرکت زنجیره' else: killer_type = 'خارج استان' l += 1 payer_date = jdatetime.date.fromgregorian( day=transaction.date.day, month=transaction.date.month, year=transaction.date.year ) if transaction.kill_house != None: fullname = transaction.kill_house.kill_house_operator.user.fullname mobile = transaction.kill_house.kill_house_operator.user.mobile elif transaction.chain_company is not None: fullname = transaction.chain_company.user.fullname mobile = transaction.chain_company.user.mobile else: fullname = transaction.user.fullname mobile = transaction.user.mobile type = 'دستی' if transaction.transaction_type == 'wage-gateway-manual' else 'آنلاین' list1 = [ m, killer_type, type, str(payer_date), transaction.refId, transaction.orderId, fullname, mobile, transaction.cardHolderPan, transaction.amount, transaction.union_share, transaction.guilds_share, transaction.company_share, transaction.other_share ] m += 1 create_value(worksheet, list1, l + 1, 1, border_style='thin') total_amount = \ transactions.aggregate(total=Sum('amount'))['total'] or 0 total_union_share = \ transactions.aggregate(total=Sum('union_share'))['total'] or 0 total_guilds_share = \ transactions.aggregate(total=Sum('guilds_share'))['total'] or 0 total_company_share = \ transactions.aggregate(total=Sum('company_share'))['total'] or 0 total_other_share = \ transactions.aggregate(total=Sum('other_share'))['total'] or 0 value_header_list = [ m - 1, total_amount, total_union_share, total_guilds_share, total_company_share, total_other_share, ] create_value(worksheet, value_header_list, 3, 5) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', total_amount, total_union_share, total_guilds_share, total_company_share, total_other_share, ] create_value(worksheet, list2, l + 3, 1, color='green') 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 kill_house_total_wage_excel_new(request): date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None user = SystemUserProfile.objects.get(key=request.GET['key']) kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first() sheet_names2 = [ 'اطلاعات کلی', 'تخصیصات بدون بار', 'بارهای روزانه', 'مرغ زنده خارج استان', 'خرید لاشه خارج استان', # 'فروش لاشه خارج استان', ] output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) wage_type = WageType.objects.filter(en_name='province-kill-request').first() total_check_wage = wage_type.amount percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0, trash=False) for percentage_wage_type in percentages_wage_type: if percentage_wage_type.share_type.en_name == 'union': union_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name == 'company': company_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name == 'guilds': guilds_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name in ['city', 'wallet']: pass else: other_wage_percent = percentage_wage_type.percent / 100 total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_buying_live_weight_amount = total_wage_type.filter(en_name='live-buy', trash=False).first().amount free_buying_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-buy', trash=False).first().amount free_sell_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount total_wage_information = TotalWageInformation.objects.filter(trash=False).first() if not total_wage_information: total_wage_information = TotalWageInformation.objects.create() serialized_wage_data = TotalWageInformationSerializer( total_wage_information, context={'request': request} ).data.get('wage_info', {}) serializer_finance_info = serialized_wage_data.get('finance_info') effective_wage_counting_type = serialized_wage_data.get('wage_counting_type', wage_counting_type) for name in sheet_names2: sheet_name = name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) if sheet_name == 'اطلاعات کلی': finance_info = serializer_finance_info or {} if not finance_info and date1 and date2: finance_info = get_kill_house_finance_info_by_date(kill_house, date1, date2) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') if 'date1' in request.GET: from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) excel_description(worksheet, 'A3', f'اطلاعات کلی تعرفه از تاریخ{from_date_1} تا {from_date_2}', color='red', row2='C3') excel_description(worksheet, 'A4', f'{kill_house.name}', color='red', row2='B4') if effective_wage_counting_type == 'carcass': header_list1 = [ 'کل وزن لاشه داخل استان', 'وزن مر غ زنده خارج از استان', 'وزن لاشه خرید خارج از استان', 'کل تعرفه', ] create_header(worksheet, header_list1, 4, 4, height=50, width=19, border_style='thin', color='C4D79B') value_list1 = [ finance_info.get('total_province_carcasses_weight', 0), finance_info.get('total_out_live_buying_province_carcasses_weight', 0), finance_info.get('total_out_carcasses_buying_province_carcasses_weight', 0), finance_info.get('total_price', 0), ] create_value(worksheet, value_list1, 5, 4, border_style='thin') header_list2 = [ 'تعرفه کشتار و توزیع داخل استان', 'تعرفه کشتار و توزیع خارج استان استان', 'تعرفه خرید لاشه خارج استان', 'تعرفه خرید مرغ زنده خارج استان', 'کل وزن زنده کشتار داخل استان(کیلوگرم)', 'وزن لاشه کشتار داخل استان(کیلوگرم)', 'وزن توزیع لاشه داخل استان(کیلوگرم)', 'تعرفه توزیع لاشه داخل استان(ریال)', 'وزن توزیع لاشه به خارج استان(کیلوگرم)', 'تعرفه توزیع لاشه به خارج استان(ریال)', 'وزن لاشه ورودی به استان(کیلوگرم)', 'تعرفه لاشه ورودی به استان(ریال)', 'وزن مرغ زنده ورودی به استان(کیلوگرم)', 'تعرفه مرغ زنده ورودی به استان(کیلوگرم)', ] create_header(worksheet, header_list2, 1, 9, height=50, width=19, border_style='thin', color='E26B0A') value_list2 = [ finance_info.get('province_live_wage_amount', 0), finance_info.get('free_sell_carcesses_weight_amount', 0), finance_info.get('free_buying_carcesses_weight_amount', 0), finance_info.get('free_buying_live_weight_amount', 0), finance_info.get('total_province_live_weight', 0), finance_info.get('total_province_carcasses_weight', 0), finance_info.get('total_pure_province_carcasses_weight', 0), finance_info.get('total_pure_province_carcasses_price', 0), finance_info.get('total_out_selling_province_carcasses_weight', 0), finance_info.get('total_out_selling_province_carcasses_price', 0), finance_info.get('total_out_carcasses_buying_province_carcasses_weight', 0), finance_info.get('total_out_carcasses_buying_province_carcasses_price', 0), finance_info.get('total_out_live_buying_province_carcasses_weight', 0), finance_info.get('total_out_live_buying_province_carcasses_price', 0), ] create_value(worksheet, value_list2, 10, 1, border_style='thin') else: header_list1 = [ 'کل وزن لاشه داخل استان', 'وزن مر غ زنده خارج از استان', 'وزن لاشه خرید خارج از استان', 'کل تعرفه', ] create_header(worksheet, header_list1, 4, 4, height=50, width=19, border_style='thin', color='C4D79B') value_list1 = [ finance_info.get('total_province_carcasses_weight', 0), finance_info.get('total_out_live_buying_province_carcasses_weight', 0), finance_info.get('total_out_carcasses_buying_province_carcasses_weight', 0), finance_info.get('total_price', 0), ] create_value(worksheet, value_list1, 5, 4, border_style='thin') header_list2 = [ 'تعرفه کشتار و توزیع داخل استان', 'تعرفه کشتار و توزیع خارج استان استان', 'تعرفه خرید لاشه خارج استان', 'تعرفه خرید مرغ زنده خارج استان', 'کل وزن زنده کشتار داخل استان(کیلوگرم)', # 'وزن لاشه کشتار داخل استان(کیلوگرم)', # 'وزن توزیع لاشه داخل استان(کیلوگرم)', 'تعرفه کشتار داخل استان(ریال)', 'وزن توزیع لاشه به خارج استان(کیلوگرم)', 'تعرفه توزیع لاشه به خارج استان(ریال)', 'وزن لاشه ورودی به استان(کیلوگرم)', 'تعرفه لاشه ورودی به استان(ریال)', 'وزن مرغ زنده ورودی به استان(کیلوگرم)', 'تعرفه مرغ زنده ورودی به استان(کیلوگرم)', ] create_header(worksheet, header_list2, 1, 9, height=50, width=19, border_style='thin', color='E26B0A') value_list2 = [ finance_info.get('province_live_wage_amount', 0), finance_info.get('free_sell_carcesses_weight_amount', 0), finance_info.get('free_buying_carcesses_weight_amount', 0), finance_info.get('free_buying_live_weight_amount', 0), finance_info.get('total_province_live_weight', 0), # finance_info['total_province_carcasses_weight'], finance_info.get('total_pure_province_carcasses_price', 0), # finance_info['total_pure_province_carcasses_price'], finance_info.get('total_out_selling_province_carcasses_weight', 0), finance_info.get('total_out_selling_province_carcasses_price', 0), finance_info.get('total_out_carcasses_buying_province_carcasses_weight', 0), finance_info.get('total_out_carcasses_buying_province_carcasses_price', 0), finance_info.get('total_out_live_buying_province_carcasses_weight', 0), finance_info.get('total_out_live_buying_province_carcasses_price', 0), ] create_value(worksheet, value_list2, 10, 1, border_style='thin') # excel_description(worksheet, 'D13', 'اطلاعات بار', size='16', row2='F13') # header_list3 = [ # 'تعداد بارهای ایجاد شده', # 'مجموع تعداد قطعه بارها', # 'مجموع وزن زنده بارها', # 'مجموع تعداد نهایی در کشتارگاه', # 'مجموع وزن نهایی در کشتار گاه', # 'ملاک قطعه کشتار شده', # 'ملاک وزن زنده کشتار شده', # 'تعرفه پایه', # 'وزن لاشه', # 'مجموع تعرفه های بار', # # ] # create_header(worksheet, header_list3, 1, 14, height=50, width=19, border_style='thin', color='0070C0') # kill_house_requests_quantity = \ # kill_house_requests.aggregate(total=Sum('quantity'))['total'] or 0 # kill_house_requests_accepted_real_weight = \ # kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 # kill_house_requests_accepted_real_quantity = \ # kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0 # kill_house_requests_wight = \ # kill_house_requests.aggregate(total=Sum( # F('quantity') * F('province_kill_request__province_request__poultry_request__Index_weight')))[ # 'total'] or 0 # # kill_house_requests_accepted_real_wight = \ # kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 # assignment = KillHouseAssignmentInformation.objects.filter( # kill_house_request__in=kill_house_requests, trash=False) # # assignment_net_weight = \ # assignment.aggregate(total=Sum('net_weight'))['total'] or 0 # assignment_real_quantity = \ # assignment.aggregate(total=Sum('real_quantity'))['total'] or 0 # value_list3 = [ # len(kill_house_requests), # kill_house_requests_quantity, # kill_house_requests_wight, # assignment_real_quantity, # assignment_net_weight, # kill_house_requests_accepted_real_quantity, # kill_house_requests_accepted_real_weight, # province_live_wage_type.amount, # kill_house_requests_accepted_real_wight * 0.75, # province_live_wage_type.amount * (kill_house_requests_accepted_real_wight * 0.75), # # ] # create_value(worksheet, value_list3, 15, 1, border_style='thin') # # excel_description(worksheet, 'B17', 'تخصیصات بدون بار', size='16', row2='F17') # header_list4 = [ # 'تعداد سفارشات', # 'تعداد کل', # 'وزن کل', # 'تعرفه', # 'وزن لاشه ملاک تعرفه', # 'کل تعرفه', # # ] # create_header(worksheet, header_list4, 2, 18, height=50, width=19, border_style='thin', color='00B050') # # province_kill_request = ProvinceKillRequest.objects.filter(killhouse_user=kill_house, # state__in=('pending', 'accepted'), # return_to_province=False, # archive_wage=False, # first_car_allocated_quantity=0, # kill_request__recive_date__date__gte=date1, # kill_request__recive_date__date__lte=date2, # trash=False).order_by( # 'kill_request__recive_date') # # total_weight = \ # province_kill_request.aggregate(total=Sum('total_killed_weight'))[ # 'total'] or 0 # total_killed_quantity = \ # province_kill_request.aggregate(total=Sum('total_killed_quantity'))[ # 'total'] or 0 # # value_list4 = [ # len(province_kill_request), # total_killed_quantity, # total_weight, # province_live_wage_type.amount, # total_weight * 0.75, # province_live_wage_type.amount * (total_weight * 0.75), # # ] # create_value(worksheet, value_list4, 19, 2, border_style='thin') # # excel_description(worksheet, 'C22', 'فروش لاشه خارج استان', size='16', row2='F22') # header_list5 = [ # 'تعداد کل لاشه', # 'حجم کل لاشه', # 'وزن کل لاشه', # 'تعرفه', # 'مبلغ کل تعرفه', # # ] # create_header(worksheet, header_list5, 3, 23, height=50, width=19, border_style='thin', color='B1A0C7') # free_sales = KillHouseFreeSaleBarInformation.objects.filter(trash=False, date__date__gte=date1, # date__date__lte=date2, # kill_house=kill_house).order_by('-date') # # total_quantity = free_sales.aggregate(total=Sum('number_of_carcasses'))[ # 'total'] or 0 # total_weight = free_sales.aggregate(total=Sum('weight_of_carcasses'))[ # 'total'] or 0 # # value_list5 = [ # len(free_sales), # total_quantity, # total_weight, # free_sell_carcesses_weight_wage_type.amount, # total_weight * free_sell_carcesses_weight_wage_type.amount, # ] # create_value(worksheet, value_list5, 24, 3, border_style='thin') # # excel_description(worksheet, 'C26', 'خرید مرغ زنده خارج استان', size='16', row2='F26') # header_list6 = [ # 'تعداد خریداران', # 'تعداد کل', # 'وزن کل', # 'تعرفه', # 'مبلغ کل', # # ] # create_header(worksheet, header_list6, 3, 27, height=50, width=19, border_style='thin') # kill_house_free_bar_info_live = kill_house_free_bar_info.filter(buy_type='live') # # total_quantity = \ # kill_house_free_bar_info_live.aggregate(total=Sum('quantity'))[ # 'total'] or 0 # total_weight = \ # kill_house_free_bar_info_live.aggregate(total=Sum('live_weight'))[ # 'total'] or 0 # # value_list6 = [ # len(kill_house_free_bar_info_live), # total_quantity, # total_weight, # free_buying_live_weight_wage_type.amount, # total_weight * free_buying_live_weight_wage_type.amount, # ] # create_value(worksheet, value_list6, 28, 3, border_style='thin') # # excel_description(worksheet, 'C30', 'خرید لاشه خارج استان', size='16', row2='F30') # header_list7 = [ # 'تعداد خرید', # 'وزن کل', # 'تعرفه', # 'مبلغ کل', # # ] # create_header(worksheet, header_list7, 3, 31, height=50, width=19, border_style='thin', color='C4D79B') # kill_house_free_bar_info_carcass = kill_house_free_bar_info.filter(buy_type='carcass') # total_weight = \ # kill_house_free_bar_info_carcass.aggregate(total=Sum('weight_of_carcasses'))[ # 'total'] or 0 # # value_list7 = [ # len(kill_house_free_bar_info_carcass), # total_weight, # free_buying_carcesses_weight_wage_type.amount, # total_weight * free_buying_carcesses_weight_wage_type.amount, # # ] # create_value(worksheet, value_list7, 32, 3, border_style='thin') elif sheet_name == 'تخصیصات بدون بار': worksheet['H3'] = 'در این قسمت تخصیصات فاقد بار نمایش داده میشود' merge_range1 = 'H3:K3' worksheet.merge_cells(merge_range1) worksheet['H3'].font = Font(color="C00000", bold=True) worksheet['H3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) if 'date1' in request.GET: province_kill_request = ProvinceKillRequest.objects.filter(killhouse_user=kill_house, state__in=('pending', 'accepted'), return_to_province=False, archive_wage=False, first_car_allocated_quantity=0, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, trash=False).order_by( 'kill_request__recive_date') else: province_kill_request = ProvinceKillRequest.objects.filter(killhouse_user=kill_house, state__in=('pending', 'accepted'), wage_pay=False, archive_wage=False, return_to_province=False, first_car_allocated_quantity=0, trash=False).order_by( 'kill_request__recive_date') if effective_wage_counting_type == 'carcass': header_list = [ 'تعداد سفارشات', 'تعداد کل', 'وزن کل', 'وزن لاشه ملاک تعرفه', 'جمع کل تعرفه', ] else: header_list = [ 'تعداد سفارشات', 'تعداد کل', 'وزن کل', 'وزن ملاک تعرفه', 'جمع کل تعرفه', ] for col_num, option in enumerate(header_list, 3): cell = worksheet.cell(row=3, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[3].height = 20.8 if effective_wage_counting_type == 'carcass': excel_options = [ 'ردیف', 'کد سفارش', 'مرغدار', 'تلفن مرغدار', 'شهر', 'تاریخ کشتار', 'محل کشتار', 'نژاد', 'تعداد(قطعه)', 'وزن(کیلوگرم)', 'میانگین وزنی(کیلوگرم)', 'وزن لاشه ملاک تعرفه ', 'تعرفه (ریال)', 'تعرفه تخصیص(ریال)', ] else: excel_options = [ 'ردیف', 'کد سفارش', 'مرغدار', 'تلفن مرغدار', 'شهر', 'تاریخ کشتار', 'محل کشتار', 'نژاد', 'تعداد(قطعه)', 'وزن(کیلوگرم)', 'میانگین وزنی(کیلوگرم)', 'وزن ملاک تعرفه ', 'تعرفه (ریال)', 'تعرفه تخصیص(ریال)', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str l = 6 m = 1 for province_kill in province_kill_request: kill_date_1 = shamsi_date(province_kill.province_request.poultry_request.send_date) if province_kill.kill_request.slaughter_house is not None: kill_place = province_kill.kill_request.slaughter_house.name else: kill_place = province_kill.kill_request.kill_house.name total_amount = province_kill.total_wage_amount if effective_wage_counting_type == 'carcass': list1 = [ m, str(province_kill.province_request.poultry_request.order_code), province_kill.province_request.poultry_request.poultry.unit_name, province_kill.province_request.poultry_request.poultry.user.mobile, province_kill.province_request.poultry_request.poultry.address.city.name, str(kill_date_1), kill_place, province_kill.province_request.poultry_request.hatching.chicken_breed, province_kill.total_killed_quantity, province_kill.total_killed_weight, province_kill.province_request.poultry_request.Index_weight, province_kill.total_killed_weight * 0.75, province_live_wage_amount, (province_kill.total_killed_weight * 0.75) * province_live_wage_amount, ] else: list1 = [ m, str(province_kill.province_request.poultry_request.order_code), province_kill.province_request.poultry_request.poultry.unit_name, province_kill.province_request.poultry_request.poultry.user.mobile, province_kill.province_request.poultry_request.poultry.address.city.name, str(kill_date_1), kill_place, province_kill.province_request.poultry_request.hatching.chicken_breed, province_kill.total_killed_quantity, province_kill.total_killed_weight, province_kill.province_request.poultry_request.Index_weight, province_kill.total_killed_weight, province_live_wage_amount, (province_kill.total_killed_weight) * province_live_wage_amount, ] for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') l += 1 m += 1 total_weight = \ province_kill_request.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 total_killed_quantity = \ province_kill_request.aggregate(total=Sum('total_killed_quantity'))[ 'total'] or 0 total_wage_amount = \ province_kill_request.aggregate(total=Sum('total_wage_amount'))[ 'total'] or 0 if effective_wage_counting_type == 'carcass': value_list = [ m - 1, total_killed_quantity, total_weight, total_weight * 0.75, (total_weight * 0.75) * province_live_wage_amount, ] else: value_list = [ m - 1, total_killed_quantity, total_weight, total_weight, (total_weight) * province_live_wage_amount, ] for item in range(len(value_list)): cell = worksheet.cell(row=4, column=item + 3, value=value_list[item]) value = value_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') if effective_wage_counting_type == 'carcass': list2 = [ 'مجموع==>', '', '', '', '', '', '', '', total_killed_quantity, total_weight, '', total_weight * 0.75, province_live_wage_amount, (total_weight * 0.75) * province_live_wage_amount, ] else: list2 = [ 'مجموع==>', '', '', '', '', '', '', '', total_killed_quantity, total_weight, '', total_weight, province_live_wage_amount, (total_weight) * province_live_wage_amount, ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'بارهای روزانه': filterset_class = KillHouseRequestFilterSet filterset_fields = [ 'killhouse_user__kill_house_operator__user__fullname', 'killhouse_user__kill_house_operator__user__mobile', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__order_code', 'province_request__poultry_request__order_code', 'bar_code', ] filtered_kill_reqs = KillHouseRequest.objects.filter(Q(killhouse_user=kill_house) | Q(killer=kill_house), trash=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2).order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('province_kill_request__wage', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer').values('message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer', 'province_kill_request__wage', ) if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=filtered_kill_reqs ) ).filter(): ps = filterset_class(data=query, queryset=filtered_kill_reqs) filtered_kill_reqs = ps.filter() poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values( 'province_request__poultry_request')) .only('quantity', 'Index_weight')).annotate( total_quantity=Sum('quantity'), total_weight=Sum(F('quantity') * F('Index_weight')) ) total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] if effective_wage_counting_type == 'carcass': excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'کشتار', 'کدسفارش مرغدار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', 'کشتارکن اختصاصی', 'تلفن کشتارکن اختصاصی', ' محل کشتار ', 'نوع تخصیص', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'وزن ملاک تعرفه', 'تعرفه(ریال)', 'تعرفه کل بار', ] else: excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'کشتار', 'کدسفارش مرغدار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', 'کشتارکن اختصاصی', 'تلفن کشتارکن اختصاصی', ' محل کشتار ', 'نوع تخصیص', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'وزن ملاک تعرفه', 'تعرفه(ریال)', 'تعرفه کل بار', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str if effective_wage_counting_type == 'carcass': header_list = [ 'تعداد بارهای ایجاد شده', 'تعداد بارهای دارای کشتارکن اختصاصی', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', ' قطعه کشتار شده', ' وزن کشتار شده', 'وزن لاشه ملاک تعرفه', 'مجموع تعرفه های بار', ] else: header_list = [ 'تعداد بارهای ایجاد شده', 'تعداد بارهای دارای کشتارکن اختصاصی', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', ' قطعه کشتار شده', ' وزن کشتار شده', 'وزن ملاک تعرفه', 'مجموع تعرفه های بار', ] for col_num, option in enumerate(header_list, 9): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 worksheet['B1'] = f'گزارش بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی' if filtered_kill_reqs.exists(): name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name'] worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 all_quantity = 0 all_real_quantity = 0 all_net_weighte = 0 all_weighte = 0 all_vet_state_accepted = len( filtered_kill_reqs.filter(vet_state='accepted')) bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True') accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get( 'total_quantity', 0) accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get( 'total_quantity', 0) all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate( total_quantity=Sum('vet_accepted_real_quantity')).get( 'total_quantity', 0) all_vet_accepted_real_weight = filtered_kill_reqs.aggregate( total_quantity=Sum('vet_accepted_real_weight')).get( 'total_quantity', 0) killer_exclusive = 0 total_amount = 0 weight_amount = 0 if filtered_kill_reqs: for kill in filtered_kill_reqs: if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' l += 1 date_of_inner_bar = '-' vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'), trash=False).select_related('vet__user').only( 'vet__user__fullname', 'vet__user__mobile').values( 'vet__user__fullname', 'vet__user__mobile').first() vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-' vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-' kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'), trash=False).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only( 'create_date').values( 'create_date').first() kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' code = kill.get('clearance_code') if kill.get('clearance_code') else '-' if kill.get('quantity'): quantity = kill.get('quantity') all_quantity += quantity else: quantity = '-' send_date = kill.get('province_request__poultry_request__send_date') date_of_poultry_request = jdatetime.date.fromgregorian( day=send_date.day, month=send_date.month, year=send_date.year ) killers = 'کشتارکن' name_killer_exclusive = '-' mobile_killer_exclusive = '-' if kill.get('killhouse_user__killer') == False: killers = 'کشتارگاه' if kill.get('killer') != None: name_killer_exclusive = kill['killer__name'] mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile']) killer_exclusive += 1 assignment = KillHouseAssignmentInformation.objects.filter( kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight', 'real_quantity').values( 'net_weight', 'real_quantity', 'create_date').first() if assignment: net_weighte = assignment.get('net_weight') all_net_weighte += net_weighte real_quantity = assignment.get('real_quantity') all_real_quantity += real_quantity vet_check_date = assignment.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) else: net_weighte = '-' real_quantity = '-' if vet_checks: vet_check_date = vet_checks.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) if kill.get('kill_request__slaughter_house') is not None: kill_place = kill.get('kill_request__slaughter_house__name') else: kill_place = '-' vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-' vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-' weight = kill.get('quantity') * kill.get( 'province_kill_request__province_request__poultry_request__Index_weight') all_weighte += weight quarantine_quantity = '-' if kill['quarantine_quantity'] != None: quarantine_quantity = kill['quarantine_quantity'] else: if kill['quarantine_code_state'] == 'contradiction': quarantine_quantity = 'مغایرت کد رهگیری' elif kill['quarantine_code_state'] == 'noclearance': quarantine_quantity = 'فاقد کد رهگیری' elif kill['quarantine_code_state'] == 'notconfirmed': quarantine_quantity = 'عدم تایید راهداری' elif kill['quarantine_code_state'] == 'merge': quarantine_quantity = 'ادغام' sale_type = 'دولتی' if kill[ 'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد' if kill['province_kill_request__province_request__poultry_request__union'] == True: type = 'فروش آزاد' elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' else: type = 'اتحادیه' age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی' if kill['message'] is not None: state_delete = 'بار حذف شده' else: state_delete = 'فعال' if effective_wage_counting_type == 'carcass': accepted_real_weight_kill = kill['accepted_real_weight'] * 0.75 total_amount += (kill['accepted_real_weight'] * 0.75) * province_live_wage_amount weight_amount += kill['accepted_real_weight'] * 0.75 else: total_amount += (kill['accepted_real_weight']) * province_live_wage_amount weight_amount += kill['accepted_real_weight'] accepted_real_weight_kill = kill['accepted_real_weight'] list1 = [ m, str(kill.get('bar_code')), str(date_of_poultry_request), freez_state, str(kill.get('province_request__poultry_request__order_code')), kill.get('province_request__poultry_request__poultry__unit_name'), str(kill.get('province_request__poultry_request__poultry__user__mobile')), kill.get('province_request__poultry_request__poultry__user__city__name'), sale_type, age, kill.get('province_request__poultry_request__amount') if kill.get( 'province_request__poultry_request__amount') else '-', kill.get('province_request__poultry_request__chicken_breed'), vet_farm_name, vet_farm_mobile, killers, kill.get('killhouse_user__name'), kill.get('killhouse_user__kill_house_operator__user__mobile'), kill.get('killhouse_user__system_address__city__name'), name_killer_exclusive, mobile_killer_exclusive, kill_place, type, kill_house_vet_name, kill_house_vet_mobile, kill.get('add_car__driver__driver_name'), kill.get('add_car__driver__driver_mobile'), kill.get('add_car__driver__type_car'), str(kill.get('traffic_code')), quantity, weight, code, quarantine_quantity, state, str(date_of_inner_bar), vet_quantity, vet_wight, real_quantity, net_weighte, kill['accepted_real_quantity'], kill['accepted_real_weight'], accepted_real_weight_kill, province_live_wage_amount, (accepted_real_weight_kill) * province_live_wage_amount, ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False)) all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get( 'total_quantity', 0) has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False)) value_header_list = [ len(filtered_kill_reqs), killer_exclusive, all_quantity, all_weighte, all_real_quantity, all_net_weighte, accepted_real_quantity if accepted_real_quantity != None else 0, accepted_real_wight if accepted_real_wight != None else 0, weight_amount, total_amount ] for item in range(len(value_header_list)): cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item]) value = value_header_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_kill_request_quantity, all_weighte, '', all_quarantine_quantity if all_quarantine_quantity != None else 0, '', '', all_vet_accepted_real_quantity, all_vet_accepted_real_weight, all_real_quantity, all_net_weighte, accepted_real_quantity if accepted_real_quantity != None else 0, accepted_real_wight if accepted_real_wight != None else 0, weight_amount, province_live_wage_amount, total_amount, ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'مرغ زنده خارج استان': date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) type = 'live' date_type = 'buy' bar_state = request.GET.get('bar_state') kill_house_free_bar_info_list = [] role = request.GET.get('role') kill_houses = None order_by_type = 'create_date' if role in ['KillHouse', 'KillHouseVet']: if role == 'KillHouse': kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False) else: kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house', flat=True) kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() filters = { 'register_date__date__gte': date1, 'register_date__date__lte': date2, 'trash': False, } else: filters = { 'trash': False } if kill_houses is not None: filters['kill_house__in'] = kill_houses if type: filters['buy_type'] = type if type == 'live': if bar_state: if bar_state == 'entered': filters['weight_of_carcasses__gt'] = 0 else: filters['weight_of_carcasses'] = 0 kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(order_by_type) excel_options = [ 'ردیف', 'کدسفارش', 'تاریخ خرید', 'ماهیت خریدار', 'خریدار', 'تلفن خریدار', 'فروشنده', 'تلفن فروشنده', 'نوع خرید', 'استان/شهر', 'دامپزشک فارم', 'تلفن دامپزشک فارم', 'وضعیت دامپزشک', 'ماشین', 'راننده', 'تلفن راننده', 'کدقرنطینه', 'تعداد قطعه زنده', 'وزن زنده (کیلوگرم)', 'تعداد لاشه', 'وزن لاشه (کیلوگرم)', 'حجم تایید شده', 'وزن تایید شده', 'تایید/رد کننده', 'تاریخ تایید/ رد', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) header_list2 = [ 'تعداد بارها', ' تعداد بار های درانتظار تایید', 'مجموع قطعه زنده در انتظار تایید', 'مجموع وزن زنده (کیلوگرم) درانتظار تایید', 'مجموع تعداد لاشه درانتظار تایید', 'مجموع وزن لاشه (کیلوگرم) درانتظار تایید', ' تعداد بار های رد شده', 'مجموع قطعه زنده رد شده', 'مجموع وزن زنده (کیلوگرم) رد شده', 'مجموع تعداد لاشه رد شده', 'مجموع وزن لاشه (کیلوگرم) رد شده', ' تعداد بار های تایید شده', 'مجموع قطعه زنده تایید شده', 'مجموع وزن زنده (کیلوگرم) تایید شده', 'مجموع تعداد لاشه تایید شده', 'مجموع وزن لاشه (کیلوگرم) تایید شده', 'حجم تایید شده دامپزشک', 'وزن تایید شده دامپزشک', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str type1 = 'زنده' if type == 'live' else 'لاشه' worksheet['B1'] = f'گزارش بار {type1} خرید از استان' if kill_house_free_bar_info.exists(): name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name \ if kill_house_free_bar_info.first() else '' worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if kill_house_free_bar_info: for kill in kill_house_free_bar_info: l += 1 if kill.kill_house_vet_state == 'accepted': state = 'تایید شده' elif kill.kill_house_vet_state == 'pending': state = 'درانتظار تایید' else: state = 'رد شده' if kill.buy_type == 'live': buy_type = 'زنده' else: buy_type = 'لاشه' date_of_buy = jdatetime.date.fromgregorian( day=kill.date.day, month=kill.date.month, year=kill.date.year ) if kill.date_of_accept_reject: date_of_reject_accepted = jdatetime.date.fromgregorian( day=kill.date_of_accept_reject.day, month=kill.date_of_accept_reject.month, year=kill.date_of_accept_reject.year ) else: date_of_reject_accepted = '-' if kill.exclusive_killer: killer_type = f'کشتارکن اختصاصی {kill.kill_house.name}' kill_house_name = kill.exclusive_killer.name kill_house_mobile = kill.exclusive_killer.kill_house_operator.user.mobile elif kill.kill_house.killer == True and kill.kill_house.type == 'public': killer_type = 'کشتارکن عمومی' kill_house_name = kill.kill_house.name kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile else: killer_type = 'کشتارگاه' kill_house_name = kill.kill_house.name kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile bar_code = str(kill.bar_code) if kill.bar_code else '-' list1 = [ m, bar_code, str(date_of_buy), killer_type, kill_house_name, kill_house_mobile, kill.poultry_name, kill.poultry_mobile, buy_type, f'{kill.province} / {kill.city}', kill.vet_farm_name, kill.vet_farm_mobile, state, kill.car, kill.driver_name, kill.driver_mobile, kill.bar_clearance_code, kill.quantity, kill.live_weight, kill.number_of_carcasses, kill.weight_of_carcasses, kill.kill_house_vet_quantity, kill.kill_house_vet_weight, kill.acceptor_rejector, str(date_of_reject_accepted) ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) bar_pending = kill_house_free_bar_info.filter(kill_house_vet_state='pending') bar_pending_quantity = bar_pending.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_pending_live_weight = bar_pending.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_pending_number_of_carcasses = bar_pending.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_pending_weight_of_carcasses = bar_pending.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected') bar_rejected_quantity = bar_rejected.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_rejected_live_weight = bar_rejected.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_rejected_number_of_carcasses = bar_rejected.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_rejected_weight_of_carcasses = bar_rejected.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted') bar_accepted_quantity = bar_accepted.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_accepted_live_weight = bar_accepted.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_accepted_number_of_carcasses = bar_accepted.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_accepted_weight_of_carcasses = bar_accepted.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_accepted_kill_house_vet_quantity = bar_accepted.aggregate( total_quantity=Sum('kill_house_vet_quantity')).get( 'total_quantity') or 0 bar_accepted_kill_house_vet_weight = bar_accepted.aggregate( total_quantity=Sum('kill_house_vet_weight')).get( 'total_quantity') or 0 bar_quantity = kill_house_free_bar_info.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_live_weight = kill_house_free_bar_info.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_number_of_carcasses = kill_house_free_bar_info.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_weight_of_carcasses = kill_house_free_bar_info.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_kill_house_vet_quantity = kill_house_free_bar_info.aggregate( total_quantity=Sum('kill_house_vet_quantity')).get( 'total_quantity') or 0 bar_kill_house_vet_weight = kill_house_free_bar_info.aggregate( total_quantity=Sum('kill_house_vet_weight')).get( 'total_quantity') or 0 value_header_list2 = [ m - 1, len(bar_pending), int(bar_pending_quantity), int(bar_pending_live_weight), int(bar_pending_number_of_carcasses), int(bar_pending_weight_of_carcasses), len(bar_rejected), int(bar_rejected_quantity), int(bar_rejected_live_weight), int(bar_rejected_number_of_carcasses), int(bar_rejected_weight_of_carcasses), len(bar_accepted), int(bar_accepted_quantity), int(bar_accepted_live_weight), int(bar_accepted_number_of_carcasses), int(bar_accepted_weight_of_carcasses), int(bar_accepted_kill_house_vet_quantity), int(bar_accepted_kill_house_vet_weight) ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', bar_quantity, bar_live_weight, int(bar_number_of_carcasses), int(bar_weight_of_carcasses), int(bar_kill_house_vet_quantity), bar_kill_house_vet_weight, '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'خرید لاشه خارج استان': date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) type = 'carcass' date_type = 'buy' bar_state = request.GET.get('bar_state') kill_house_free_bar_info_list = [] role = request.GET.get('role') kill_houses = None order_by_type = 'create_date' if role in ['KillHouse', 'KillHouseVet']: if role == 'KillHouse': kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False) else: kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house', flat=True) kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() filters = { 'create_date__date__gte': date1, 'create_date__date__lte': date2, 'trash': False, } else: filters = { 'trash': False } if kill_houses is not None: filters['kill_house__in'] = kill_houses if type: filters['buy_type'] = type if type == 'live': if bar_state: if bar_state == 'entered': filters['weight_of_carcasses__gt'] = 0 else: filters['weight_of_carcasses'] = 0 kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(order_by_type) excel_options = [ 'ردیف', 'کدسفارش', 'تاریخ خرید', 'ماهیت خریدار', 'خریدار', 'تلفن خریدار', 'فروشنده', 'تلفن فروشنده', 'نوع خرید', 'استان/شهر', 'دامپزشک فارم', 'تلفن دامپزشک فارم', 'وضعیت دامپزشک', 'ماشین', 'راننده', 'تلفن راننده', 'کدقرنطینه', 'تعداد قطعه زنده', 'وزن زنده (کیلوگرم)', 'تعداد لاشه', 'وزن لاشه (کیلوگرم)', 'حجم تایید شده', 'وزن تایید شده', 'تایید/رد کننده', 'تاریخ تایید/ رد', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) header_list2 = [ 'تعداد بارها', ' تعداد بار های درانتظار تایید', 'مجموع قطعه زنده در انتظار تایید', 'مجموع وزن زنده (کیلوگرم) درانتظار تایید', 'مجموع تعداد لاشه درانتظار تایید', 'مجموع وزن لاشه (کیلوگرم) درانتظار تایید', ' تعداد بار های رد شده', 'مجموع قطعه زنده رد شده', 'مجموع وزن زنده (کیلوگرم) رد شده', 'مجموع تعداد لاشه رد شده', 'مجموع وزن لاشه (کیلوگرم) رد شده', ' تعداد بار های تایید شده', 'مجموع قطعه زنده تایید شده', 'مجموع وزن زنده (کیلوگرم) تایید شده', 'مجموع تعداد لاشه تایید شده', 'مجموع وزن لاشه (کیلوگرم) تایید شده', 'حجم تایید شده دامپزشک', 'وزن تایید شده دامپزشک', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str type1 = 'زنده' if type == 'live' else 'لاشه' worksheet['B1'] = f'گزارش بار {type1} خرید از استان' if kill_house_free_bar_info.exists(): name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name \ if kill_house_free_bar_info.first() else '' worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if kill_house_free_bar_info: for kill in kill_house_free_bar_info: l += 1 if kill.kill_house_vet_state == 'accepted': state = 'تایید شده' elif kill.kill_house_vet_state == 'pending': state = 'درانتظار تایید' else: state = 'رد شده' if kill.buy_type == 'live': buy_type = 'زنده' else: buy_type = 'لاشه' date_of_buy = jdatetime.date.fromgregorian( day=kill.date.day, month=kill.date.month, year=kill.date.year ) if kill.date_of_accept_reject: date_of_reject_accepted = jdatetime.date.fromgregorian( day=kill.date_of_accept_reject.day, month=kill.date_of_accept_reject.month, year=kill.date_of_accept_reject.year ) else: date_of_reject_accepted = '-' if kill.exclusive_killer: killer_type = f'کشتارکن اختصاصی {kill.kill_house.name}' kill_house_name = kill.exclusive_killer.name kill_house_mobile = kill.exclusive_killer.kill_house_operator.user.mobile elif kill.kill_house.killer == True and kill.kill_house.type == 'public': killer_type = 'کشتارکن عمومی' kill_house_name = kill.kill_house.name kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile else: killer_type = 'کشتارگاه' kill_house_name = kill.kill_house.name kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile bar_code = str(kill.bar_code) if kill.bar_code else '-' list1 = [ m, bar_code, str(date_of_buy), killer_type, kill_house_name, kill_house_mobile, kill.poultry_name, kill.poultry_mobile, buy_type, f'{kill.province} / {kill.city}', kill.vet_farm_name, kill.vet_farm_mobile, state, kill.car, kill.driver_name, kill.driver_mobile, kill.bar_clearance_code, kill.quantity, kill.live_weight, kill.number_of_carcasses, kill.weight_of_carcasses, kill.kill_house_vet_quantity, kill.kill_house_vet_weight, kill.acceptor_rejector, str(date_of_reject_accepted) ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) bar_pending = kill_house_free_bar_info.filter(kill_house_vet_state='pending') bar_pending_quantity = bar_pending.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_pending_live_weight = bar_pending.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_pending_number_of_carcasses = bar_pending.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_pending_weight_of_carcasses = bar_pending.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected') bar_rejected_quantity = bar_rejected.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_rejected_live_weight = bar_rejected.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_rejected_number_of_carcasses = bar_rejected.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_rejected_weight_of_carcasses = bar_rejected.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted') bar_accepted_quantity = bar_accepted.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_accepted_live_weight = bar_accepted.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_accepted_number_of_carcasses = bar_accepted.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_accepted_weight_of_carcasses = bar_accepted.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_accepted_kill_house_vet_quantity = bar_accepted.aggregate( total_quantity=Sum('kill_house_vet_quantity')).get( 'total_quantity') or 0 bar_accepted_kill_house_vet_weight = bar_accepted.aggregate( total_quantity=Sum('kill_house_vet_weight')).get( 'total_quantity') or 0 bar_quantity = kill_house_free_bar_info.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_live_weight = kill_house_free_bar_info.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_number_of_carcasses = kill_house_free_bar_info.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_weight_of_carcasses = kill_house_free_bar_info.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_kill_house_vet_quantity = kill_house_free_bar_info.aggregate( total_quantity=Sum('kill_house_vet_quantity')).get( 'total_quantity') or 0 bar_kill_house_vet_weight = kill_house_free_bar_info.aggregate( total_quantity=Sum('kill_house_vet_weight')).get( 'total_quantity') or 0 value_header_list2 = [ m - 1, len(bar_pending), int(bar_pending_quantity), int(bar_pending_live_weight), int(bar_pending_number_of_carcasses), int(bar_pending_weight_of_carcasses), len(bar_rejected), int(bar_rejected_quantity), int(bar_rejected_live_weight), int(bar_rejected_number_of_carcasses), int(bar_rejected_weight_of_carcasses), len(bar_accepted), int(bar_accepted_quantity), int(bar_accepted_live_weight), int(bar_accepted_number_of_carcasses), int(bar_accepted_weight_of_carcasses), int(bar_accepted_kill_house_vet_quantity), int(bar_accepted_kill_house_vet_weight) ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', bar_quantity, bar_live_weight, int(bar_number_of_carcasses), int(bar_weight_of_carcasses), int(bar_kill_house_vet_quantity), bar_kill_house_vet_weight, '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") workbook.save(output) output.seek(0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response[ 'Content-Disposition'] = f'attachment; filename="کارمزدهای کشتارگاه {kill_house.name}.xlsx"'.encode( 'utf-8') response.write(output.getvalue()) return response def payment_transactions_province_excel(request): filterset_class = InternalTransactionFilterSet filterset_fields = [ 'saleReferenceId', 'refId', 'orderId', 'cardHolderPan', ] if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() transactions = InternalTransaction.objects.filter( date__date__gte=date1, date__date__lte=date2, status='completed', payer_type='kill_house', trash=False).order_by('-date') else: transactions = InternalTransaction.objects.filter( status='completed', payer_type='kill_house', trash=False).order_by('-date') if request.GET['role'] == 'ProvinceOperator': transactions = transactions.filter(union_share__gt=0) elif request.GET['role'] == 'Company': transactions = transactions.filter(company_share__gt=0) elif request.GET['role'] == 'Guilds': transactions = transactions.filter(guilds_share__gt=0) elif request.GET['role'] == 'SuperAdmin': transactions = transactions.filter().exclude(guilds_share=0, company_share=0, union_share=0) else: transactions = transactions if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=transactions ) ).filter(): ps = filterset_class(data=query, queryset=transactions) transactions = ps.filter() 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') header_list = [ 'تعداد کل تراکنش ها', 'مبلغ کل تراکنش(ریال)', 'سهم کل اتحادیه(ریال)', 'سهم کل صنف(ریال)', 'سهم کل شرکت(ریال)', 'سهم کل دامپزشک(ریال)', ] if base_url_for_sms_report == 'ha': province = 'همدان' elif base_url_for_sms_report == 'ku': province = 'کردستان' elif base_url_for_sms_report == 'ma': province = 'مرکزی' elif base_url_for_sms_report == 'bu': province = 'بوشهر' else: province = 'تست' if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) from_date_2 = shamsi_date(date2) excel_description(worksheet, 'B2', f'گزارش ریز تراکنش ها استان {province} از تاریخ {from_date_1} تا {from_date_2}', color='red', row2='C3') else: excel_description(worksheet, 'B2', f'گزارش ریز تراکنش ها استان {province}', color='red', row2='C3') create_header(worksheet, header_list, 5, 2, height=20) create_header_freez(worksheet, excel_options, 1, 6, 7, height=22, width=20.01) l = 5 m = 1 role = request.GET['role'] for transaction in transactions: if transaction.kill_house: killer_type = 'کشتارگاه' if transaction.kill_house.killer == False else 'کشتارکن' elif transaction.chain_company: killer_type = 'شرکت زنجیره' else: killer_type = 'خارج استان' l += 1 payer_date = jdatetime.date.fromgregorian( day=transaction.date.day, month=transaction.date.month, year=transaction.date.year ) if transaction.kill_house != None: fullname = transaction.kill_house.kill_house_operator.user.fullname mobile = transaction.kill_house.kill_house_operator.user.mobile elif transaction.chain_company is not None: fullname = transaction.chain_company.user.fullname mobile = transaction.chain_company.user.mobile else: fullname = transaction.user.fullname mobile = transaction.user.mobile type = 'دستی' if transaction.transaction_type == 'wage-gateway-manual' else 'آنلاین' list1 = [ m, killer_type, type, str(payer_date), transaction.refId, transaction.orderId, fullname, mobile, transaction.cardHolderPan, transaction.amount, transaction.union_share, transaction.guilds_share, transaction.company_share, transaction.other_share ] m += 1 create_value(worksheet, list1, l + 1, 1, border_style='thin') total_amount = \ transactions.aggregate(total=Sum('amount'))['total'] or 0 total_union_share = \ transactions.aggregate(total=Sum('union_share'))['total'] or 0 total_guilds_share = \ transactions.aggregate(total=Sum('guilds_share'))['total'] or 0 total_company_share = \ transactions.aggregate(total=Sum('company_share'))['total'] or 0 total_other_share = \ transactions.aggregate(total=Sum('other_share'))['total'] or 0 value_header_list = [ m - 1, total_amount, total_union_share, total_guilds_share, total_company_share, total_other_share, ] create_value(worksheet, value_header_list, 3, 5) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', total_amount, total_union_share, total_guilds_share, total_company_share, total_other_share, ] create_value(worksheet, list2, l + 3, 1, color='green') 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 general_free_bar_excel(request): value_header_list2_pending1 = [] value_header_list2_accepted = [] value_header_list2_rejected = [] filterset_class = PoultryRequestFilterSet filterset_fields = [ 'order_code', 'poultry__user__mobile', 'poultry__user__fullname', 'poultry__user__first_name', 'poultry__user__last_name', 'poultry__address__city__name', ] now = datetime.datetime.now().date() date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date() if 'date1' in request.GET else now date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date() if 'date2' in request.GET else now excel_options = [ 'درخواست های جدید', 'تایید شده', 'رد شده', ] output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) header_list_main = [ 'تعداد بارها', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'کمترین سن مرغ', 'بیشترین سن مرغ', 'تعداد بارهای دارای کد قرنطینه', ] for name in excel_options: sheet_name = name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') user = SystemUserProfile.objects.get(key=request.GET['key']) poultry_requests = PoultryRequest.objects.filter( send_date__date__gte=date1, send_date__date__lte=date2, out_province_request_cancel=False, trash=False, out=True).order_by('-send_date') if sheet_name == 'درخواست های جدید': if request.GET['role'] == 'VetFarm': vet_farms = VetFarm.objects.filter(vet__user=user, trash=False) poultries = Poultry.objects.filter( pk__in=vet_farms.values('poultry') ) poultry_requests = poultry_requests.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), poultry__in=poultries ).order_by('-send_date') elif request.GET['role'] == 'CityOperator': city_operator = CityOperator.objects.get(user=user) poultry_requests = poultry_requests.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), poultry__city_operator=city_operator.unit_name, out=True, ).order_by('-send_date') elif request.GET['role'] in ['CityJahad', 'CityPoultry']: poultry_requests = poultry_requests.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), poultry__address__city=user.city, out=True, ).order_by('-send_date') elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Supporter']: poultry_requests = poultry_requests.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), out=True ).order_by('-send_date') else: poultry_requests = poultry_requests if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=poultry_requests ) ).filter(): ps = filterset_class(data=query, queryset=poultry_requests) poultry_requests = ps.filter() poultry_requests_accepted = poultry_requests excel_options = [ 'ردیف', 'وضعیت', 'پرداخت کننده', 'کدسفارش مرغدار', ' تاریخ ثبت درخواست', ' تاریخ کشتار', ' کشتار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', ' استان مرغدار', 'سن مرغ', ' نژاد', 'تعداد درخواست', 'میانگین وزنی', 'وزن درخواست', 'مانده در سالن', 'جوجه ریزی اولیه', ' ماهیت خریدار', 'خریدار', 'تلفن خریدار', ' شهر خریدار', 'استان خریدار', 'محل کشتار', 'کد یکتای کشتارگاه', 'شهر محل کشتار', 'نوع خودرو', 'پلاک', 'نام راننده', 'موبایل راننده', 'کد بهداشتی حمل و نقل', 'کد رهگیری سامانه قرنطینه', 'ثبت کننده کد قرنطینه', 'تاریخ ثبت کد قرنطینه', 'سازنده', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str header_list = [ 'تعداد بارهای تایید شده', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'کمترین سن مرغ', 'بیشترین سن مرغ', 'تعداد بارهای دارای کد قرنطینه', ] for col_num, option in enumerate(header_list, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 worksheet['B1'] = f'گزارش بارهای جدید خارج از استان' if poultry_requests.exists(): name = poultry_requests.first().poultry.user.province.name worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 6 m = 1 all_weighte = 0 all_chicken_quantity = 0 all_age = [] all_quantity = poultry_requests_accepted.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_weighte = poultry_requests_accepted.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] has_code = 0 if poultry_requests: for poultry_request in poultry_requests: # if ProvinceKillRequest.objects.filter( # province_request__city_request_Poultry__poultry_request=poultry_request, # state='accepted').exists(): # age = (poultry_request.send_date - poultry_request.hatching.date).days + 1 # else: age = (poultry_request.send_date - poultry_request.hatching.date).days + 1 all_age.append(age) all_chicken_quantity += poultry_request.hatching.quantity create_date_of_poultry_request = jdatetime.date.fromgregorian( day=poultry_request.create_date.day, month=poultry_request.create_date.month, year=poultry_request.create_date.year ) date_of_kill_request = jdatetime.date.fromgregorian( day=poultry_request.send_date.day, month=poultry_request.send_date.month, year=poultry_request.send_date.year ) if poultry_request.quarantine_code_registrar is not None: date_code = poultry_request.quarantine_code_registrar['date'].split('-') date_of_create_code = jdatetime.date.fromgregorian( day=int(date_code[2]), month=int(date_code[1]), year=int(date_code[0]) ) full_name = poultry_request.quarantine_code_registrar['fullname'] mobile = poultry_request.quarantine_code_registrar['mobile'] else: date_of_create_code = '-' full_name = '-' mobile = '-' killing_place = '-' killing_place_city = '-' uniq_id = '-' if poultry_request.out_province_poultry_request_buyer: if poultry_request.out_province_poultry_request_buyer.type == 'killhouse': is_killer = 'کشتارگاه' uniq_id = poultry_request.out_province_poultry_request_buyer.kill_house_unique_id if poultry_request.out_province_poultry_request_buyer.kill_house_unique_id else '-' else: is_killer = 'کشتارکن' killing_place = poultry_request.killer_kill_house_unit_name \ if poultry_request.killer_kill_house_unit_name is not None \ else '-' killing_place_city = poultry_request.killer_kill_house_province \ + '(' + poultry_request.killer_kill_house_city \ + ')' if poultry_request.killer_kill_house_province \ and poultry_request.killer_kill_house_city is not None \ else '-' uniq_id = poultry_request.kill_house_unique_id if poultry_request.kill_house_unique_id else '-' else: is_killer = 'کشتارگاه' if poultry_request.buyer is not None and poultry_request.buyer[ 'buyerType'] == 'killhouse' else 'کشتارکن' if poultry_request.quarantine_code: code = poultry_request.quarantine_code has_code += 1 else: code = '-' freez_state = 'منجمد' if poultry_request.freezing == True else 'عادی' if poultry_request.out_province_poultry_request_buyer is not None: full_name_buyer = poultry_request.out_province_poultry_request_buyer.fullname mobile_buyer = poultry_request.out_province_poultry_request_buyer.user.mobile city_buyer = poultry_request.out_province_poultry_request_buyer.user.city.name province_buyer = poultry_request.out_province_poultry_request_buyer.user.province.name else: full_name_buyer = poultry_request.buyer['firstName'] mobile_buyer = poultry_request.buyer['mobile'] city_buyer = poultry_request.buyer['city'] province_buyer = poultry_request.buyer['province'] if poultry_request.province_state == 'rejected': state1 = 'رد شده' elif poultry_request.province_state == 'pending' and poultry_request.out_province_request_cancel == False: state1 = 'در انتظار تایید' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'در انتظار پرداخت' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == False and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'تایید شده' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == True and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'پرداخت شده' else: state1 = 'لغو شده' list1 = [ m, state1, poultry_request.payer_fullname if poultry_request.payer_fullname else '-', str(poultry_request.order_code), str(create_date_of_poultry_request), str(date_of_kill_request), freez_state, poultry_request.poultry.user.fullname, poultry_request.poultry.user.mobile, poultry_request.poultry.user.city.name, poultry_request.poultry.user.province.name, age, poultry_request.hatching.chicken_breed, poultry_request.quantity, poultry_request.Index_weight, int(poultry_request.quantity * poultry_request.Index_weight), poultry_request.hatching.left_over, poultry_request.hatching.quantity, is_killer, full_name_buyer, mobile_buyer, city_buyer, province_buyer, killing_place, uniq_id, killing_place_city, poultry_request.out_province_driver_info[ 'driverCar'] if poultry_request.out_province_driver_info != None else '-', poultry_request.out_province_driver_info[ 'driverPelak'] if poultry_request.out_province_driver_info != None else '-', poultry_request.out_province_driver_info[ 'driverName'] if poultry_request.out_province_driver_info != None else '-', poultry_request.out_province_driver_info[ 'driverMobile'] if poultry_request.out_province_driver_info != None else '-', poultry_request.out_province_driver_info[ 'driverhealthCode'] if poultry_request.out_province_driver_info != None else '-', code, full_name + '(' + mobile + ')', str(date_of_create_code), poultry_request.registrar['fullname'] if poultry_request.registrar else '-' ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') l += 1 # last_age=sorted(reversed(all_age)) all_age = sorted(all_age) value_header_list2 = [ len(poultry_requests_accepted), all_quantity if all_quantity != None else 0, all_weighte if all_weighte != None else 0, all_age[0] if len(all_age) > 0 else None, all_age[len(all_age) - 1] if len(all_age) > 0 else None, has_code, ] value_header_list2_accepted.extend(value_header_list2) for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', all_quantity if all_quantity != None else 0, '', all_weighte, '', all_chicken_quantity, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'تایید شده': if request.GET['role'] == 'VetFarm': vet_farms = VetFarm.objects.filter(vet__user=user, trash=False) poultries = Poultry.objects.filter( pk__in=vet_farms.values('poultry') ) poultry_requests = poultry_requests.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False), poultry__in=poultries).order_by('-send_date') elif request.GET['role'] == 'CityOperator': city_operator = CityOperator.objects.get(user=user) poultry_requests = poultry_requests.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False), poultry__city_operator=city_operator.unit_name, ).order_by('-send_date') elif request.GET['role'] in ['CityJahad', 'CityPoultry']: poultry_requests = poultry_requests.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False), poultry__address__city=user.city, ).order_by('-send_date') elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Supporter']: poultry_requests = poultry_requests.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False), ).order_by('-send_date') else: poultry_requests = poultry_requests if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=poultry_requests ) ).filter(): ps = filterset_class(data=query, queryset=poultry_requests) poultry_requests = ps.filter() poultry_requests_accepted = poultry_requests excel_options = [ 'ردیف', 'وضعیت', 'پرداخت کننده', 'کدسفارش مرغدار', ' تاریخ ثبت درخواست', ' تاریخ کشتار', ' کشتار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', ' استان مرغدار', 'سن مرغ', ' نژاد', 'تعداد درخواست', 'میانگین وزنی', 'وزن درخواست', 'مانده در سالن', 'جوجه ریزی اولیه', ' ماهیت خریدار', 'خریدار', 'تلفن خریدار', ' شهر خریدار', 'استان خریدار', 'محل کشتار', 'کد یکتای کشتارگاه', 'شهر محل کشتار', 'نوع خودرو', 'پلاک', 'نام راننده', 'موبایل راننده', 'کد بهداشتی حمل و نقل', 'کد رهگیری سامانه قرنطینه', 'ثبت کننده کد قرنطینه', 'تاریخ ثبت کد قرنطینه', 'سازنده', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str header_list = [ 'تعداد بارهای تایید شده', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'کمترین سن مرغ', 'بیشترین سن مرغ', 'تعداد بارهای دارای کد قرنطینه', ] for col_num, option in enumerate(header_list, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 worksheet['B1'] = f'گزارش بارهای تایید شده خارج از استان' if poultry_requests.exists(): name = poultry_requests.first().poultry.user.province.name worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 6 m = 1 all_weighte = 0 all_chicken_quantity = 0 all_age = [] all_quantity = poultry_requests_accepted.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_weighte = poultry_requests_accepted.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] has_code = 0 if poultry_requests: for poultry_request in poultry_requests: if ProvinceKillRequest.objects.filter( province_request__city_request_Poultry__poultry_request=poultry_request, state='accepted').exists(): age = (poultry_request.send_date - poultry_request.hatching.date).days + 1 else: age = (datetime.datetime.now() - poultry_request.hatching.date).days + 1 all_age.append(age) all_chicken_quantity += poultry_request.hatching.quantity create_date_of_poultry_request = jdatetime.date.fromgregorian( day=poultry_request.create_date.day, month=poultry_request.create_date.month, year=poultry_request.create_date.year ) date_of_kill_request = jdatetime.date.fromgregorian( day=poultry_request.send_date.day, month=poultry_request.send_date.month, year=poultry_request.send_date.year ) if poultry_request.quarantine_code_registrar is not None: date_code = poultry_request.quarantine_code_registrar['date'].split('-') date_of_create_code = jdatetime.date.fromgregorian( day=int(date_code[2]), month=int(date_code[1]), year=int(date_code[0]) ) full_name = poultry_request.quarantine_code_registrar['fullname'] mobile = poultry_request.quarantine_code_registrar['mobile'] else: date_of_create_code = '-' full_name = '-' mobile = '-' killing_place = '-' killing_place_city = '-' uniq_id = '-' if poultry_request.out_province_poultry_request_buyer: if poultry_request.out_province_poultry_request_buyer.type == 'killhouse': is_killer = 'کشتارگاه' uniq_id = poultry_request.out_province_poultry_request_buyer.kill_house_unique_id if poultry_request.out_province_poultry_request_buyer.kill_house_unique_id else '-' else: is_killer = 'کشتارکن' killing_place = poultry_request.killer_kill_house_unit_name \ if poultry_request.killer_kill_house_unit_name is not None \ else '-' killing_place_city = poultry_request.killer_kill_house_province \ + '(' + poultry_request.killer_kill_house_city \ + ')' if poultry_request.killer_kill_house_province \ and poultry_request.killer_kill_house_city is not None \ else '-' uniq_id = poultry_request.kill_house_unique_id if poultry_request.kill_house_unique_id else '-' else: is_killer = 'کشتارگاه' if poultry_request.buyer is not None and poultry_request.buyer[ 'buyerType'] == 'killhouse' else 'کشتارکن' if poultry_request.quarantine_code: code = poultry_request.quarantine_code has_code += 1 else: code = '-' freez_state = 'منجمد' if poultry_request.freezing == True else 'عادی' if poultry_request.out_province_poultry_request_buyer is not None: full_name_buyer = poultry_request.out_province_poultry_request_buyer.fullname mobile_buyer = poultry_request.out_province_poultry_request_buyer.user.mobile city_buyer = poultry_request.out_province_poultry_request_buyer.user.city.name province_buyer = poultry_request.out_province_poultry_request_buyer.user.province.name else: full_name_buyer = poultry_request.buyer['firstName'] mobile_buyer = poultry_request.buyer['mobile'] city_buyer = poultry_request.buyer['city'] province_buyer = poultry_request.buyer['province'] if poultry_request.province_state == 'rejected': state1 = 'رد شده' elif poultry_request.province_state == 'pending' and poultry_request.out_province_request_cancel == False: state1 = 'در انتظار تایید' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'در انتظار پرداخت' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == False and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'تایید شده' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == True and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'پرداخت شده' else: state1 = 'لغو شده' list1 = [ m, state1, poultry_request.payer_fullname if poultry_request.payer_fullname else '-', str(poultry_request.order_code), str(create_date_of_poultry_request), str(date_of_kill_request), freez_state, poultry_request.poultry.user.fullname, poultry_request.poultry.user.mobile, poultry_request.poultry.user.city.name, poultry_request.poultry.user.province.name, age, poultry_request.hatching.chicken_breed, poultry_request.quantity, poultry_request.Index_weight, int(poultry_request.quantity * poultry_request.Index_weight), poultry_request.hatching.left_over, poultry_request.hatching.quantity, is_killer, full_name_buyer, mobile_buyer, city_buyer, province_buyer, killing_place, uniq_id, killing_place_city, poultry_request.out_province_driver_info[ 'driverCar'] if poultry_request.out_province_driver_info or \ poultry_request.out_province_driver_info['driverCar'] != None else '-', poultry_request.out_province_driver_info[ 'driverPelak'] if poultry_request.out_province_driver_info \ or poultry_request.out_province_driver_info[ 'driverPelak'] != None else '-', poultry_request.out_province_driver_info[ 'driverName'] if poultry_request.out_province_driver_info \ or poultry_request.out_province_driver_info['driverName'] != None else '-', poultry_request.out_province_driver_info[ 'driverMobile'] if poultry_request.out_province_driver_info or \ poultry_request.out_province_driver_info[ 'driverMobile'] != None else '-', poultry_request.out_province_driver_info[ 'driverhealthCode'] if poultry_request.out_province_driver_info or \ poultry_request.out_province_driver_info[ 'driverhealthCode'] != None else '-', code, full_name + '(' + mobile + ')', str(date_of_create_code), poultry_request.registrar['fullname'] if poultry_request.registrar else '-' ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') l += 1 # last_age=sorted(reversed(all_age)) all_age = sorted(all_age) value_header_list2 = [ len(poultry_requests_accepted), all_quantity if all_quantity != None else 0, all_weighte if all_weighte != None else 0, all_age[0] if len(all_age) > 0 else None, all_age[len(all_age) - 1] if len(all_age) > 0 else None, has_code, ] value_header_list2_pending1.extend(value_header_list2) for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', all_quantity if all_quantity != None else 0, '', all_weighte, '', all_chicken_quantity, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'رد شده': if request.GET['role'] == 'VetFarm': vet_farms = VetFarm.objects.filter(vet__user=user, trash=False) poultries = Poultry.objects.filter( pk__in=vet_farms.values('poultry') ) poultry_requests = poultry_requests.filter( Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True, wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False) | Q( state_process='pending', province_state='pending', final_state='pending', has_wage=False, wage_pay=False, out_province_request_cancel=True), poultry__in=poultries, ).order_by('-send_date') elif request.GET['role'] == 'CityOperator': city_operator = CityOperator.objects.get(user=user) poultry_requests = poultry_requests.filter( Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True, wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False) | Q( state_process='pending', province_state='pending', final_state='pending', has_wage=False, wage_pay=False, out_province_request_cancel=True), poultry__city_operator=city_operator.unit_name, ).order_by('-send_date') elif request.GET['role'] in ['CityJahad', 'CityPoultry']: poultry_requests = poultry_requests.filter( Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True, wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False) | Q( state_process='pending', province_state='pending', final_state='pending', has_wage=False, wage_pay=False, out_province_request_cancel=True), poultry__address__city=user.city, ).order_by('-send_date') elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Supporter']: poultry_requests = poultry_requests.filter( Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True, wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False) | Q( state_process='pending', province_state='pending', final_state='pending', has_wage=False, wage_pay=False, out_province_request_cancel=True)).order_by('-send_date') else: poultry_requests = poultry_requests if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=poultry_requests ) ).filter(): ps = filterset_class(data=query, queryset=poultry_requests) poultry_requests = ps.filter() poultry_requests_accepted = poultry_requests excel_options = [ 'ردیف', 'وضعیت', 'پرداخت کننده', 'کدسفارش مرغدار', ' تاریخ ثبت درخواست', ' تاریخ کشتار', ' کشتار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', ' استان مرغدار', 'سن مرغ', ' نژاد', 'تعداد درخواست', 'میانگین وزنی', 'وزن درخواست', 'مانده در سالن', 'جوجه ریزی اولیه', ' ماهیت خریدار', 'خریدار', 'تلفن خریدار', ' شهر خریدار', 'استان خریدار', 'محل کشتار', 'کد یکتای کشتارگاه', 'شهر محل کشتار', 'نوع خودرو', 'پلاک', 'نام راننده', 'موبایل راننده', 'کد بهداشتی حمل و نقل', 'کد رهگیری سامانه قرنطینه', 'ثبت کننده کد قرنطینه', 'تاریخ ثبت کد قرنطینه', 'سازنده', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str header_list = [ 'تعداد بارهای تایید شده', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'کمترین سن مرغ', 'بیشترین سن مرغ', 'تعداد بارهای دارای کد قرنطینه', ] for col_num, option in enumerate(header_list, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 worksheet['B1'] = f'گزارش بارهای حذف /رد شده خارج از استان' if poultry_requests.exists(): name = poultry_requests.first().poultry.user.province.name worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 6 m = 1 all_weighte = 0 all_chicken_quantity = 0 all_age = [] all_quantity = poultry_requests_accepted.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_weighte = poultry_requests_accepted.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] has_code = 0 if poultry_requests: for poultry_request in poultry_requests: if ProvinceKillRequest.objects.filter( province_request__city_request_Poultry__poultry_request=poultry_request, state='accepted').exists(): age = (poultry_request.send_date - poultry_request.hatching.date).days + 1 else: age = (datetime.datetime.now() - poultry_request.hatching.date).days + 1 all_age.append(age) all_chicken_quantity += poultry_request.hatching.quantity create_date_of_poultry_request = jdatetime.date.fromgregorian( day=poultry_request.create_date.day, month=poultry_request.create_date.month, year=poultry_request.create_date.year ) date_of_kill_request = jdatetime.date.fromgregorian( day=poultry_request.send_date.day, month=poultry_request.send_date.month, year=poultry_request.send_date.year ) if poultry_request.quarantine_code_registrar is not None: date_code = poultry_request.quarantine_code_registrar['date'].split('-') date_of_create_code = jdatetime.date.fromgregorian( day=int(date_code[2]), month=int(date_code[1]), year=int(date_code[0]) ) full_name = poultry_request.quarantine_code_registrar['fullname'] mobile = poultry_request.quarantine_code_registrar['mobile'] else: date_of_create_code = '-' full_name = '-' mobile = '-' killing_place = '-' killing_place_city = '-' uniq_id = '-' if poultry_request.out_province_poultry_request_buyer: if poultry_request.out_province_poultry_request_buyer.type == 'killhouse': is_killer = 'کشتارگاه' uniq_id = poultry_request.out_province_poultry_request_buyer.kill_house_unique_id if poultry_request.out_province_poultry_request_buyer.kill_house_unique_id else '-' else: is_killer = 'کشتارکن' killing_place = poultry_request.killer_kill_house_unit_name \ if poultry_request.killer_kill_house_unit_name is not None \ else '-' killing_place_city = poultry_request.killer_kill_house_province \ + '(' + poultry_request.killer_kill_house_city \ + ')' if poultry_request.killer_kill_house_province \ and poultry_request.killer_kill_house_city is not None \ else '-' uniq_id = poultry_request.kill_house_unique_id if poultry_request.kill_house_unique_id else '-' else: is_killer = 'کشتارگاه' if poultry_request.buyer is not None and poultry_request.buyer[ 'buyerType'] == 'killhouse' else 'کشتارکن' if poultry_request.quarantine_code: code = poultry_request.quarantine_code has_code += 1 else: code = '-' freez_state = 'منجمد' if poultry_request.freezing == True else 'عادی' if poultry_request.out_province_poultry_request_buyer is not None: full_name_buyer = poultry_request.out_province_poultry_request_buyer.fullname mobile_buyer = poultry_request.out_province_poultry_request_buyer.user.mobile city_buyer = poultry_request.out_province_poultry_request_buyer.user.city.name province_buyer = poultry_request.out_province_poultry_request_buyer.user.province.name else: full_name_buyer = poultry_request.buyer['firstName'] mobile_buyer = poultry_request.buyer['mobile'] city_buyer = poultry_request.buyer['city'] province_buyer = poultry_request.buyer['province'] if poultry_request.province_state == 'rejected': state1 = 'رد شده' elif poultry_request.province_state == 'pending' and poultry_request.out_province_request_cancel == False: state1 = 'در انتظار تایید' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'در انتظار پرداخت' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == False and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'تایید شده' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == True and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'پرداخت شده' else: state1 = 'لغو شده' list1 = [ m, state1, poultry_request.payer_fullname if poultry_request.payer_fullname else '-', str(poultry_request.order_code), str(create_date_of_poultry_request), str(date_of_kill_request), freez_state, poultry_request.poultry.user.fullname, poultry_request.poultry.user.mobile, poultry_request.poultry.user.city.name, poultry_request.poultry.user.province.name, age, poultry_request.hatching.chicken_breed, poultry_request.quantity, poultry_request.Index_weight, int(poultry_request.quantity * poultry_request.Index_weight), poultry_request.hatching.left_over, poultry_request.hatching.quantity, is_killer, full_name_buyer, mobile_buyer, city_buyer, province_buyer, killing_place, uniq_id, killing_place_city, poultry_request.out_province_driver_info[ 'driverCar'] if poultry_request.out_province_driver_info or \ poultry_request.out_province_driver_info['driverCar'] != None else '-', poultry_request.out_province_driver_info[ 'driverPelak'] if poultry_request.out_province_driver_info \ or poultry_request.out_province_driver_info[ 'driverPelak'] != None else '-', poultry_request.out_province_driver_info[ 'driverName'] if poultry_request.out_province_driver_info \ or poultry_request.out_province_driver_info['driverName'] != None else '-', poultry_request.out_province_driver_info[ 'driverMobile'] if poultry_request.out_province_driver_info or \ poultry_request.out_province_driver_info[ 'driverMobile'] != None else '-', poultry_request.out_province_driver_info[ 'driverhealthCode'] if poultry_request.out_province_driver_info or \ poultry_request.out_province_driver_info[ 'driverhealthCode'] != None else '-', code, full_name + '(' + mobile + ')', str(date_of_create_code), poultry_request.registrar['fullname'] if poultry_request.registrar else '-' ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') l += 1 # last_age=sorted(reversed(all_age)) all_age = sorted(all_age) value_header_list2 = [ len(poultry_requests_accepted), all_quantity if all_quantity != None else 0, all_weighte if all_weighte != None else 0, all_age[0] if len(all_age) > 0 else None, all_age[len(all_age) - 1] if len(all_age) > 0 else None, has_code, ] value_header_list2_rejected.extend(value_header_list2) for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', all_quantity if all_quantity != None else 0, '', all_weighte, '', all_chicken_quantity, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") sheet_name = 'اطلاعات کلی' worksheet = workbook.create_sheet(sheet_name) if sheet_name == 'اطلاعات کلی': worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') if 'date1' in request.GET: from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) worksheet['E3'] = f'اطلاعات بارهای جدید خارج استان از تاریخ {from_date_1} تا {from_date_2}' merge_range1 = 'E3:J3' worksheet.merge_cells(merge_range1) worksheet['E3'].font = Font(color="C00000", bold=True) worksheet['E3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['E8'] = f'اطلاعات بارهای تایید شده خارج استان از تاریخ {from_date_1} تا {from_date_2}' merge_range2 = 'E8:J8' worksheet.merge_cells(merge_range2) worksheet['E8'].font = Font(color="C00000", bold=True) worksheet['E8'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['E13'] = f'اطلاعات بارهای رد شده خارج استان از تاریخ {from_date_1} تا {from_date_2}' merge_range3 = 'E13:J13' worksheet.merge_cells(merge_range3) worksheet['E13'].font = Font(color="C00000", bold=True) worksheet['E13'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) for col_num, option in enumerate(header_list_main, 5): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=4, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[4].height = 35 worksheet.column_dimensions[col_letter].width = 18 for col_num, option in enumerate(header_list_main, 5): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=9, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[9].height = 35 worksheet.column_dimensions[col_letter].width = 18 for col_num, option in enumerate(header_list_main, 5): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=14, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[14].height = 35 worksheet.column_dimensions[col_letter].width = 18 for item in range(len(value_header_list2_pending1)): cell = worksheet.cell(row=5, column=item + 5, value=value_header_list2_pending1[item]) value = value_header_list2_pending1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) for item in range(len(value_header_list2_accepted)): cell = worksheet.cell(row=10, column=item + 5, value=value_header_list2_accepted[item]) value = value_header_list2_accepted[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) for item in range(len(value_header_list2_rejected)): cell = worksheet.cell(row=15, column=item + 5, value=value_header_list2_rejected[item]) value = value_header_list2_rejected[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) 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 out_province_poultry_request_buyers_excel(request): filterset_class = OutProvincePoultryRequestBuyerFilterSet filterset_fields = [ 'user__national_id', 'user__base_order', 'user__mobile', 'user__first_name', 'user__last_name', 'user__fullname', 'unit_name', ] buyers = OutProvincePoultryRequestBuyer.objects.filter(trash=False).order_by('id') if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=buyers ) ).filter(): ps = filterset_class(data=query, queryset=buyers) buyers = ps.filter() excel_options = [ 'ردیف', 'نام کامل', 'موبایل', 'استان', 'شهر', 'ماهیت خریدار', 'نام واحد', 'تعداد درخواست ها', 'حجم درخواست ها(قطعه)', 'وزن درخواست ها(کیلوگرم)', 'وضعیت', ] date1 = datetime.datetime.now().date() from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) header_list = [ 'تعداد کل خریداران', 'مجموع تعداد درخواست ها', 'مجموع حجم درخواست ها', 'مجموع وزن درخواست ها', ] for col_num, option in enumerate(header_list, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20 worksheet['B2'] = f'این گزارش در مورخ {from_date_1} صادر شده است.' worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B2:C3' worksheet.merge_cells(merge_range1) worksheet['B2'].font = red_font for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') worksheet.column_dimensions[col_letter].width = 20.01 worksheet.row_dimensions[6].height = 22 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str l = 5 m = 1 all_poultry_requests = 0 all_total_quantity = 0 all_total_weight = 0 for buyer in buyers: poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True, out_province_request_cancel=False) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False), trash=False, out=True, out_province_poultry_request_buyer=buyer) all_poultry_requests += len(poultry_requests) total_quantity = poultry_requests.aggregate(total=Sum('quantity'))[ 'total'] or 0 all_total_quantity += total_quantity total_weight = poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 all_total_weight += total_weight l += 1 active = 'فعال' if buyer.active == True else 'غیرفعال' type = 'کشتارکن' if buyer.type == 'killer' else 'کشتارگاه' list1 = [ m, buyer.user.fullname, buyer.user.mobile, buyer.user.province.name, buyer.user.city.name, type, buyer.unit_name if buyer.unit_name is not None else '-', len(poultry_requests), total_quantity, total_weight, active ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) value_header_list = [ len(buyers), all_poultry_requests, all_total_quantity, all_total_weight ] for item in range(len(value_header_list)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item]) value = value_header_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', all_poultry_requests, all_total_quantity, all_total_weight, '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' else: cell.value = value cell.alignment = Alignment(horizontal='center') cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 chain_company_buyers_excel(request): filterset_class = ChainCompanyFilterSet filterset_fields = [ 'user__national_id', 'user__mobile', 'user__first_name', 'user__last_name', 'user__fullname', 'name', ] chain_companies = ChainCompany.objects.filter(trash=False).order_by('id') if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=chain_companies ) ).filter(): ps = filterset_class(data=query, queryset=chain_companies) chain_companies = ps.filter() excel_options = [ 'ردیف', 'نام شرکت', 'مدیر عامل', 'موبایل مدیر عامل', 'شهر', 'تعداد سفارشات', 'حجم سفارشات(قطعه)', 'وزن سفارشات(قطعه)', ] date1 = datetime.datetime.now().date() from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) header_list = [ 'تعداد شرکت ها', 'مجموع تعداد سفارشات', 'مجموع حجم سفارشات', 'مجموع وزن سفارشات', ] for col_num, option in enumerate(header_list, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20 worksheet['B2'] = f'این گزارش در مورخ {from_date_1} صادر شده است.' worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B2:C3' worksheet.merge_cells(merge_range1) worksheet['B2'].font = red_font for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') worksheet.column_dimensions[col_letter].width = 20.01 worksheet.row_dimensions[6].height = 22 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str l = 5 m = 1 all_poultry_requests = 0 all_total_quantity = 0 all_total_weight = 0 for buyer in chain_companies: chain_allocations = ChainAllocation.objects.filter(chain_company=buyer, state='accepted', trash=False).order_by( '-id') total_quantity = chain_allocations.aggregate(total=Sum('quantity'))[ 'total'] or 0 total_weight = chain_allocations.aggregate(total=Sum('weight'))[ 'total'] or 0 all_poultry_requests += len(chain_allocations) all_total_quantity += total_quantity all_total_weight += total_weight l += 1 list1 = [ m, buyer.name, buyer.user.fullname, buyer.user.mobile, buyer.user.city.name, len(chain_allocations), total_quantity, total_weight ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) value_header_list = [ len(chain_companies), all_poultry_requests, all_total_quantity, all_total_weight ] for item in range(len(value_header_list)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item]) value = value_header_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', all_poultry_requests, all_total_quantity, all_total_weight, ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' else: cell.value = value cell.alignment = Alignment(horizontal='center') cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 bar_chain_excel(request): now = datetime.datetime.now() date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else now date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date1' in request.GET else now filterset_class = ChainAllocationFilterSet filterset_fields = [ 'poultry_hatching__poultry__breeding_unique_id', 'poultry_hatching__poultry__user__mobile', 'poultry_hatching__poultry__user__fullname', 'poultry_hatching__poultry__user__first_name', 'poultry_hatching__poultry__user__last_name', 'poultry_hatching__poultry__unit_name', 'chain_company__name', ] chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2, ).order_by('id') if request.GET['state'] == 'accepted': if request.GET['role'] == "ChainCompany": user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) chain_allocations = chain_allocations.filter(chain_company__user=user, state__in=('accepted', 'pending'), trash=False).order_by('-id') elif request.GET['role'] in ['CityJahad', 'CityPoultry']: user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) chain_allocations = chain_allocations.filter(poultry_hatching__poultry__address__city=user.city, state__in=('accepted', 'pending'), trash=False).order_by('-id') elif request.GET['role'] == "CityOperator": user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) city_operator = CityOperator.objects.get(user=user, trash=False) chain_allocations = chain_allocations.filter( poultry_hatching__poultry__city_operator=city_operator.unit_name, state__in=('accepted', 'pending'), trash=False).order_by('-id') elif request.GET['role'] == "VetFarm": user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) vet = Vet.objects.get(user=user, trash=False) poultry_ids = VetFarm.objects.filter(vet=vet, trash=False).select_related('poultry').only( 'poultry').values_list('poultry', flat=True).distinct() poultry = Poultry.objects.filter(id__in=poultry_ids) chain_allocations = chain_allocations.filter(poultry_hatching__poultry__in=poultry, state__in=('accepted', 'pending'), trash=False).order_by('-id') else: chain_allocations = chain_allocations.filter(state__in=('accepted', 'pending'), trash=False).order_by('-id') state1 = 'تایید شده' else: if request.GET['role'] == "ChainCompany": user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) chain_allocations = chain_allocations.filter(chain_company__user=user, state__in=('rejected', 'deleted'), trash__in=(False, True), temporary_trash=False, temporary_deleted=False).order_by('-id') elif request.GET['role'] in ['CityJahad', 'CityPoultry']: user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) chain_allocations = chain_allocations.filter(poultry_hatching__poultry__address__city=user.city, state__in=('rejected', 'deleted'), trash__in=(False, True), temporary_trash=False, temporary_deleted=False).order_by('-id') elif request.GET['role'] == "CityOperator": user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) city_operator = CityOperator.objects.get(user=user, trash=False) chain_allocations = chain_allocations.filter( poultry_hatching__poultry__city_operator=city_operator.unit_name, state__in=('rejected', 'deleted'), trash__in=(False, True), temporary_trash=False, temporary_deleted=False).order_by('-id') elif request.GET['role'] == "VetFarm": user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) vet = Vet.objects.get(user=user, trash=False) poultry_ids = VetFarm.objects.filter(vet=vet, trash=False).select_related('poultry').only( 'poultry').values_list('poultry', flat=True).distinct() poultry = Poultry.objects.filter(id__in=poultry_ids) chain_allocations = chain_allocations.filter( poultry_hatching__poultry__in=poultry, state__in=('rejected', 'deleted'), trash__in=(False, True), temporary_trash=False, temporary_deleted=False).order_by('-id') else: chain_allocations = chain_allocations.filter( state__in=('rejected', 'deleted'), trash__in=(False, True), temporary_trash=False, temporary_deleted=False).order_by('-id') state1 = 'رد شده' if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=chain_allocations ) ).filter(): ps = filterset_class(data=query, queryset=chain_allocations) chain_allocations = ps.filter() excel_options = [ 'ردیف', 'وضعیت', ' تاریخ سفارش', 'نوع فروش', 'ثبت کننده سفارش', 'تلفن ثبت کننده سفارش', 'خریدار', 'تلفن خریدار', 'مرغداری', 'تلفن مرغداری', 'شرکت زنجیره', ' تلفن شرکت زنجیره', 'کد بهداشتی', 'کد قرنطینه', 'راننده ', 'تلفن راننده ', 'خودرو', 'پلاک', 'حجم', 'میانگین وزن', 'وزن', 'حذف/رد کننده', 'تلفن حذف/رد کننده', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if state1 == 'تایید شده': for col_num, option in enumerate(excel_options[:21], 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str else: for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str header_list = [ 'تعداد بارها', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'کمترین سن مرغ', 'بیشترین سن مرغ', 'تعداد بارهای دارای کد قرنطینه', ] for col_num, option in enumerate(header_list, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 worksheet['B1'] = f'گزارش بارهای {state1} شرکت زنجیره' if chain_allocations.exists(): name = chain_allocations.first().poultry_hatching.poultry.user.province.name worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 6 m = 1 all_age = [] all_quantity = chain_allocations.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity') or 0 all_weighte = chain_allocations.aggregate( total=Sum('weight'))[ 'total'] or 0 has_code = 0 if chain_allocations: for chain_allocation in chain_allocations: age = (chain_allocation.poultry_hatching.chicken_age) all_age.append(age) chain_date = jdatetime.date.fromgregorian( day=chain_allocation.date.day, month=chain_allocation.date.month, year=chain_allocation.date.year ) if chain_allocation.quarantine_code: has_code += 1 remover_fullname = '-' remover_mobile = '-' if chain_allocation.state == 'accepted': state = 'تایید شده' elif chain_allocation.state == 'rejected': state = 'رد شده' remover_fullname = chain_allocation.seconder['fullname'] if chain_allocation.seconder else None remover_mobile = chain_allocation.seconder['mobile'] if chain_allocation.seconder else None elif chain_allocation.state == 'pending': state = 'در انتظار تایید' else: state = 'حذف شده' remover_fullname = chain_allocation.remover['fullname'] if chain_allocation.remover else None remover_mobile = chain_allocation.remover['mobile'] if chain_allocation.remover else None out_province = 'خارج استان' if chain_allocation.out_province == True else 'داخل استان' full_name_registerer = chain_allocation.registerer['fullname'] if chain_allocation.registerer else '-' mobile_registerer = chain_allocation.registerer['mobile'] if chain_allocation.registerer else '-' if chain_allocation.kill_house is not None: buyer_fullname = chain_allocation.kill_house.name buyer_mobile = chain_allocation.kill_house.kill_house_operator.user.mobile else: buyer_fullname = chain_allocation.buyer_name buyer_mobile = chain_allocation.buyer_mobile list1 = [ m, state, str(chain_date), out_province, full_name_registerer, mobile_registerer, buyer_fullname, buyer_mobile, chain_allocation.poultry_hatching.poultry.unit_name, chain_allocation.poultry_hatching.poultry.user.mobile, chain_allocation.company_name, chain_allocation.company_user_mobile, chain_allocation.health_code if chain_allocation.health_code else '-', chain_allocation.quarantine_code if chain_allocation.quarantine_code else '-', chain_allocation.driver_name if chain_allocation.driver_name else '-', chain_allocation.driver_mobile if chain_allocation.driver_mobile else '-', chain_allocation.type_car if chain_allocation.type_car else '-', chain_allocation.pelak if chain_allocation.pelak else '-', chain_allocation.quantity, chain_allocation.index_weight, chain_allocation.weight, remover_fullname, remover_mobile, ] m += 1 if state1 == 'تایید شده': for item in range(len(list1) - 2): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) else: for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) l += 1 # last_age=sorted(reversed(all_age)) all_age = sorted(all_age) value_header_list2 = [ len(chain_allocations), all_quantity, all_weighte, all_age[0] if len(all_age) > 0 else None, all_age[len(all_age) - 1] if len(all_age) > 0 else None, has_code, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_quantity, '', all_weighte, '', '', ] if state1 == 'تایید شده': for item in range(len(list2) - 2): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") else: for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 general_city_operator(request): date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None city_operator_list = [] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) sheet_name = 'اطلاعات کلی' worksheet = workbook.create_sheet(sheet_name) if sheet_name == 'اطلاعات کلی': worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') city_operators = CityOperator.objects.filter(trash=False).exclude(unit_name='اتحادیه استان (فاقد تعاونی)') row_list2 = len(city_operators) + 7 province = city_operators.last().user.province.name worksheet[f'F1'] = f'گزارش اطلاعات کلی جوجه ریزی و کشتار تعاونی های استان {province}' worksheet[f'F1'].font = Font(color="C00000", bold=True, size=12) worksheet[f'F1'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = f'F1:I2' worksheet.merge_cells(merge_range1) worksheet[f'D{row_list2}'] = f'اطلاعات کشتار به تفکیک تعاونی ها از تاریخ {from_date_1} تا {from_date_2}' worksheet[f'D{row_list2}'].font = Font(color="C00000", bold=True, size=12) worksheet[f'D{row_list2}'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = f'D{row_list2}:J{row_list2 + 1}' worksheet.merge_cells(merge_range1) header_list1 = [ 'تعاونی', 'شهر', 'کاربر', 'تلفن کاربر', 'تعداد فارم', 'تعداد کل جوجه ریزی', 'حجم کل جوجه ریزی', 'حجم کل کشتارشده', 'وزن کل کشتارشده', 'میانگین وزنی', 'حجم کل فروش خارج از استان', 'وزن کل فروش خارج از استان', 'وزن کل لاشه', 'تعداد جوجه ریزی فعال', 'حجم جوجه ریزی فعال', 'مانده در سالن', 'تعداد درخواست کشتار تعاونی', 'حجم درخواست کشتار تعاونی', 'درصد نسبت به حجم کل', 'تعداد خرید مستقیم', 'حجم خرید مستقیم', 'درصد نسبت به حجم کل', 'تعداد درخواست کشتار کاربر سایر', 'حجم کشتار کاربر سایر', 'درصد نسبت به حجم کل', 'تعداد گزارشات کاربر تعاونی', 'تعداد گزارشات کاربر ادمین', 'کل گزارشات', 'درصد فعالیت کاربر نسبت به جوجه ریزی ها', 'درصد فعالیت ادمین نسبت به جوجه ریزی ها', 'درصد فعالیت نسبت به کل گزارشات کاربران', 'درصد فعالیت نسبت به کاربر ادمین', ] for col_num, option in enumerate(header_list1, 2): cell = worksheet.cell(row=3, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="31869B", fill_type="solid") cell.font = Font(size=10, bold=True, color='FFFFFF') cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) l = 4 row_list = len(city_operators) + 12 row_city = len(city_operators) + 10 len_poultry = 0 len_all_hatching = 0 all_hathcing_quantitya_all = 0 all_province_requests_quantity = 0 all_province_requests_weight = 0 len_hatching = 0 all_hatching_quantity = 0 all_hatching_lest_over = 0 all_out_poultry_request_quantity = 0 all_out_poultry_request_weight = 0 city_operator_poultry_request_quantity_all = 0 city_operator_poultry_request_weight_all = 0 direct_bying_poultry_request_quantity_all = 0 direct_bying_poultry_request_weight_all = 0 province_operaor_poultry_request_quantity_all = 0 province_operaor_poultry_request_weight_all = 0 city_operator_name = city_operators.values_list('user__fullname', flat=True).distinct() city_operator_all_violation_all = PoultryHatching.objects.filter(trash=False, violation_reporter__isnull=False, violation_reporter__in=city_operator_name).count() all_admin_all_violation = 0 for city_operator in city_operators: poultry_request = PoultryRequest.objects.filter(trash=False, out_province_request_cancel=False, province_state='accepted', poultry__city_operator=city_operator.unit_name) poultry = Poultry.objects.filter(trash=False, city_operator=city_operator.unit_name) out_poultry_request = poultry_request.filter(out=True) city_operator_poultry_request = poultry_request.filter(direct_buying=False, registrar__role='CityOperator') province_operaor_poultry_request = poultry_request.filter(~Q(registrar__role='CityOperator'), direct_buying=False) direct_bying_poultry_request = poultry_request.filter(direct_buying=True) province_requests = ProvinceKillRequest.objects.filter(trash=False, province_request__poultry_request__poultry__city_operator=city_operator.unit_name , return_to_province=False, state__in=('accepted', 'pending')) province_requests_quantity = \ province_requests.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 province_requests_weight = \ province_requests.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 kill_requests = KillHouseRequest.objects.filter(trash=False, province_kill_request__in=province_requests) all_hatching = PoultryHatching.objects.filter(trash=False, poultry__in=poultry) all_violation = all_hatching.filter(violation_reporter__isnull=False) city_operator_all_violation = all_violation.filter(violation_reporter=city_operator.user.fullname).count() admin_all_violation = all_violation.filter(~Q(violation_reporter=city_operator.user.fullname)).count() hathcing_quantity_all = \ all_hatching.aggregate( total=Sum(F('quantity')))[ 'total'] or 0 out_poultry_request_quantity_all = \ out_poultry_request.aggregate( total=Sum(F('quantity')))[ 'total'] or 0 out_poultry_request_weight_all = \ out_poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 hatching = all_hatching.filter(archive=False, allow_hatching='pending') hatching_quantity = \ hatching.aggregate( total=Sum('quantity'))[ 'total'] or 0 hatching_lest_over = \ hatching.aggregate( total=Sum('left_over'))[ 'total'] or 0 city_operator_poultry_request_quantity = \ city_operator_poultry_request.aggregate( total=Sum('quantity'))[ 'total'] or 0 city_operator_poultry_request_weight = \ city_operator_poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 quantity_all = \ poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 direct_bying_poultry_request_quantity = \ direct_bying_poultry_request.aggregate( total=Sum('quantity'))[ 'total'] or 0 direct_bying_poultry_request_weight = \ direct_bying_poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 province_operaor_poultry_request_quantity = \ province_operaor_poultry_request.aggregate( total=Sum('quantity'))[ 'total'] or 0 province_operaor_poultry_request_weight = \ province_operaor_poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 all_report = city_operator_all_violation + admin_all_violation all_admin_all_violation += admin_all_violation list1 = [ city_operator.unit_name, city_operator.user.city.name, city_operator.user.fullname, city_operator.user.mobile, len(poultry), len(all_hatching), hathcing_quantity_all, province_requests_quantity, province_requests_weight, round(province_requests_weight / province_requests_quantity, 1) if province_requests_quantity > 0 else 0, out_poultry_request_quantity_all, out_poultry_request_weight_all, province_requests_weight * 0.75, len(hatching), hatching_quantity, hatching_lest_over, city_operator_poultry_request_quantity, city_operator_poultry_request_weight, round((city_operator_poultry_request_weight * 100) / quantity_all) if quantity_all > 0 else 0, direct_bying_poultry_request_quantity, direct_bying_poultry_request_weight, round((direct_bying_poultry_request_weight * 100) / quantity_all) if quantity_all > 0 else 0, province_operaor_poultry_request_quantity, province_operaor_poultry_request_weight, round((province_operaor_poultry_request_weight * 100) / quantity_all) if quantity_all > 0 else 0, city_operator_all_violation, admin_all_violation, city_operator_all_violation + admin_all_violation, str(round(city_operator_all_violation * 100 / len(all_hatching), 1) if len(all_hatching) > 0 else 0), str(round(admin_all_violation * 100 / len(all_hatching), 1) if len(all_hatching) > 0 else 0), str(round(city_operator_all_violation * 100 / city_operator_all_violation_all, 1) if city_operator_all_violation_all > 0 else 0), str(round(city_operator_all_violation * 100 / all_report, 1) if all_report > 0 else 0), ] for item in range(len(list1)): cell = worksheet.cell(row=l, column=item + 2, value=list1[item]) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) l += 1 len_poultry += len(poultry) len_all_hatching += len(all_hatching) all_hathcing_quantitya_all += hathcing_quantity_all all_province_requests_quantity += province_requests_quantity all_province_requests_weight += province_requests_weight len_hatching += len(hatching) all_hatching_quantity += hatching_quantity all_hatching_lest_over += hatching_lest_over all_out_poultry_request_quantity += out_poultry_request_quantity_all all_out_poultry_request_weight += out_poultry_request_weight_all province_requests_date = province_requests.filter( province_request__poultry_request__send_date__date__gte=date1 , province_request__poultry_request__send_date__date__lte=date2, province_request__poultry_request__poultry__city_operator=city_operator.unit_name ) city_operator_poultry_request_quantity_all += city_operator_poultry_request_quantity city_operator_poultry_request_weight_all += city_operator_poultry_request_weight direct_bying_poultry_request_quantity_all += direct_bying_poultry_request_quantity direct_bying_poultry_request_weight_all += direct_bying_poultry_request_weight province_operaor_poultry_request_quantity_all += province_operaor_poultry_request_quantity province_operaor_poultry_request_weight_all += province_operaor_poultry_request_weight list2 = [ 'ردیف', 'ماهیت', 'خریدار', 'نام و نام خانوادگی مالک', 'تلفن مالک', 'شهر', 'تعداد سفارش', 'حجم سفارش', 'تعداد بار ', 'حجم بار', 'وزن بار', 'وزن لاشه', ] if province_requests_date: if city_operator not in city_operator_list: city_operator_list.append(city_operator) kill_houses1 = province_requests_date.values_list('killhouse_user', flat=True).distinct() for col_num, option in enumerate(list2, 2): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=row_list, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="31869B", fill_type="solid") cell.font = Font(size=10, bold=True, color='FFFFFF') if option in ['تعداد سفارش', 'حجم سفارش', 'تعداد بار ', 'حجم بار', 'وزن بار', 'وزن لاشه']: cell.fill = PatternFill(start_color="FF0000", fill_type="solid") # worksheet.row_dimensions[row_list].height = 35 worksheet.column_dimensions[col_letter].width = 17 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) m = 1 kill_houses = KillHouse.objects.filter(id__in=kill_houses1) len_province_requests_kill = 0 all_province_quantity = 0 len_kill_requests_date = 0 all_accepted_assignment_real_quantity = 0 all_accepted_assignment_real_weight = 0 all_ware_house_accepted_real_weight = 0 for kill_house in kill_houses: province_requests_kill = province_requests_date.filter(killhouse_user=kill_house) province_quantity = \ province_requests_kill.aggregate( total=Sum('main_quantity'))[ 'total'] or 0 kill_requests_date = kill_requests.filter(kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, killhouse_user=kill_house, province_kill_request__in=province_requests_kill) accepted_assignment_real_quantity = \ kill_requests_date.aggregate( total=Sum('accepted_real_quantity'))[ 'total'] or 0 accepted_assignment_real_weight = \ kill_requests_date.aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 len_province_requests_kill += len(province_requests_kill) all_province_quantity += province_quantity len_kill_requests_date += len(kill_requests_date) all_accepted_assignment_real_quantity += accepted_assignment_real_quantity all_accepted_assignment_real_weight += int(accepted_assignment_real_weight) all_ware_house_accepted_real_weight += int(accepted_assignment_real_weight) * 0.75 # killer='کشتارگاه' if kill_house.killer == False else 'کشتارکن' if kill_house.killer == True and kill_house.type == 'exclusive': parent = KillHousePercentage.objects.get(kill_house=kill_house, trash=False) killer_type = f'کشتارکن اختصاصی {parent.kill_house_for_killer.name}' elif kill_house.killer == True and kill_house.type == 'public': killer_type = 'کشتارکن عمومی' else: killer_type = 'کشتارگاه' list1 = [ m, killer_type, kill_house.name, kill_house.kill_house_operator.user.fullname, kill_house.kill_house_operator.user.mobile, kill_house.kill_house_operator.user.city.name, len(province_requests_kill), province_quantity, len(kill_requests_date), accepted_assignment_real_quantity, int(accepted_assignment_real_weight), int(accepted_assignment_real_weight) * 0.75, ] for item in range(len(list1)): cell = worksheet.cell(row=row_list + 1, column=item + 2, value=list1[item]) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) row_list += 1 m += 1 else: row_list += 5 worksheet[f'F{row_city}'] = f'{city_operator.unit_name}' worksheet[f'F{row_city}'].font = Font(color="C00000", bold=True, size=12) worksheet[f'F{row_city}'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = f'F{row_city}:H{row_city + 1}' worksheet.merge_cells(merge_range1) row_city += len(kill_houses) + 5 list2 = [ 'مجموع==>', '', '', '', '', '', len_province_requests_kill, all_province_quantity, len_kill_requests_date, all_accepted_assignment_real_quantity, all_accepted_assignment_real_weight, all_ware_house_accepted_real_weight, ] for item in range(len(list2)): cell = worksheet.cell(row=row_city - 2, column=item + 2, value=list2[item]) value = list2[item] cell.font = Font(size=10, bold=True, color='FFFFFF') if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.fill = PatternFill(start_color="00B050", fill_type="solid") list2 = [ 'مجموع==>', '', '', '', len_poultry, len_all_hatching, all_hathcing_quantitya_all, all_province_requests_quantity, all_province_requests_weight, round(all_province_requests_weight / all_province_requests_quantity, 1) if all_province_requests_quantity > 0 else 0, all_out_poultry_request_quantity, all_out_poultry_request_weight, all_province_requests_weight * 0.75, len_hatching, all_hatching_quantity, all_hatching_lest_over, city_operator_poultry_request_quantity_all, city_operator_poultry_request_weight_all, '', direct_bying_poultry_request_quantity_all, direct_bying_poultry_request_weight_all, '', province_operaor_poultry_request_quantity_all, province_operaor_poultry_request_weight_all, '', city_operator_all_violation_all, all_admin_all_violation, all_admin_all_violation + city_operator_all_violation_all, '', '', '', '', ] create_value(worksheet, list2, l + 1, 2, color='green') for city_operator in city_operator_list: sheet_name = city_operator.unit_name sheet_name1 = sheet_name.split(' ')[-2] + ' ' + sheet_name.split(' ')[-1] worksheet = workbook.create_sheet(f'تعاونی {sheet_name1}') worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') filtered_kill_request = KillHouseRequest.objects.filter( trash=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, province_request__poultry_request__poultry__city_operator=city_operator.unit_name).order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer').values( 'ware_house_confirmation', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer', ) if 'key' in request.GET: if 'role' in request.GET: user = SystemUserProfile.objects.get(key=request.GET['key']) if request.GET['role'] == 'CityOperator': city_operator = CityOperator.objects.get(trash=False, user=user) filtered_kill_reqs = filtered_kill_request.filter( province_request__poultry_request__poultry__city_operator=city_operator.unit_name) elif request.GET['role'] in ['CityJahad', 'CityPoultry']: filtered_kill_reqs = filtered_kill_request.filter( province_request__poultry_request__poultry__user__city=user.city) elif request.GET['role'] == 'VetFarm': vet = Vet.objects.filter(user=user, trash=False) poultries = [] if vet.count() > 0: vet = vet.last() vet_farms = VetFarm.objects.filter(vet=vet, trash=False) if vet_farms.count() > 0: for vet_farm in vet_farms: if vet_farm.poultry in poultries: pass else: poultries.append(vet_farm.poultry) filtered_kill_reqs = filtered_kill_request.filter( province_request__poultry_request__poultry__in=poultries) elif request.GET['role'] == 'KillHouse': filtered_kill_reqs = filtered_kill_request.filter( killhouse_user__kill_house_operator__user=user) else: filtered_kill_reqs = filtered_kill_request else: filtered_kill_reqs = filtered_kill_request else: filtered_kill_reqs = filtered_kill_request poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values( 'province_request__poultry_request')) .only('quantity', 'Index_weight')).annotate( total_quantity=Sum('quantity'), total_weight=Sum(F('quantity') * F('Index_weight')) ) total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'کشتار', 'کدسفارش مرغدار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', 'کشتارکن اختصاصی', 'تلفن کشتارکن اختصاصی', ' محل کشتار ', 'نوع تخصیص', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'وضعیت', 'وضعیت سند', 'وضعیت ورود انبار', 'تعداد لاشه', 'وزن لاشه', 'درصد افت در لحظه', 'درصد افت ورود به انبار', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str header_list = [ 'تعداد بارهای ایجاد شده', 'تعداد بارهای دارای کشتارکن اختصاصی', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'تعداد بارهای دارای کد قرنطینه', 'تعداد بار احراز شده از قرنطینه', 'مجموع تعداد قطعه احراز شده از قرنطینه', 'تعداد تخلیه شده دامپزشک', 'مجموع تعداد تخلیه شده دامپزشک', 'مجموع وزن تخلیه شده دامپزشک', 'تعداد بارهای تکمیل شده', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'تعداد بار های داری سند', 'تعداد بار های وارد شده در انبار', 'مجموع تعداد لاشه', 'مجموع وزن لاشه', 'میانگین درصد افت لاشه ورود به انبار', ] for col_num, option in enumerate(header_list, 9): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 header_list2 = [ 'تعداد درخواست مرغداران', ' مجموع تعداد قطعه درخواست مرغداران', ' مجموع وزن درخواست مرغداران', ] for col_num, option in enumerate(header_list2, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 worksheet['B1'] = f'گزارش بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی {sheet_name}' if filtered_kill_reqs.exists(): name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name'] worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' red_font = Font(color="C00000", bold=True) worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:F1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 all_quantity = 0 all_real_quantity = 0 all_net_weighte = 0 all_weighte = 0 all_vet_state_accepted = len( filtered_kill_reqs.filter(vet_state='accepted')) bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True') accepted_real_quantity = filtered_kill_reqs.aggregate( total_quantity=Sum('accepted_real_quantity')).get( 'total_quantity', 0) accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get( 'total_quantity', 0) all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate( total_quantity=Sum('vet_accepted_real_quantity')).get( 'total_quantity', 0) all_vet_accepted_real_weight = filtered_kill_reqs.aggregate( total_quantity=Sum('vet_accepted_real_weight')).get( 'total_quantity', 0) killer_exclusive = 0 all_assignment_state_archive_state = 0 len_weight_loss = 0 all_state_ware_house_confirmation = 0 if filtered_kill_reqs: for kill in filtered_kill_reqs: if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' l += 1 date_of_inner_bar = '-' vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'), trash=False).select_related('vet__user').only( 'vet__user__fullname', 'vet__user__mobile').values( 'vet__user__fullname', 'vet__user__mobile').first() vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-' vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-' kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'), trash=False).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only( 'create_date').values( 'create_date').first() kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' code = kill.get('clearance_code') if kill.get('clearance_code') else '-' if kill.get('quantity'): quantity = kill.get('quantity') else: quantity = '-' send_date = kill.get('province_request__poultry_request__send_date') date_of_poultry_request = jdatetime.date.fromgregorian( day=send_date.day, month=send_date.month, year=send_date.year ) killers = 'کشتارکن' name_killer_exclusive = '-' mobile_killer_exclusive = '-' if kill.get('killhouse_user__killer') == False: killers = 'کشتارگاه' if kill.get('killer') != None: name_killer_exclusive = kill['killer__name'] mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile']) killer_exclusive += 1 assignment = KillHouseAssignmentInformation.objects.filter( kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight', 'real_quantity').values( 'net_weight', 'real_quantity', 'create_date').first() if assignment: net_weighte = assignment.get('net_weight') real_quantity = assignment.get('real_quantity') vet_check_date = assignment.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) else: net_weighte = '-' real_quantity = '-' if vet_checks: vet_check_date = vet_checks.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) if kill.get('kill_request__slaughter_house') is not None: kill_place = kill.get('kill_request__slaughter_house__name') else: kill_place = '-' vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-' vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-' weight = kill.get('quantity') * kill.get( 'province_kill_request__province_request__poultry_request__Index_weight') quarantine_quantity = '-' if kill['quarantine_quantity'] != None: quarantine_quantity = kill['quarantine_quantity'] else: if kill['quarantine_code_state'] == 'contradiction': quarantine_quantity = 'مغایرت کد رهگیری' elif kill['quarantine_code_state'] == 'noclearance': quarantine_quantity = 'فاقد کد رهگیری' elif kill['quarantine_code_state'] == 'notconfirmed': quarantine_quantity = 'عدم تایید راهداری' elif kill['quarantine_code_state'] == 'merge': quarantine_quantity = 'ادغام' sale_type = 'دولتی' if kill[ 'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد' if kill['province_kill_request__province_request__poultry_request__union'] == True: type = 'فروش آزاد' elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' else: type = 'اتحادیه' age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی' if kill['message'] is not None: state_delete = 'بار حذف شده' else: state_delete = 'فعال' all_quantity += quantity all_weighte += weight all_real_quantity += real_quantity if real_quantity != '-' else 0 all_net_weighte += net_weighte if net_weighte != '-' else 0 if kill['assignment_state_archive'] == 'True': all_assignment_state_archive_state += 1 assignment_state_archive_state = 'وارد شده است' else: assignment_state_archive_state = 'وارد نشده است' ware_house_accepted_real_quantity = kill['ware_house_accepted_real_quantity'] ware_house_accepted_real_weight = kill['ware_house_accepted_real_weight'] weight_loss = round(kill['weight_loss'], 2) if kill['weight_loss'] > 0 else 0 if weight_loss > 0: len_weight_loss += 1 if kill['ware_house_confirmation'] == True: state_ware_house_confirmation = 'ورود به انبار' all_state_ware_house_confirmation += 1 else: state_ware_house_confirmation = '-' weight_loss1 = kill['accepted_real_weight'] - kill['ware_house_accepted_real_weight'] if kill[ 'ware_house_accepted_real_weight'] > 0 else 0 if weight_loss1 < 0: weight_loss1 = weight_loss1 * -1 total_weight_loss = (weight_loss1 / kill['accepted_real_weight']) * 100 if kill[ 'accepted_real_weight'] != 0 else 0 list1 = [ m, str(kill.get('bar_code')), str(date_of_poultry_request), freez_state, str(kill.get('province_request__poultry_request__order_code')), kill.get('province_request__poultry_request__poultry__unit_name'), str(kill.get('province_request__poultry_request__poultry__user__mobile')), kill.get('province_request__poultry_request__poultry__user__city__name'), sale_type, age, kill.get('province_request__poultry_request__amount') if kill.get( 'province_request__poultry_request__amount') else '-', kill.get('province_request__poultry_request__chicken_breed'), vet_farm_name, vet_farm_mobile, killers, kill.get('killhouse_user__name'), kill.get('killhouse_user__kill_house_operator__user__mobile'), kill.get('killhouse_user__system_address__city__name'), name_killer_exclusive, mobile_killer_exclusive, kill_place, type, kill_house_vet_name, kill_house_vet_mobile, kill.get('add_car__driver__driver_name'), kill.get('add_car__driver__driver_mobile'), kill.get('add_car__driver__type_car'), str(kill.get('traffic_code')), quantity, weight, code, quarantine_quantity, state, str(date_of_inner_bar), vet_quantity, vet_wight, real_quantity, net_weighte, kill['accepted_real_quantity'], kill['accepted_real_weight'], state_delete, assignment_state_archive_state, state_ware_house_confirmation, ware_house_accepted_real_quantity, ware_house_accepted_real_weight, f'%{round(total_weight_loss, 2)}', f'%{weight_loss}', ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] if isinstance(value, (int)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values if list1[40] == 'بار حذف شده': cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid") worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False)) all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get( 'total_quantity', 0) has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False)) all_ware_house_accepted_real_quantity = filtered_kill_reqs.aggregate( total_quantity=Sum('ware_house_accepted_real_quantity')).get( 'total_quantity') or 0 all_ware_house_accepted_real_weight = filtered_kill_reqs.aggregate( total_quantity=Sum('ware_house_accepted_real_weight')).get( 'total_quantity', 0) or 0 all_weight_loss = filtered_kill_reqs.aggregate( total_quantity=Sum('weight_loss')).get( 'total_quantity', 0) or 0 all_weight_loss = round(all_weight_loss / len_weight_loss, 2) if all_weight_loss > 0 else 0 value_header_list = [ len(filtered_kill_reqs), killer_exclusive, all_quantity, all_weighte, has_code, has_qarantine, all_quarantine_quantity if all_quarantine_quantity != None else 0, all_vet_state_accepted, all_vet_accepted_real_quantity, all_vet_accepted_real_weight, len(bar_complete), all_real_quantity, all_net_weighte, accepted_real_quantity if accepted_real_quantity != None else 0, accepted_real_wight if accepted_real_wight != None else 0, all_assignment_state_archive_state, all_state_ware_house_confirmation, all_ware_house_accepted_real_quantity, all_ware_house_accepted_real_weight, all_weight_loss ] for item in range(len(value_header_list)): cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item]) value = value_header_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) value_header_list2 = [ len(poultry_request), total_requests_quantity, total_requests_weight ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_kill_request_quantity, all_weighte, '', all_quarantine_quantity if all_quarantine_quantity != None else 0, '', '', all_vet_accepted_real_quantity, all_vet_accepted_real_weight, all_real_quantity, all_net_weighte, accepted_real_quantity if accepted_real_quantity != None else 0, accepted_real_wight if accepted_real_wight != None else 0, '', '', '', all_ware_house_accepted_real_quantity, all_ware_house_accepted_real_weight, '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 kill_house_total_transactions_wage_payid_admin_x_excel(request): filterset_class = KillHouseFilterSet filterset_fields = [ 'name', 'kill_house_operator__user__fullname', 'kill_house_operator__user__mobile', 'system_address__city__name', ] date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None kill_house_list = [] excel_options = [ 'ردیف', 'تاریخ پرداخت', 'نوع پرداخت', 'نام پرداخت کننده', 'تلفن پرداخت کننده', 'شماره درخواست', 'شماره پیگیری', 'کد سفارش', 'شماره کارت', 'مبلغ تراکنش(ریال)', 'سهم اتحادیه(ریال)', 'سهم شرکت(ریال)', 'سهم اصناف(ریال)', 'سهم دامپزشک(ریال)', ] output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) sheet_name = 'اطلاعات کلی' worksheet = workbook.create_sheet(sheet_name) if sheet_name == 'اطلاعات کلی': worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') if 'date1' in request.GET: from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) worksheet['B2'] = f'اطلاعات کلی تعرفه {from_date_1} تا {from_date_2}' merge_range1 = 'B2:C2' worksheet.merge_cells(merge_range1) worksheet['B2'].font = Font(color="C00000", bold=True) worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) worksheet['B5'] = f'جزئیات {from_date_1} تا {from_date_2}' worksheet['B5'].font = Font(color="C00000", bold=True) worksheet['B5'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) else: # worksheet['B2'] = 'اطلاعات کلی تعرفه(از 1403/01/01 به بعد)' worksheet['B2'].font = Font(color="C00000") worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = 'B2:C2' worksheet.merge_cells(merge_range1) worksheet['B5'] = f'جزئیات' worksheet['B5'].font = Font(color="C00000", bold=True) worksheet['B5'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) header_list1 = [ 'کل تعرفه (ریال)', 'سهم اتحادیه', 'سهم شرکت', 'سهم صنف', 'سهم دامپزشک', 'کل تعرفه پرداخت شده (ریال)', 'سهم پرداخت شده اتحادیه (ریال)', 'سهم پرداخت شده شرکت (ریال)', 'سهم پرداخت شده اصناف (ریال)', 'سهم پرداخت شده دامپزشک (ریال)', 'مجموع تخفیفات (ریال)', 'کل تعرفه پرداخت نشده (ریال)', 'سهم پرداخت نشده اتحادیه (ریال)', 'سهم پرداخت نشده شرکت (ریال)', 'سهم پرداخت نشده اصناف (ریال)', 'سهم پرداخت نشده دامپزشک (ریال)', ] for col_num, option in enumerate(header_list1, 4): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='FFFFFF') worksheet.row_dimensions[2].height = 35 worksheet.column_dimensions[col_letter].width = 18 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) try: total_wage = TotalWageInformation.objects.get(trash=False) except: total_wage = TotalWageInformation() total_wage.save() serializer_total_wage_information = TotalWageInformationSerializer(total_wage, context={'request': request}).data wage_info = serializer_total_wage_information.get('wage_info', {}) shares = wage_info.get('shares', []) company_data = next((item for item in shares if item["name"] == "شرکت"), None) etehadiye_data = next((item for item in shares if item["name"] == "اتحادیه"), None) sanf_protein_data = next((item for item in shares if item["name"] == "صنف پروتئین"), None) dampezshk_data = next((item for item in shares if item["name"] == "دامپزشک"), None) values_list = [ wage_info.get('total_wage', 0), etehadiye_data['total_wage'], company_data['total_wage'], sanf_protein_data['total_wage'], dampezshk_data['total_wage'], wage_info.get('total_paid_wage', 0), etehadiye_data['total_paid_wage'], company_data['total_paid_wage'], sanf_protein_data['total_paid_wage'], dampezshk_data['total_paid_wage'], wage_info.get('off', 0), wage_info.get('total_unpaid_wage', 0), etehadiye_data['total_unpaid_wage'], company_data['total_unpaid_wage'], sanf_protein_data['total_unpaid_wage'], dampezshk_data['total_unpaid_wage'], ] create_value(worksheet, values_list, 3, 4, border_style='thin') kill_houses = KillHouse.objects.filter(trash=False).exclude(out_province=True).order_by('id') kill_houses = KillHouseForNewWageInormationSerializer(kill_houses, many=True, context={'request': request}).data if wage_info['wage_counting_type'] == 'carcass': l = 15 m = 1 header_list2 = [ "وزن کل فروش به خارج از استان ", "تعرفه کل فروش به خارج از استان(ریال)", "کل وزن زنده کشتار داخل استان(کیلوگرم)", "کل وزن لاشه کشتار داخل استان(کیلوگرم)", "وزن توزیع لاشه داخل استان(کیلوگرم)", "تعرفه توزیع لاشه داخل استان(ریال)", "وزن توزیع لاشه به خارج از استان(کیلوگرم)", "تعرفه توزیع لاشه به خارج از استان(ریال)", "وزن لاشه ورودی به استان(کیلوگرم)", "تعرفه لاشه ورودی به استان(ریال)", "وزن مرغ زنده ورودی به استان(کیلوگرم)", "تعرفه مرغ زنده ورودی به استان(ریال)", "وزن خرید های بازگشتی(کیلوگرم)", "تعرفه خرید های بازگشتی(ریال)", ] values_list2 = [ wage_info.get('out_province_poultry_request_weight', 0), wage_info.get('out_province_poultry_request_wage', 0), wage_info.get('total_province_live_weight', 0), wage_info.get('total_province_carcasses_weight', 0), wage_info.get('province_kill_requests_total_weight', 0), wage_info.get('province_kill_requests_total_wage', 0), wage_info.get('free_bars_out_province_carcases_total_weight', 0), wage_info.get('free_bars_out_province_carcases_total_wage', 0), wage_info.get('free_bars_carcases_total_weight', 0), wage_info.get('free_bars_carcases_total_wage', 0), wage_info.get('free_bars_live_total_weight', 0), wage_info.get('free_bars_live_total_wage', 0), wage_info.get('return_total_province_live_weight', 0), wage_info.get('total_return_pure_province_carcasses_price', 0), ] header_list5 = [ 'سهم', 'تعرفه فروش مرغ زنده به خارج از استان(ریال)', 'تعرفه توزیع لاشه به داخل استان(ریال)', 'تعرفه توزیع لاشه خارج استان(ریال)', 'تعرفه لاشه ورودی به استان(ریال)', 'تعرفه مرغ زنده ورودی به استان(ریال)', 'تعرفه کل(ریال)', 'تعرفه پرداخت شده(ریال)', 'تعرفه پرداخت نشده(ریال)', ] header_list = [ 'ردیف', 'کشتارگاه', 'کل تعرفه (ریال)', 'سهم اتحادیه (ریال)', 'سهم شرکت (ریال)', 'سهم صنف (ریال)', 'سهم دامپزشک (ریال)', 'کل تعرفه پرداخت شده (ریال)', 'سهم اتحادیه از واریزی(ریال)', 'سهم شرکت از واریزی(ریال)', 'سهم اصناف از واریزی(ریال)', 'سهم دامپزشک از واریزی(ریال)', 'تخفیفات (ریال)', 'کل تعرفه پرداخت نشده (ریال)', ' سهم اتحادیه پرداخت نشده', ' سهم شرکت پرداخت نشده', 'سهم صنف پرداخت نشده', 'سهم دامپزشک پرداخت نشده', 'کل وزن زنده کشتار داخل استان', 'وزن لاشه کشتار داخل استان', 'وزن توزیع لاشه کشتار داخل استان', 'تعرفه توزیع لاشه کشتار داخل استان', 'وزن توزیع لاشه به خارج استان', 'تعرفه توزیع لاشه به خارج استان', 'وزن لاشه ورودی به استان', 'تعرفه لاشه ورودی به استان', 'وزن مرغ زنده ورودی به استان', 'تعرفه مرغ زنده ورودی به استان', 'وزن خریدهای بازگشتی', 'تعرفه خریدهای بازگشتی', ] for kill_house in kill_houses: wage_info2 = kill_house.get('wage_info', {}) shares2 = kill_house.get('shares', []) company_data2 = next((item for item in shares2 if item["name"] == "شرکت"), None) etehadiye_data2 = next((item for item in shares2 if item["name"] == "اتحادیه"), None) sanf_protein_data2 = next((item for item in shares2 if item["name"] == "صنف پروتئین"), None) dampezshk_data2 = next((item for item in shares2 if item["name"] == "دامپزشک"), None) values_list3 = [ m, kill_house['name'], wage_info2['total_wage'], etehadiye_data2['total_wage'], company_data2['total_wage'], sanf_protein_data2['total_wage'], dampezshk_data2['total_wage'], wage_info2.get('total_paid_wage', 0), etehadiye_data2['total_paid_wage'], company_data2['total_paid_wage'], sanf_protein_data2['total_paid_wage'], dampezshk_data2['total_paid_wage'], wage_info2.get('off', 0), wage_info2.get('total_unpaid_wage', 0), etehadiye_data2['total_unpaid_wage'], company_data2['total_unpaid_wage'], sanf_protein_data2['total_unpaid_wage'], dampezshk_data2['total_unpaid_wage'], wage_info2.get('total_province_live_weight', 0), wage_info2.get('total_province_carcasses_weight', 0), wage_info2.get('province_kill_requests_total_weight', 0), wage_info2.get('province_kill_requests_total_wage', 0), wage_info2.get('free_bars_out_province_carcases_total_weight', 0), wage_info2.get('free_bars_out_province_carcases_total_wage', 0), wage_info2.get('free_bars_carcases_total_weight', 0), wage_info2.get('free_bars_carcases_total_wage', 0), wage_info2.get('free_bars_live_total_weight', 0), wage_info2.get('free_bars_live_total_wage', 0), wage_info2.get('return_total_province_live_weight', 0), wage_info2.get('total_return_pure_province_carcasses_price', 0), ] for item in range(len(values_list3)): cell = worksheet.cell(row=l, column=item + 1, value=values_list3[item]) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_list3[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) l += 1 m += 1 if int(wage_info2.get('total_paid_wage')) > 0: if kill_house not in kill_house_list: kill_house_list.append({"name": kill_house['name']}) list2 = [ "مجموع==>", "", sum(kill_house.get('wage_info', {}).get('total_wage', 0) for kill_house in kill_houses), sum(next( (item.get("total_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "اتحادیه"), 0) for kill_house in kill_houses), sum(next((item.get("total_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "شرکت"), 0) for kill_house in kill_houses), sum(next((item.get("total_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "صنف پروتئین"), 0) for kill_house in kill_houses), sum(next( (item.get("total_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "دامپزشک"), 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_paid_wage', 0) for kill_house in kill_houses), sum(next((item.get("total_paid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "اتحادیه"), 0) for kill_house in kill_houses), sum(next( (item.get("total_paid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "شرکت"), 0) for kill_house in kill_houses), sum(next((item.get("total_paid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "صنف پروتئین"), 0) for kill_house in kill_houses), sum(next((item.get("total_paid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "دامپزشک"), 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('off', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_unpaid_wage', 0) for kill_house in kill_houses), sum(next((item.get("total_unpaid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "اتحادیه"), 0) for kill_house in kill_houses), sum(next((item.get("total_unpaid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "شرکت"), 0) for kill_house in kill_houses), sum(next((item.get("total_unpaid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "صنف پروتئین"), 0) for kill_house in kill_houses), sum(next((item.get("total_unpaid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "دامپزشک"), 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_province_live_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_province_carcasses_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('province_kill_requests_total_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('province_kill_requests_total_wage', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_out_province_carcases_total_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_out_province_carcases_total_wage', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_carcases_total_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_carcases_total_wage', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_live_total_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_live_total_wage', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('return_total_province_live_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_return_pure_province_carcasses_price', 0) for kill_house in kill_houses), ] else: l = 15 m = 1 header_list2 = [ "وزن کل فروش به خارج از استان ", "تعرفه کل فروش به خارج از استان(ریال)", "کل وزن زنده کشتار داخل استان(کیلوگرم)", "تعرفه کشتار داخل استان(کیلوگرم)", "وزن توزیع لاشه به خارج از استان(کیلوگرم)", "تعرفه توزیع لاشه به خارج از استان(ریال)", "وزن لاشه ورودی به استان(کیلوگرم)", "تعرفه لاشه ورودی به استان(ریال)", "وزن مرغ زنده ورودی به استان(کیلوگرم)", "تعرفه مرغ زنده ورودی به استان(ریال)", "وزن خرید های بازگشتی(کیلوگرم)", "تعرفه خرید های بازگشتی(ریال)", ] values_list2 = [ wage_info.get('out_province_poultry_request_weight', 0), wage_info.get('out_province_poultry_request_wage', 0), wage_info.get('total_province_live_weight', 0), wage_info.get('province_kill_requests_total_wage', 0), wage_info.get('free_bars_out_province_carcases_total_weight', 0), wage_info.get('free_bars_out_province_carcases_total_wage', 0), wage_info.get('free_bars_carcases_total_weight', 0), wage_info.get('free_bars_carcases_total_wage', 0), wage_info.get('free_bars_live_total_weight', 0), wage_info.get('free_bars_live_total_wage', 0), wage_info.get('return_total_province_live_weight', 0), wage_info.get('total_return_pure_province_carcasses_price', 0), ] header_list5 = [ 'سهم', 'تعرفه فروش مرغ زنده به خارج از استان(ریال)', 'تعرفه کشتار داخل استان(ریال)', 'تعرفه توزیع لاشه خارج استان(ریال)', 'تعرفه لاشه ورودی به استان(ریال)', 'تعرفه مرغ زنده ورودی به استان(ریال)', 'تعرفه کل(ریال)', 'تعرفه پرداخت شده(ریال)', 'تعرفه پرداخت نشده(ریال)', ] header_list = [ 'ردیف', 'کشتارگاه', 'کل تعرفه (ریال)', 'سهم اتحادیه (ریال)', 'سهم شرکت (ریال)', 'سهم صنف (ریال)', 'سهم دامپزشک (ریال)', 'کل تعرفه پرداخت شده (ریال)', 'سهم اتحادیه از واریزی(ریال)', 'سهم شرکت از واریزی(ریال)', 'سهم اصناف از واریزی(ریال)', 'سهم دامپزشک از واریزی(ریال)', 'تخفیفات (ریال)', 'کل تعرفه پرداخت نشده (ریال)', ' سهم اتحادیه پرداخت نشده', ' سهم شرکت پرداخت نشده', 'سهم صنف پرداخت نشده', 'سهم دامپزشک پرداخت نشده', 'کل وزن زنده کشتار داخل استان', 'تعرفه کشتار داخل استان', 'وزن توزیع لاشه به خارج استان', 'تعرفه توزیع لاشه به خارج استان', 'وزن لاشه ورودی به استان', 'تعرفه لاشه ورودی به استان', 'وزن مرغ زنده ورودی به استان', 'تعرفه مرغ زنده ورودی به استان', 'وزن خریدهای بازگشتی', 'تعرفه خریدهای بازگشتی', ] for kill_house in kill_houses: wage_info2 = kill_house.get('wage_info', {}) shares2 = kill_house.get('shares', []) company_data2 = next((item for item in shares2 if item["name"] == "شرکت"), None) etehadiye_data2 = next((item for item in shares2 if item["name"] == "اتحادیه"), None) sanf_protein_data2 = next((item for item in shares2 if item["name"] == "صنف پروتئین"), None) dampezshk_data2 = next((item for item in shares2 if item["name"] == "دامپزشک"), None) values_list3 = [ m, kill_house['name'], wage_info2['total_wage'], etehadiye_data2['total_wage'], company_data2['total_wage'], sanf_protein_data2['total_wage'], dampezshk_data2['total_wage'], wage_info2.get('total_paid_wage', 0), etehadiye_data2['total_paid_wage'], company_data2['total_paid_wage'], sanf_protein_data2['total_paid_wage'], dampezshk_data2['total_paid_wage'], wage_info2.get('off', 0), wage_info2.get('total_unpaid_wage', 0), etehadiye_data2['total_unpaid_wage'], company_data2['total_unpaid_wage'], sanf_protein_data2['total_unpaid_wage'], dampezshk_data2['total_unpaid_wage'], wage_info2.get('total_province_live_weight', 0), wage_info2.get('province_kill_requests_total_wage', 0), wage_info2.get('free_bars_out_province_carcases_total_weight', 0), wage_info2.get('free_bars_out_province_carcases_total_wage', 0), wage_info2.get('free_bars_carcases_total_weight', 0), wage_info2.get('free_bars_carcases_total_wage', 0), wage_info2.get('free_bars_live_total_weight', 0), wage_info2.get('free_bars_live_total_wage', 0), wage_info2.get('return_total_province_live_weight', 0), wage_info2.get('total_return_pure_province_carcasses_price', 0), ] for item in range(len(values_list3)): cell = worksheet.cell(row=l, column=item + 1, value=values_list3[item]) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_list3[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) l += 1 m += 1 if int(wage_info2.get('total_paid_wage')) > 0: if kill_house not in kill_house_list: kill_house_list.append({"name": kill_house['name']}) list2 = [ "مجموع==>", "", sum(kill_house.get('wage_info', {}).get('total_wage', 0) for kill_house in kill_houses), sum(next( (item.get("total_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "اتحادیه"), 0) for kill_house in kill_houses), sum(next((item.get("total_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "شرکت"), 0) for kill_house in kill_houses), sum(next( (item.get("total_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "صنف پروتئین"), 0) for kill_house in kill_houses), sum(next( (item.get("total_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "دامپزشک"), 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_paid_wage', 0) for kill_house in kill_houses), sum(next( (item.get("total_paid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "اتحادیه"), 0) for kill_house in kill_houses), sum(next( (item.get("total_paid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "شرکت"), 0) for kill_house in kill_houses), sum(next((item.get("total_paid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "صنف پروتئین"), 0) for kill_house in kill_houses), sum(next( (item.get("total_paid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "دامپزشک"), 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('off', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_unpaid_wage', 0) for kill_house in kill_houses), sum(next((item.get("total_unpaid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "اتحادیه"), 0) for kill_house in kill_houses), sum(next( (item.get("total_unpaid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "شرکت"), 0) for kill_house in kill_houses), sum(next((item.get("total_unpaid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "صنف پروتئین"), 0) for kill_house in kill_houses), sum(next((item.get("total_unpaid_wage", 0) for item in kill_house.get("shares", []) if item["name"] == "دامپزشک"), 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_province_live_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('province_kill_requests_total_wage', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_out_province_carcases_total_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_out_province_carcases_total_wage', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_carcases_total_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_carcases_total_wage', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_live_total_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('free_bars_live_total_wage', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('return_total_province_live_weight', 0) for kill_house in kill_houses), sum(kill_house.get('wage_info', {}).get('total_return_pure_province_carcasses_price', 0) for kill_house in kill_houses), ] for item in range(len(list2)): cell = worksheet.cell(row=l, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=9, bold=True) cell.fill = PatternFill(start_color="FFFF00", fill_type="solid") for col_num, option in enumerate(header_list, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=14, column=col_num, value=option) if option in ['کل تعرفه (ریال)', 'سهم شرکت (ریال)', 'سهم اتحادیه (ریال)', 'سهم صنف (ریال)', 'سهم دامپزشک (ریال)']: cell.fill = PatternFill(start_color="76933C", fill_type="solid") elif option in ['کل تعرفه پرداخت نشده (ریال)', 'کل تعرفه پرداخت نشده (ریال)', ' سهم شرکت پرداخت نشده', 'سهم دامپزشک پرداخت نشده', ' سهم اتحادیه پرداخت نشده', 'سهم صنف پرداخت نشده']: cell.fill = PatternFill(start_color="E26B0A", fill_type="solid") elif option in ['تعداد بار', 'حجم بار', 'وزن بار']: cell.fill = PatternFill(start_color="163CB6", fill_type="solid") elif option in ['تعداد تخصیص بدون بار', 'حجم تخصیص بدون بار', 'وزن تخصیص بدون بار', ]: cell.fill = PatternFill(start_color="476DE7", fill_type="solid") else: cell.fill = PatternFill(start_color="31869B", fill_type="solid") cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.font = Font(size=10, bold=True, color='FFFFFF') worksheet.row_dimensions[14].height = 45 worksheet.column_dimensions[col_letter].width = 27 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) create_value(worksheet, values_list2, 6, 3, border_style='thin') for col_num, option in enumerate(header_list2, 3): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=5, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='FFFFFF') worksheet.row_dimensions[5].height = 35 worksheet.column_dimensions[col_letter].width = 18 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) for col_num, option in enumerate(header_list5, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=8, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="1E487B", fill_type="solid") cell.font = Font(size=10, bold=True, color='FFFFFF') worksheet.row_dimensions[8].height = 25 worksheet.column_dimensions[col_letter].width = 20 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) values_union = [ etehadiye_data['name'], etehadiye_data['out_province_poultry_request_wage'], etehadiye_data['province_kill_request_wage'], etehadiye_data['free_sell_carcasses_wage'], etehadiye_data['free_buying_carcasses_wage'], etehadiye_data['free_buying_live_wage'], etehadiye_data['total_wage'], etehadiye_data['total_paid_wage'], etehadiye_data['total_unpaid_wage'], ] for item in range(len(values_union)): cell = worksheet.cell(row=9, column=item + 1, value=values_union[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_union[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) values_company = [ company_data['name'], company_data['out_province_poultry_request_wage'], company_data['province_kill_request_wage'], company_data['free_sell_carcasses_wage'], company_data['free_buying_carcasses_wage'], company_data['free_buying_live_wage'], company_data['total_wage'], company_data['total_paid_wage'], company_data['total_unpaid_wage'], ] for item in range(len(values_company)): cell = worksheet.cell(row=10, column=item + 1, value=values_company[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_company[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) values_guild = [ sanf_protein_data['name'], sanf_protein_data['out_province_poultry_request_wage'], sanf_protein_data['province_kill_request_wage'], sanf_protein_data['free_sell_carcasses_wage'], sanf_protein_data['free_buying_carcasses_wage'], sanf_protein_data['free_buying_live_wage'], sanf_protein_data['total_wage'], sanf_protein_data['total_paid_wage'], sanf_protein_data['total_unpaid_wage'], ] for item in range(len(values_guild)): cell = worksheet.cell(row=11, column=item + 1, value=values_guild[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_guild[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) values_other = [ dampezshk_data['name'], dampezshk_data['out_province_poultry_request_wage'], dampezshk_data['province_kill_request_wage'], dampezshk_data['free_sell_carcasses_wage'], dampezshk_data['free_buying_carcasses_wage'], dampezshk_data['free_buying_live_wage'], dampezshk_data['total_wage'], dampezshk_data['total_paid_wage'], dampezshk_data['total_unpaid_wage'], ] for item in range(len(values_other)): cell = worksheet.cell(row=12, column=item + 1, value=values_other[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = values_other[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) for kill_house in kill_house_list: sheet_name = kill_house['name'] worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') worksheet.column_dimensions[col_letter].width = 20.01 worksheet.row_dimensions[2].height = 27 worksheet.freeze_panes = worksheet['A3'] max_col = worksheet.max_column range_str = f'A2:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str l = 1 m = 1 kill_house = KillHouse.objects.get(name=sheet_name, trash=False) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).order_by('id') else: transactions = InternalTransaction.objects.filter( Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), status='completed', trash=False).order_by('id') for transaction in transactions: if transaction.kill_house != None: fullname = transaction.kill_house.kill_house_operator.user.fullname mobile = transaction.kill_house.kill_house_operator.user.mobile else: fullname = transaction.chain_company.user.fullname mobile = transaction.chain_company.user.mobile date = convert_to_shamsi( datetime=transaction.date ) type = 'دستی' if transaction.transaction_type == 'wage-gateway-manual' else 'آنلاین' if request.GET['role'] == 'ProvinceOperator': amout = transaction.union_share elif request.GET['role'] == 'Company': amout = transaction.company_share elif request.GET['role'] == 'Guilds': amout = transaction.guilds_share else: amout = transaction.amount list1 = [ m, date, type, fullname, mobile, transaction.orderId, transaction.saleReferenceId, transaction.orderId, transaction.cardHolderPan, amout, transaction.union_share, transaction.company_share, transaction.guilds_share, transaction.other_share, ] l += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values m += 1 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 buy_outside_the_province_excel(request): now = datetime.datetime.now().date() date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date() if 'start' in request.GET else now date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date() if 'end' in request.GET else now filterset_class = KillHouseRequestFilterSet filterset_fields = [ 'killhouse_user__kill_house_operator__user__fullname', 'killhouse_user__kill_house_operator__user__mobile', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__order_code', 'province_request__poultry_request__order_code', 'bar_code', ] filtered_kill_request = KillHouseRequest.objects.filter( trash=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2).order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'province_kill_request__province_request__poultry_request__out', 'killer__name', 'killhouse_user__type', 'killer').values('kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_confirmation', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'province_kill_request__province_request__poultry_request__out', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer', ) user = SystemUserProfile.objects.get(key=request.GET['key']) if request.GET['role'] == 'CityOperator': city_operator = CityOperator.objects.get(trash=False, user=user) filtered_kill_reqs = filtered_kill_request.filter( province_request__poultry_request__poultry__city_operator=city_operator.unit_name) elif request.GET['role'] in ['CityJahad', 'CityPoultry']: filtered_kill_reqs = filtered_kill_request.filter( province_request__poultry_request__poultry__user__city=user.city) elif request.GET['role'] == 'VetFarm': vet = Vet.objects.filter(user=user, trash=False) poultries = [] if vet.count() > 0: vet = vet.last() vet_farms = VetFarm.objects.filter(vet=vet, trash=False) if vet_farms.count() > 0: for vet_farm in vet_farms: if vet_farm.poultry in poultries: pass else: poultries.append(vet_farm.poultry) filtered_kill_reqs = filtered_kill_request.filter( province_request__poultry_request__poultry__in=poultries) elif request.GET['role'] == 'KillHouse': filtered_kill_reqs = filtered_kill_request.filter(killhouse_user__kill_house_operator__user=user) else: filtered_kill_reqs = filtered_kill_request if request.GET['role'] == 'KillHouse': kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False) elif request.GET['role'] == 'KillHouseVet': kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house') kill_house = kill_house_vets.values_list('kill_house', flat=True).distinct() else: kill_house = KillHouse.objects.filter(system_address__province=user.province, trash=False) if 'state' in request.GET: if request.GET['state'] == 'completed': filtered_kill_reqs = filtered_kill_reqs.filter(assignment_state_archive='True') elif request.GET['state'] == 'bar_pending': filtered_kill_reqs = filtered_kill_reqs.filter( (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q( killer__in=kill_house)), assignment_state_archive='pending') else: filtered_kill_reqs = filtered_kill_reqs else: filtered_kill_reqs = filtered_kill_reqs if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=filtered_kill_reqs ) ).filter(): ps = filterset_class(data=query, queryset=filtered_kill_reqs) filtered_kill_reqs = ps.filter() poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values( 'province_request__poultry_request')) .only('quantity', 'Index_weight')).annotate( total_quantity=Sum('quantity'), total_weight=Sum(F('quantity') * F('Index_weight')) ) total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] or 0 total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0 excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'نوع کشتار', 'کدسفارش مرغدار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', 'کشتارکن اختصاصی', 'تلفن کشتارکن اختصاصی', ' محل کشتار ', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'وضعیت', 'وضعیت سند', 'وضعیت ورود انبار', 'تعداد لاشه', 'وزن لاشه', 'درصد افت', 'کشور مقصد', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) header_list = [ 'تعداد بارهای ایجاد شده', 'تعداد بارهای دارای کشتارکن اختصاصی', 'مجموع حجم بارها', 'مجموع وزن بارها', 'میانگین وزن ', 'کمترین سن', 'بیشترین سن', 'میانگین سنی', 'تعداد بارهای دارای کد قرنطینه', 'حجم بارهای دارای کد قرنطینه', 'تعداد بار احراز شده از قرنطینه', 'مجموع تعداد قطعه احراز شده از قرنطینه', 'تعداد بار فاقد قرنطینه', 'حجم بار فاقد قرنطینه', ' تعداد بارهایی که در قرنطینه و رصدیار اختلاف دارند', 'تعداد تخلیه شده دامپزشک', 'مجموع تعداد تخلیه شده دامپزشک', 'مجموع وزن تخلیه شده دامپزشک', 'تعداد بارهای تکمیل شده', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'تعداد بار های وارد شده در انبار', 'مجموع تعداد لاشه', 'مجموع وزن لاشه', 'میانگین درصد افت لاشه', ] header_list2 = [ 'تعداد درخواست مرغداران', ' مجموع تعداد قطعه درخواست مرغداران', ' مجموع وزن درخواست مرغداران', ] for col_num, option in enumerate(header_list, 9): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 for col_num, option in enumerate(header_list2, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str worksheet['B1'] = f'گزارش بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی' if filtered_kill_reqs.exists(): name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name'] worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 all_age = [] all_quantity = 0 all_real_quantity = 0 all_net_weighte = 0 all_weighte = 0 all_vet_state_accepted = len( filtered_kill_reqs.filter(vet_state='accepted')) bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True') accepted_real_quantity = filtered_kill_reqs.aggregate( total_quantity=Sum('accepted_real_quantity')).get( 'total_quantity') or 0 accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get( 'total_quantity') or 0 all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity') or 0 all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate( total_quantity=Sum('vet_accepted_real_quantity')).get( 'total_quantity') or 0 all_vet_accepted_real_weight = filtered_kill_reqs.aggregate( total_quantity=Sum('vet_accepted_real_weight')).get( 'total_quantity') or 0 killer_exclusive = 0 all_assignment_state_archive_state = 0 len_weight_loss = 0 all_state_ware_house_confirmation = 0 if filtered_kill_reqs: for kill in filtered_kill_reqs: age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if age not in all_age: all_age.append(age) if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' l += 1 date_of_inner_bar = '-' vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'), trash=False).select_related('vet__user').only('vet__user__fullname', 'vet__user__mobile').values( 'vet__user__fullname', 'vet__user__mobile').first() vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-' vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-' kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'), trash=False).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only( 'create_date').values( 'create_date').first() kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' code = kill.get('clearance_code') if kill.get('clearance_code') else '-' if kill.get('quantity'): quantity = kill.get('quantity') else: quantity = '-' send_date = kill.get('province_request__poultry_request__send_date') date_of_poultry_request = jdatetime.date.fromgregorian( day=send_date.day, month=send_date.month, year=send_date.year ) killers = 'کشتارکن' name_killer_exclusive = '-' mobile_killer_exclusive = '-' if kill.get('killhouse_user__killer') == False: killers = 'کشتارگاه' if kill.get('killer') != None: name_killer_exclusive = kill['killer__name'] mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile']) killer_exclusive += 1 assignment = KillHouseAssignmentInformation.objects.filter( kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight', 'real_quantity').values( 'net_weight', 'real_quantity', 'create_date').first() if assignment: net_weighte = int(assignment.get('net_weight')) real_quantity = assignment.get('real_quantity') vet_check_date = assignment.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) else: net_weighte = '-' real_quantity = '-' if vet_checks: vet_check_date = vet_checks.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) if kill.get('kill_request__slaughter_house') is not None: kill_place = kill.get('kill_request__slaughter_house__name') else: kill_place = '-' vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-' vet_wight = int(kill['vet_accepted_real_weight']) if kill['vet_accepted_real_weight'] else '-' weight = int(kill.get('quantity') * kill.get( 'province_kill_request__province_request__poultry_request__Index_weight')) quarantine_quantity = '-' if kill['quarantine_quantity'] != None: quarantine_quantity = kill['quarantine_quantity'] else: if kill['quarantine_code_state'] == 'contradiction': quarantine_quantity = 'مغایرت کد رهگیری' elif kill['quarantine_code_state'] == 'noclearance': quarantine_quantity = 'فاقد کد رهگیری' elif kill['quarantine_code_state'] == 'notconfirmed': quarantine_quantity = 'عدم تایید راهداری' elif kill['quarantine_code_state'] == 'merge': quarantine_quantity = 'ادغام' export_country = '-' sale_type = 'دولتی' if kill[ 'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد' if kill['province_kill_request__province_request__poultry_request__out'] == True: type = 'خارج از استان' elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' elif kill['province_request__poultry_request__freezing'] == True: type = 'انجماد' elif kill['province_request__poultry_request__export'] == True: type = 'صادرات' export_country = kill['kill_request__export_country'] else: type = 'عادی' age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی' if kill['message'] is not None: state_delete = 'بار حذف شده' else: state_delete = 'فعال' all_quantity += quantity all_weighte += weight all_real_quantity += real_quantity if real_quantity != '-' else 0 all_net_weighte += net_weighte if net_weighte != '-' else 0 ware_house_accepted_real_quantity = kill['ware_house_accepted_real_quantity'] ware_house_accepted_real_weight = kill['ware_house_accepted_real_weight'] weight_loss = round(kill['weight_loss'], 2) if kill['weight_loss'] > 0 else 0 if weight_loss > 0: len_weight_loss += 1 if kill['ware_house_confirmation'] == True: state_ware_house_confirmation = 'ورود به انبار' all_state_ware_house_confirmation += 1 else: state_ware_house_confirmation = '-' list1 = [ m, str(kill.get('bar_code')), str(date_of_poultry_request), type, str(kill.get('province_request__poultry_request__order_code')), kill.get('province_request__poultry_request__poultry__unit_name'), str(kill.get('province_request__poultry_request__poultry__user__mobile')), kill.get('province_request__poultry_request__poultry__user__city__name'), sale_type, age, kill.get('province_request__poultry_request__amount') if kill.get( 'province_request__poultry_request__amount') else '-', kill.get('province_request__poultry_request__chicken_breed'), vet_farm_name, vet_farm_mobile, killers, kill.get('killhouse_user__name'), kill.get('killhouse_user__kill_house_operator__user__mobile'), kill.get('killhouse_user__system_address__city__name'), name_killer_exclusive, mobile_killer_exclusive, kill_place, kill_house_vet_name, kill_house_vet_mobile, kill.get('add_car__driver__driver_name'), kill.get('add_car__driver__driver_mobile'), kill.get('add_car__driver__type_car'), str(kill.get('traffic_code')), quantity, weight, code, quarantine_quantity, state, str(date_of_inner_bar), vet_quantity, vet_wight, real_quantity, net_weighte, kill['accepted_real_quantity'], int(kill['accepted_real_weight']), state_delete, kill['document_status'] if kill['document_status'] else '-', state_ware_house_confirmation, ware_house_accepted_real_quantity, int(ware_house_accepted_real_weight), f'%{weight_loss}', export_country, ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] if isinstance(value, (int)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values if list1[40] == 'بار حذف شده': cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid") worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') all_age1 = sorted(all_age) has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False)) all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get( 'total_quantity') or 0 has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False)) all_ware_house_accepted_real_quantity = filtered_kill_reqs.aggregate( total_quantity=Sum('ware_house_accepted_real_quantity')).get( 'total_quantity') or 0 all_ware_house_accepted_real_weight = filtered_kill_reqs.aggregate( total_quantity=Sum('ware_house_accepted_real_weight')).get( 'total_quantity', 0) or 0 all_weight_loss = filtered_kill_reqs.aggregate( total_quantity=Sum('weight_loss')).get( 'total_quantity', 0) or 0 all_weight_loss = round(int(all_weight_loss) / len_weight_loss, 2) if len_weight_loss > 0 else 0 has_code1 = filtered_kill_reqs.filter(clearance_code__isnull=False) all_quarantine_quantity_has_code = has_code1.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity') or 0 hasnt_code = filtered_kill_reqs.filter(clearance_code__isnull=True) all_quarantine_quantity_hasnt_code = hasnt_code.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity') or 0 difference_bar = len(filtered_kill_reqs.filter( Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')))) value_header_list = [ len(filtered_kill_reqs), killer_exclusive, all_quantity, int(all_weighte), round(all_weighte / all_quantity, 1) if all_weighte > 0 and all_quantity > 0 else 0, all_age1[0] if len(all_age1) > 0 else '-', all_age1[len(all_age1) - 1] if len(all_age1) > 0 else '-', int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-', has_code, all_quarantine_quantity_has_code, has_qarantine, all_quarantine_quantity, len(hasnt_code), all_quarantine_quantity_hasnt_code, difference_bar, all_vet_state_accepted, all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), len(bar_complete), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, all_state_ware_house_confirmation, all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), f'%{all_weight_loss}' ] for item in range(len(value_header_list)): cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item]) value = value_header_list[item] # Check if the value is a number before formatting if isinstance(value, (int)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) value_header_list2 = [ len(poultry_request), total_requests_quantity, int(total_requests_weight) ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_kill_request_quantity, int(all_weighte), '', all_quarantine_quantity if all_quarantine_quantity != None else 0, '', '', all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, '', '', '', all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), f'%{all_weight_loss}', '' ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") workbook.save(output) output.seek(0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') if request.GET['role'] == 'KillHouse': name = filtered_kill_request.first()['killhouse_user__name'] response[ 'Content-Disposition'] = f'attachment; filename="مدیریت بارهای کشتارگاه {name}.xlsx"'.encode( 'utf-8') elif 'state' in request.GET: if request.GET['state'] == 'bar_pending': response[ 'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تکمیل نشده.xlsx"'.encode( 'utf-8') else: response[ 'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تکمیل شده.xlsx"'.encode( 'utf-8') else: response[ 'Content-Disposition'] = f'attachment; filename="مدیریت بارها.xlsx"'.encode( 'utf-8') response.write(output.getvalue()) return response def poultry_request_report_excel(request): date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date() filterset_class = PoultryRequestFilterSet filterset_fields = poultry_request_new_fields filtered_poultry_request = PoultryRequest.objects.filter( trash=False, send_date__date__gte=date1, send_date__date__lte=date2 ).select_related('poultry', 'poultry__user', 'hatching', 'poultry__user__city').only('freezing', 'remain_quantity', 'amount', 'key', 'poultry', 'send_date', 'hatching__date', 'create_date', 'order_code', 'poultry__unit_name', 'poultry__user__fullname', 'poultry__user__mobile', 'poultry__user__city__name', 'hatching__quantity', 'quantity', 'hatching__left_over', 'hatching__chicken_breed', 'poultry__address__province__name', 'Index_weight', 'hatching__quantity', 'union', 'direct_buying', 'free_sale_in_province', 'export').values( 'key', 'poultry', 'remain_quantity', 'send_date', 'hatching__date', 'create_date', 'order_code', 'poultry__unit_name', 'poultry__user__fullname', 'poultry__user__mobile', 'poultry__user__city__name', 'hatching__quantity', 'quantity', 'hatching__left_over', 'hatching__chicken_breed', 'poultry__address__province__name', 'Index_weight', 'amount', 'hatching__quantity', 'union', 'direct_buying', 'free_sale_in_province', 'freezing', 'export').order_by( '-send_date') user = SystemUserProfile.objects.get(key=request.GET['key']) if request.GET['role'] == 'CityOperator': city_operator = CityOperator.objects.get(trash=False, user=user) filtered_poultry_reqs = filtered_poultry_request.filter(poultry__city_operator=city_operator.unit_name) elif request.GET['role'] in ['CityJahad', 'CityPoultry']: filtered_poultry_reqs = filtered_poultry_request.filter(poultry__user__city=user.city) else: filtered_poultry_reqs = filtered_poultry_request if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=filtered_poultry_reqs ) ).filter(): ps = filterset_class(data=query, queryset=filtered_poultry_reqs) filtered_poultry_reqs = ps.filter() excel_options = [ 'ردیف', 'کد سفارش', 'نام واحد', 'نام و نام خانوادگی مرغدار', 'موبایل', 'آدرس', 'تاریخ جوجه ریزی', 'تعداد کل جوجه ریزی', 'سن مرغ', 'تعداد درخواست کشتار', 'وزن درخواست کشتار', 'میانگین وزنی', 'فروش', 'کشتار', 'قیمت مرغ زنده', 'تعداد تخصیصی به خریدار', 'مانده قابل تخصیص', 'تعداد قطعه باقی مانده در سالن', 'نژاد', 'تاریخ درخواست کشتار', 'دامپزشک فارم', 'تلفن دامپزشک فارم', 'وضعیت درخواست', 'خریدار', 'تعداد تخصیصی قطعه', 'وزن تخصیصی', 'تاریخ تخصیص', 'نوع تخصیص', 'آدرس', 'محل کشتار', 'وضعییت تخصیص به خریدار', 'تعداد بار ایجاد شده', 'تعداد قطعه تخصیصی به بار', 'وزن تخصیصی به بار', 'مانده قطعه قابل تخصیص', 'مانده وزن قابل تخصیص', 'ماشین', 'راننده', 'تلفن', 'کد بهداشتی حمل و نقل', 'کد رهگیری سامانه قرنطینه', 'تعداد ثبت شده در قرنطینه', 'تعداد قطعه بار', 'وزن بار', 'وضعیت بار', 'تعداد تخلیه', 'وزن تخلیه', 'تاریخ تخلیه کشتارگاه', 'دامپزشک کشتارگاه', 'تلفن دامپزشک کشتارگاه', 'اطلاعات تکمیلی قطعه', 'اطلاعات تکمیلی وزن', 'کاربر کشتارگاه', 'تلفن کاربرکشتارگاه', ] from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) 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_CELL header_list = [ 'تعداد درخواست های کشتار', 'مجموع قطعه درخواست های کشتار', 'مجموع وزن درخواست های کشتار', 'تعداد تخصیص به خریداران', 'تعداد قطعه تخصیصی به خریداران', 'وزن تخصیصی به خریداران', 'مانده قابل تخصیص', 'تعداد بار ایجاد شده', 'تعداد قطعه بار های ایجاد شده', 'وزن بارهای ایجاد شده', 'تعداد قطعه قابل تخصیص به بار', 'تعداد بارهای دارای کد قرنطینه', 'مجموع تعداد قطعه ثبت شده در قرنطینه', 'تعداد بارهای تخلیه شده', 'تعداد قطعه بارهای تخلیه شده', 'وزن بارهای تخلیه شده', 'تعداد بار های تکمیل شده', 'تعداد قطعه بارهای تکمیل شده', 'وزن بارهای تکمیل شده', ] # برای بالای هدر create_header(worksheet, header_list, 4, 2, 21, 16.01) if filtered_poultry_reqs.exists(): province = filtered_poultry_reqs.first()['poultry__address__province__name'] excel_description(worksheet, 'A2', f' استان {province}', color='red') excel_description(worksheet, 'A1', 'گزارش روند پرونده های کشتار مرغ گوشتی', size=11, color='red', row2='C1') excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='C3') m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 bar_list2 = 0 province_kill_requests = ProvinceKillRequest.objects.filter( province_request__poultry_request__key__in=filtered_poultry_reqs.values('key'), trash=False, return_to_province=False, state__in=('pending', 'accepted')).select_related( 'kill_request__kill_house', 'killhouse_user__kill_house_operator', 'killhouse_user__kill_house_operator__user', 'killhouse_user__kill_house_operator__address', 'killhouse_user').only('kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'state', 'key', 'create_date', 'kill_request__kill_house', 'main_quantity', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__kill_house_operator__address__city__name', 'killhouse_user__killer', 'province_request__poultry_request__Index_weight', 'quantity', 'province_request__poultry_request__union', 'province_request__poultry_request__direct_buying', ).values( 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'key', 'create_date', 'kill_request__kill_house', 'main_quantity', 'killhouse_user__name', 'killhouse_user__killer', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__kill_house_operator__address__city__name', 'province_request__poultry_request__Index_weight', 'province_request__poultry_request__union', 'province_request__poultry_request__direct_buying', 'state', 'quantity') kill_house_requestss = KillHouseRequest.objects.filter( province_kill_request__key__in=province_kill_requests.values('key'), trash=False).select_related('add_car__driver', 'killhouse_user').only( 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__kill_house_operator__user__fullname', 'killhouse_user', 'province_kill_request__province_request__poultry_request__Index_weight', 'key', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'traffic_code', 'create_date', 'clearance_code', 'killhouse_user__killer', 'accepted_real_quantity', 'accepted_real_weight', 'quantity', 'province_request__poultry_request__Index_weight', 'vet_state', 'assignment_state_archive', 'vet_accepted_real_weight', 'vet_accepted_real_quantity', 'vet_state', 'accepted_real_weight', 'accepted_assignment_real_weight', 'accepted_assignment_real_quantity').values('vet_state', 'vet_accepted_real_weight', 'vet_accepted_real_quantity', 'quarantine_quantity', 'vet_state', 'assignment_state_archive', 'province_kill_request__province_request__poultry_request__Index_weight', 'key', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'traffic_code', 'create_date', 'clearance_code', 'killhouse_user__killer', 'accepted_real_quantity', 'killhouse_user__kill_house_operator__user__fullname', 'killhouse_user', 'accepted_real_weight', 'killhouse_user__kill_house_operator__user__mobile', 'quantity', 'quarantine_quantity', 'province_request__poultry_request__Index_weight', 'accepted_real_weight', 'accepted_assignment_real_weight', 'accepted_assignment_real_quantity') poultry_ids = [req.get('poultry') for req in filtered_poultry_reqs] vet_farms = VetFarm.objects.filter(poultry__in=poultry_ids, trash=False).select_related('vet__user') vet_farm_mapping = { vet_farm.poultry_id: (vet_farm.vet.user.fullname, vet_farm.vet.user.mobile) for vet_farm in vet_farms } for filtered_poultry_req in filtered_poultry_reqs: state_p = 'در انتظار تخصیص استان' if filtered_poultry_req.get('quantity') != filtered_poultry_req.get('remain_quantity'): state_p = 'تخصیص داده شد' vet_farm_id = filtered_poultry_req.get('poultry') vet_farm_name, vet_farm_mobile = vet_farm_mapping.get(vet_farm_id, ('-', '-')) age = (filtered_poultry_req.get('send_date').date() - filtered_poultry_req.get( "hatching__date").date()).days + 1 gregorian_date = convert_to_shamsi(day=filtered_poultry_req.get("hatching__date").day, month=filtered_poultry_req.get("hatching__date").month, year=filtered_poultry_req.get("hatching__date").year ) date_of_kill = convert_to_shamsi(day=filtered_poultry_req.get('create_date').day, month=filtered_poultry_req.get('create_date').month, year=filtered_poultry_req.get('create_date').year) if filtered_poultry_req['free_sale_in_province'] == False: sale_type = 'دولتی' elif filtered_poultry_req['export']: sale_type = 'صادرات' else: sale_type = 'آزاد' province_kill_reqs = province_kill_requests.filter( province_request__poultry_request__key=filtered_poultry_req.get('key')) freez_state = 'منجمد' if filtered_poultry_req['freezing'] == True else 'عادی' list1 = [ m, str(filtered_poultry_req.get('order_code')), filtered_poultry_req.get('poultry__unit_name'), filtered_poultry_req.get('poultry__user__fullname'), filtered_poultry_req.get('poultry__user__mobile'), filtered_poultry_req.get('poultry__user__city__name'), str(gregorian_date), filtered_poultry_req.get('hatching__quantity'), str(age), filtered_poultry_req.get('quantity'), int(filtered_poultry_req.get('quantity') * filtered_poultry_req.get('Index_weight')), filtered_poultry_req.get('Index_weight'), sale_type, freez_state, filtered_poultry_req.get('amount'), filtered_poultry_req.get('quantity') - filtered_poultry_req.get('remain_quantity'), filtered_poultry_req.get('remain_quantity'), filtered_poultry_req.get('hatching__left_over'), filtered_poultry_req.get('hatching__chicken_breed'), str(date_of_kill), vet_farm_name, vet_farm_mobile, ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=20) state_s = 'در انتظار تخصیص استان' m += 1 if province_kill_reqs.exists(): quantity_kill_house_request = kill_house_requestss.filter(province_request__poultry_request__key= filtered_poultry_req['key']) if len(province_kill_reqs) > 1: if len(quantity_kill_house_request) <= 1: s = len(province_kill_reqs) - 1 merge_cells(worksheet, l, s, cell1='A', cell2='V') # TODO : جایی که باید انجام بشه if quantity_kill_house_request.exists(): if len(quantity_kill_house_request) > 1: s = len(quantity_kill_house_request) - 1 merge_cells(worksheet, l, s, cell1='A', cell2='V') for province_kill_req in province_kill_reqs: if province_kill_req['state'] == 'pending': state_s = 'درانتظار تایید' elif province_kill_req['state'] == 'accepted': state_s = ' تایید شده' elif province_kill_req['state'] == 'rejected': state_s = 'رد شده' date_of_inner_bar = '-' code = '-' time = convert_to_shamsi(day=province_kill_req.get('create_date').day, month=province_kill_req.get('create_date').month, year=province_kill_req.get('create_date').year) if province_kill_req.get('killhouse_user__killer') == False: killers = 'کشتارگاه' else: killers = 'کشتارکن' kill_house_requests = kill_house_requestss.filter( province_kill_request__key=province_kill_req['key']) all_quantity_of_bar = kill_house_requests.aggregate( total_quantity=Sum('quantity'))['total_quantity'] or 0 bar_weight = int(all_quantity_of_bar * province_kill_req[ 'province_request__poultry_request__Index_weight']) if all_quantity_of_bar > 0 else 0 remain_province = int(province_kill_req.get('quantity') * province_kill_req[ 'province_request__poultry_request__Index_weight']) if province_kill_req['province_request__poultry_request__union'] == True: type = 'فروش آزاد' elif province_kill_req[ 'province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' else: type = 'اتحادیه' slaughter_house__name = province_kill_req.get( 'kill_request__slaughter_house__name') if province_kill_req.get( 'kill_request__slaughter_house') is not None else '-' list1 = [ state_p, killers + '(' + province_kill_req.get('killhouse_user__name') + ')', province_kill_req.get('main_quantity'), int(province_kill_req.get('main_quantity') * province_kill_req.get( 'province_request__poultry_request__Index_weight')), str(time), type, province_kill_req.get('killhouse_user__kill_house_operator__address__city__name'), slaughter_house__name, state_s, len(kill_house_requests), all_quantity_of_bar, bar_weight, province_kill_req.get('quantity'), remain_province, ] create_value(worksheet, list1, l, 23, border_style='thin', m=m - 1, height=20) if kill_house_requests.exists(): if len(kill_house_requests) > 1: s = len(kill_house_requests) - 1 letters = ["W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ"] merge_cells(worksheet, l, s, lst=letters) for kill_house_request in kill_house_requests: bar_list2 += 1 kil_house_vet = KillHouseVet.objects.filter( kill_house=kill_house_request.get('killhouse_user')).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' if (kill_house_request['assignment_state_archive'] == 'True' and kill_house_request[ 'vet_state'] == 'pending') or kill_house_request[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' all_quantity_of_bar += kill_house_request['quantity'] vet_quantity = kill_house_request['vet_accepted_real_quantity'] vet_wight = kill_house_request['vet_accepted_real_weight'] kill_house_driver_name = kill_house_request.get('add_car__driver__driver_name') kill_house_driver_mobile = kill_house_request.get('add_car__driver__driver_mobile') kill_house_driver_type_car = kill_house_request.get('add_car__driver__type_car') kill_house_traffic_code = kill_house_request.get('traffic_code') vet_checks = VetCheckRequest.objects.filter( kill_house_request__key=kill_house_request.get('key')).only( 'create_date').values('create_date').first() if vet_checks: vet_check_date = vet_checks.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) assignment = KillHouseAssignmentInformation.objects.filter( kill_house_request__key=kill_house_request.get('key')).only('real_quantity', 'net_weight', 'create_date').values( 'real_quantity', 'net_weight', 'create_date').first() if assignment: vet_check_date = assignment.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) if kill_house_request.get('clearance_code'): code = kill_house_request.get('clearance_code') quarantine_quantity = kill_house_request['quarantine_quantity'] if kill_house_request[ 'quarantine_quantity'] else '-' list1 = [ kill_house_driver_type_car, kill_house_driver_name, kill_house_driver_mobile, kill_house_traffic_code, code, quarantine_quantity, kill_house_request['quantity'], int(kill_house_request['accepted_real_weight']), state, vet_quantity, vet_wight, str(date_of_inner_bar), kill_house_vet_name, kill_house_vet_mobile, kill_house_request['accepted_assignment_real_quantity'], int(kill_house_request['accepted_assignment_real_weight']), kill_house_request['killhouse_user__kill_house_operator__user__fullname'], kill_house_request['killhouse_user__kill_house_operator__user__mobile'], ] create_value(worksheet, list1, l, 37, border_style='thin', m=m - 1) l += 1 else: list1 = ['-'] * 18 create_value(worksheet, list1, l, 37, border_style='thin', m=m - 1) l += 1 else: list1 = ['-'] * 32 create_value(worksheet, list1, l, 23, border_style='thin', m=m - 1) l += 1 aggregates = filtered_poultry_reqs.aggregate( total_quantity=Sum('quantity'), total_remain_quantity=Sum('remain_quantity'), total_weight=Sum(F('quantity') * F('Index_weight')), total_hatching=Sum('hatching__quantity'), total_left_over=Sum('hatching__left_over'), ) all_poultry_request = aggregates['total_quantity'] or 0 all_remain_quantity = aggregates['total_remain_quantity'] or 0 all_wight = aggregates['total_weight'] or 0 all_hatching = aggregates['total_hatching'] or 0 all_hatching_left_over = aggregates['total_left_over'] or 0 sum_province_to_kill_house = all_poultry_request - all_remain_quantity aggregates_province_kill_req = province_kill_requests.aggregate( total_main_quantity=Sum('main_quantity'), total_weight=Sum(F('main_quantity') * F('province_request__poultry_request__Index_weight')), total_quantity=Sum('quantity') ) all_main_quantity = aggregates_province_kill_req['total_main_quantity'] or 0 all_wight_killer = aggregates_province_kill_req['total_weight'] or 0 sum_all_remain_quantity_of_bar = aggregates_province_kill_req['total_quantity'] or 0 bar_list = len(kill_house_requestss) aggregates_kill_req = kill_house_requestss.aggregate( total_quantity=Sum('quantity'), total_weight=Sum('quantity'), total_quarantine_quantity=Sum('quarantine_quantity'), total_vet_accepted_real_quantity=Sum('vet_accepted_real_quantity'), total_vet_accepted_real_weight=Sum('vet_accepted_real_weight'), ) sum_all_quantity_of_bar = aggregates_kill_req['total_quantity'] or 0 sum_all_weight_of_bar = aggregates_kill_req['total_weight'] or 0 all_qarantine = aggregates_kill_req['total_quarantine_quantity'] or 0 all_kill_house_request_has_qarantite = len(kill_house_requestss.filter(clearance_code__isnull=False)) all_vet_quantity = aggregates_kill_req['total_vet_accepted_real_quantity'] or 0 all_vet_wight = aggregates_kill_req['total_vet_accepted_real_weight'] or 0 all_assigment = kill_house_requestss.filter(assignment_state_archive='True') vet_state_accepted = len(kill_house_requestss.filter(vet_state='accepted')) all_assignment_quantity = all_assigment.aggregate( total_quantity=Sum('accepted_assignment_real_quantity'))['total_quantity'] or 0 all_assignment_weight = all_assigment.aggregate( total_quantity=Sum('accepted_assignment_real_weight'))['total_quantity'] or 0 all_reamin_province = sum_all_remain_quantity_of_bar value_header_list = [ len(filtered_poultry_reqs), all_poultry_request, all_wight, len(province_kill_requests), all_main_quantity, all_wight_killer, all_remain_quantity, bar_list, sum_all_quantity_of_bar, sum_all_weight_of_bar, sum_all_remain_quantity_of_bar, all_kill_house_request_has_qarantite, all_qarantine, vet_state_accepted, all_vet_quantity, all_vet_wight, len(all_assigment), all_assignment_quantity, all_assignment_weight, ] create_value(worksheet, value_header_list, 3, 4) list2 = [ 'مجموع==>', '', '', '', '', '', '', all_hatching, '', all_poultry_request, all_wight, '', '', '', '', sum_province_to_kill_house, all_remain_quantity, all_hatching_left_over, '', '', '', '', '', '', all_main_quantity, all_wight_killer, '', '', '', '', '', '', sum_all_quantity_of_bar, sum_all_weight_of_bar, sum_all_remain_quantity_of_bar, all_reamin_province, '', '', '', '', '', all_qarantine, sum_all_quantity_of_bar, sum_all_weight_of_bar, '', all_vet_quantity, all_vet_wight, '', '', '', all_assignment_quantity, all_assignment_weight, '', '', ] create_value(worksheet, list2, l + 3, 1, color='green') 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 transacion_out_request_excel(request): filterset_class = InternalTransactionFilterSet filterset_fields = [ 'saleReferenceId', 'refId', 'orderId', 'cardHolderPan', 'payer_fullname', 'payer_mobile', 'user__fullname', 'user__first_name', 'user__last_name', 'user__mobile', 'poultry__user__fullname', 'poultry__user__first_name', 'poultry__user__last_name', 'poultry__user__mobile', 'out_province_poultry_request_buyer__user__fullname', 'out_province_poultry_request_buyer__user__first_name', 'out_province_poultry_request_buyer__user__last_name', 'out_province_poultry_request_buyer__user__mobile', ] date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if request.GET['type'] == 'poultry': transactions = InternalTransaction.objects.filter( payer_type='poultry', date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).order_by('-date') type_transactions = 'مرغدار' else: transactions = InternalTransaction.objects.filter( payer_type='buyer', date__date__gte=date1, date__date__lte=date2, status='completed', trash=False).order_by('-date') type_transactions = 'خریدار' if 'search' in request.GET: if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=transactions ) ).filter(): ps = filterset_class(data=query, queryset=transactions) transactions = ps.filter() excel_options = [ 'ردیف', 'کد سفارش', 'پرداخت کننده', 'تلفن پرداخت کننده', 'تاریخ پرداخت', 'مبلغ کل تراکنش(ریال)', 'سهم اتحادیه(ریال)', 'سهم شرکت(ریال)', 'سهم صنف(ریال)', 'سهم دیگر(ریال)', 'شماره پیگیری', 'شماره سفارش', ] from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) 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_CELL header_list = [ 'تعداد تراکنش ها', 'مبلغ کل(ریال)', 'سهم اتحادیه(ریال)', 'سهم شرکت(ریال)', 'سهم صنف(ریال)', 'سهم دیگر(ریال)', ] # برای بالای هدر create_header(worksheet, header_list, 4, 2, 21, 16.01) excel_description(worksheet, 'A1', f'تراکنش های خارج از استان {type_transactions}', size=11, color='red', row2='C1') excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='C3') m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 new_row = 7 for transaction in transactions: if transaction.kill_house != None: fullname = transaction.kill_house.kill_house_operator.user.fullname mobile = transaction.kill_house.kill_house_operator.user.mobile elif transaction.out_province_poultry_request_buyer != None: fullname = transaction.out_province_poultry_request_buyer.user.fullname mobile = transaction.out_province_poultry_request_buyer.user.mobile elif transaction.chain_company != None: fullname = transaction.chain_company.user.fullname mobile = transaction.chain_company.user.mobile else: fullname = transaction.user.fullname mobile = transaction.user.mobile order_codes = transaction.poultry_request.filter(trash=False) if order_codes: for order in order_codes: list11 = [ m, str(order.order_code), ] create_value(worksheet, list11, new_row, 1, m=m, border_style='thin', height=25) if len(order_codes) > 1: merge_cells(worksheet, l, len(order_codes) - 1, cell1='C', cell2='L') print(l) list1 = [ fullname, mobile, str(convert_to_shamsi(datetime=transaction.date)), transaction.amount, transaction.union_share, transaction.company_share, transaction.guilds_share, transaction.other_share, str(transaction.refId), str(transaction.orderId), ] create_value(worksheet, list1, l, 3, m=m, border_style='thin', height=25) m += 1 new_row = new_row + 1 else: list1 = [ m, '-', fullname, mobile, str(convert_to_shamsi(datetime=transaction.date)), transaction.amount, transaction.union_share, transaction.company_share, transaction.guilds_share, transaction.other_share, str(transaction.refId), str(transaction.orderId), ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=20) m += 1 l += len(order_codes) all_amount = \ transactions.aggregate( total=Sum('amount'))[ 'total'] or 0 all_union_share = \ transactions.aggregate( total=Sum('union_share'))[ 'total'] or 0 all_company_share = \ transactions.aggregate( total=Sum('company_share'))[ 'total'] or 0 all_guilds_share = \ transactions.aggregate( total=Sum('guilds_share'))[ 'total'] or 0 all_other_share = \ transactions.aggregate( total=Sum('other_share'))[ 'total'] or 0 value_header_list = [ len(transactions), all_amount, all_union_share, all_company_share, all_guilds_share, all_other_share ] create_value(worksheet, value_header_list, 3, 4) list2 = [ 'مجموع==>', '', '', '', '', all_amount, all_union_share, all_company_share, all_guilds_share, all_other_share, '', '', ] create_value(worksheet, list2, l + 3, 1, color='green') workbook.save(output) output.seek(0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response[ 'Content-Disposition'] = f'attachment; filename=" تراکنش های خارج استان {type_transactions} .xlsx"'.encode( 'utf-8') response.write(output.getvalue()) return response def from_allocation_to_distribution_excel(request): date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() kill_houses = KillHouse.objects.filter(trash=False, active=True).order_by('id') province_requests = ProvinceKillRequest.objects.filter(trash=False, state__in=('pending', 'accepted'), return_to_province=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2) kill_house_requests = KillHouseRequest.objects.filter( province_kill_request__key__in=province_requests.values('key'), trash=False) kill_house_ware_houses = KillHouseWareHouse.objects.filter( date__date__gte=date1, date__date__lte=date2, trash=False) steward_allocations = StewardAllocation.objects.filter( Q(type='manual') | Q(type='auto', system_registration_code=True), ware_house__in=kill_house_ware_houses, receiver_state__in=('pending', 'accepted'), trash=False).order_by( 'id') kill_house_free_bars = KillHouseFreeSaleBarInformation.objects.filter(trash=False, date__date__gte=date1, date__date__lte=date2) from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) sheet_name = 'اطلاعات کلی' output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) worksheet = workbook.create_sheet(sheet_name) killhouse_user = kill_house_requests.values_list('killhouse_user__id', flat=True).distinct() if sheet_name == 'اطلاعات کلی': excel_options = [ 'ردیف', 'نام واحد', 'مالک', 'تلفن مالک', 'ماهیت', 'تعداد سفارشات', 'حجم سفارشات', 'وزن سفارشات', 'تعداد تخصیصات دولتی', 'حجم تخصیصات دولتی', 'وزن تخصیصات دولتی', ' میانگین وزن تخصیصات دولتی', ' تعداد تخصیصات آزاد', 'حجم تخصیصات آزاد', ' وزن تخصیصات آزاد', ' میانگین وزن تخصیصات آزاد', 'تعداد خرید مستقیم', 'حجم خرید مستقیم', 'وزن خرید مستقیم', ' میانگین وزن خرید مستقیم', 'تعداد بار ایجاد شده', 'حجم بار ایجاد شده', 'وزن بار ایجاد شده', ' میانگین وزن بار ایجاد شده', 'تعداد بار تخلیه شده', 'حجم بار تخلیه شده', 'وزن بار تخلیه شده', ' میانگین وزن بار تخلیه شده', 'تعداد بار ورودی به انبار', 'حجم تقریبی بار ورودی به انبار', 'وزن بار ورودی به انبار', ' میانگین وزن بار ورودی به انبار', 'تعداد توزیع درون استان', 'حجم تقریبی توزیع درون استان', 'وزن توزیع درون استان', ' میانگین وزن توزیع درون استان', 'تعداد توزیع خارج استان', 'حجم تقریبی توزیع خارج استان', 'وزن توزیع خارج استان', ' میانگین وزن توزیع خارج استان', 'حجم تقریبی مانده در انبار', 'وزن مانده در انبار', ' میانگین وزن مانده در انبار', ] header_list = [ 'ردیف', 'نام واحد', 'مالک', 'تلفن مالک', 'ماهیت', 'تعداد سفارشات', 'حجم سفارشات', 'وزن سفارشات', 'میانگین وزن سفارشات', 'تعداد بار ایجاد شده', 'حجم بار ایجاد شده', 'وزن بار ایجاد شده', 'تعداد بار ورودی به انبار', 'حجم تقریبی بار ورودی به انبار', 'وزن بار ورودی به انبار', 'تعداد توزیع درون استان', 'حجم تقریبی توزیع درون استان', 'وزن توزیع درون استان', 'تعداد توزیع خارج استان', 'حجم تقریبی توزیع خارج استان', 'وزن توزیع خارج استان', 'حجم تقریبی مانده در انبار', 'وزن مانده در انبار', ] worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') create_header(worksheet, header_list, 4, 2, 21, 16.01, color='blue') province = kill_houses.first().kill_house_operator.user.province.name excel_description(worksheet, 'A1', f' گزارش عملکرد خریداران استان {province}', size=11, color='red', row2='C1') excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='C3') m = 1 header_row = 3 l = 3 excel_description(worksheet, 'I1', 'اطلاعات کلی کشتار', color='red', row2='K1') all_len_province_kill_request = 0 all_quantity_province_kill_request = 0 all_weight_province_kill_request = 0 for kill_house in kill_houses: cell_color_changer(worksheet, l, 5, 8, 'FBFEE2') percentage = KillHousePercentage.objects.filter(kill_house=kill_house).select_related( 'kill_house_for_killer', 'kill_house').first() if percentage: if percentage.kill_house_for_killer != None: place = percentage.kill_house_for_killer.name else: place = percentage.kill_house.name else: place = kill_house.name killer_type = 'کشتارگاه' if kill_house.killer == True: type = 'کشتارکن' if kill_house.type == 'public': killer_type = f'{type} عمومی ' else: killer_type = f' {type} اختصاصی ({place})' # all province_kill_request = province_requests.filter(killhouse_user=kill_house) # goveerment province_kill_request_goverment = province_kill_request.filter( province_request__poultry_request__free_sale_in_province=False) quantity_province_kill_request_goverment = \ province_kill_request_goverment.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_goverment = \ province_kill_request_goverment.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 # cell_color_changer(worksheet, l, 9, 13, 'EBF1DE') # free province_kill_request_free = province_kill_request.filter( province_request__poultry_request__free_sale_in_province=True) quantity_province_kill_request_free = \ province_kill_request_free.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_free = \ province_kill_request_free.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 # cell_color_changer(worksheet, l, 13, 17, 'DDD9C4') # direct_buying province_kill_request_direct_buying = province_kill_request.filter( province_request__poultry_request__direct_buying=True) quantity_province_kill_request_direct_buying = \ province_kill_request_direct_buying.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_direct_buying = \ province_kill_request_direct_buying.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 # cell_color_changer(worksheet, l, 17, 21, 'C5D9F1') # all len_province_kill_request = len(province_kill_request_goverment) + \ len(province_kill_request_free) + len(province_kill_request_direct_buying) quantity_province_kill_request = quantity_province_kill_request_goverment + quantity_province_kill_request_free + \ quantity_province_kill_request_direct_buying weight_province_kill_request = weight_province_kill_request_goverment + weight_province_kill_request_free + \ weight_province_kill_request_direct_buying # cell_color_changer(worksheet, l, 6, 9, 'C5D9F1') # all_len_province_kill_request += len_province_kill_request # all_quantity_province_kill_request += quantity_province_kill_request # all_weight_province_kill_request += weight_province_kill_request # bar kill_house_request = kill_house_requests.filter(Q(Q(killer=kill_house) & Q(killhouse_user=kill_house)) | Q( Q(killer__isnull=True) & Q(killhouse_user=kill_house)) | Q( Q(killer__isnull=True) | Q(killer=kill_house))) kill_house_request = kill_house_request.filter(Q(killer=kill_house) | Q(killhouse_user=kill_house)) quantity_kill_house_request = \ kill_house_request.aggregate( total=Sum('quantity'))[ 'total'] or 0 weight_kill_house_request = \ kill_house_request.aggregate( total=Sum(F('quantity') * F('province_request__poultry_request__Index_weight')))[ 'total'] or 0 cell_color_changer(worksheet, l, 13, 16, 'D8E4BC') # ware_house_confirmation ware_house_confirmation = kill_house_request.filter(ware_house_confirmation=True) quantity_kill_house_request_ware_house = \ ware_house_confirmation.aggregate( total=Sum('ware_house_accepted_real_quantity'))[ 'total'] or 0 weight_kill_house_request_ware_house = \ ware_house_confirmation.aggregate( total=Sum('ware_house_accepted_real_weight'))[ 'total'] or 0 cell_color_changer(worksheet, l, 16, 19, 'E6B8B7') # in_province kill_house_ware_house = kill_house_ware_houses.filter(kill_house=kill_house) steward_allocation = steward_allocations.filter(ware_house__in=kill_house_ware_house) total_allocated_quantity = \ steward_allocation.aggregate(total=Sum('real_number_of_carcasses'))[ 'total'] or 0 total_allocated_weight = \ steward_allocation.aggregate(total=Sum('real_weight_of_carcasses'))[ 'total'] or 0 # cell_color_changer(worksheet, l, 19, 22, 'EBF1DE') # out_province kill_house_free_bar = kill_house_free_bars.filter(kill_house=kill_house) total_quantity = kill_house_free_bar.aggregate(total=Sum('number_of_carcasses'))[ 'total'] or 0 total_weight = kill_house_free_bar.aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 cell_color_changer(worksheet, l, 22, 25, '95B3D7') # remain_ total_remain_quantity = \ kill_house_ware_house.aggregate(total=Sum('remain_total_number_of_carcasses'))[ 'total'] or 0 total_remain_weight = \ kill_house_ware_house.aggregate(total=Sum('remain_total_weight_of_carcasses'))[ 'total'] or 0 cell_color_changer(worksheet, l, 25, 27, 'DA9694') value_header_list = [ m, kill_house.name, kill_house.kill_house_operator.user.fullname, kill_house.kill_house_operator.user.mobile, killer_type, len_province_kill_request, quantity_province_kill_request, weight_province_kill_request, str(round(weight_province_kill_request / quantity_province_kill_request, 1) if weight_province_kill_request > 0 else 0), len(kill_house_request), quantity_kill_house_request, weight_kill_house_request, len(ware_house_confirmation), quantity_kill_house_request_ware_house, weight_kill_house_request_ware_house, len(steward_allocation), total_allocated_quantity, total_allocated_weight, len(kill_house_free_bar), total_quantity, total_weight, total_remain_quantity, total_remain_weight, ] create_value(worksheet, value_header_list, l, 4, border_style='thin') l += 1 header_row += 1 m += 1 l += 3 create_header_freez(worksheet, excel_options, 1, l, l + 1, 20) m = 1 excel_description(worksheet, f'I{l - 1}', 'جزئیات کشتار', color='red', row2=f'K{l - 1}') for kill_house in kill_houses: percentage = KillHousePercentage.objects.filter(kill_house=kill_house).select_related( 'kill_house_for_killer', 'kill_house').first() if percentage: if percentage.kill_house_for_killer != None: place = percentage.kill_house_for_killer.name else: place = percentage.kill_house.name else: place = kill_house.name killer_type = 'کشتارگاه' if kill_house.killer == True: type = 'کشتارکن' if kill_house.type == 'public': killer_type = f'{type} عمومی ' else: killer_type = f' {type} اختصاصی ({place})' # all province_kill_request = province_requests.filter(killhouse_user=kill_house) # goveerment province_kill_request_goverment = province_kill_request.filter( province_request__poultry_request__free_sale_in_province=False) quantity_province_kill_request_goverment = \ province_kill_request_goverment.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_goverment = \ province_kill_request_goverment.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 9, 13, 'EBF1DE') # free province_kill_request_free = province_kill_request.filter( province_request__poultry_request__free_sale_in_province=True) quantity_province_kill_request_free = \ province_kill_request_free.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_free = \ province_kill_request_free.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 13, 17, 'DDD9C4') # direct_buying province_kill_request_direct_buying = province_kill_request.filter( province_request__poultry_request__direct_buying=True) quantity_province_kill_request_direct_buying = \ province_kill_request_direct_buying.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_direct_buying = \ province_kill_request_direct_buying.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 17, 21, 'C5D9F1') # all len_province_kill_request = len(province_kill_request_goverment) + \ len(province_kill_request_free) + len(province_kill_request_direct_buying) quantity_province_kill_request = quantity_province_kill_request_goverment + quantity_province_kill_request_free + \ quantity_province_kill_request_direct_buying weight_province_kill_request = weight_province_kill_request_goverment + weight_province_kill_request_free + \ weight_province_kill_request_direct_buying cell_color_changer(worksheet, l + 1, 6, 9, 'C5D9F1') all_len_province_kill_request += len_province_kill_request all_quantity_province_kill_request += quantity_province_kill_request all_weight_province_kill_request += weight_province_kill_request # bar kill_house_request = kill_house_requests.filter(Q(Q(killer=kill_house) & Q(killhouse_user=kill_house)) | Q( Q(killer__isnull=True) & Q(killhouse_user=kill_house)) | Q( Q(killer__isnull=True) | Q(killer=kill_house))) kill_house_request = kill_house_request.filter(Q(killer=kill_house) | Q(killhouse_user=kill_house)) quantity_kill_house_request = \ kill_house_request.aggregate( total=Sum('quantity'))[ 'total'] or 0 weight_kill_house_request = \ kill_house_request.aggregate( total=Sum(F('quantity') * F('province_request__poultry_request__Index_weight')))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 21, 25, 'EBF1DE') # assignment_state_archive assignment_state_archive = kill_house_request.filter(assignment_state_archive='True') quantity_kill_house_request_assignment = \ assignment_state_archive.aggregate( total=Sum('accepted_real_quantity'))[ 'total'] or 0 weight_kill_house_request_assignment = \ assignment_state_archive.aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 25, 29, 'DDD9C4') # ware_house_confirmation ware_house_confirmation = kill_house_request.filter(ware_house_confirmation=True) quantity_kill_house_request_ware_house = \ ware_house_confirmation.aggregate( total=Sum('ware_house_accepted_real_quantity'))[ 'total'] or 0 weight_kill_house_request_ware_house = \ ware_house_confirmation.aggregate( total=Sum('ware_house_accepted_real_weight'))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 29, 33, 'C5D9F1') # in_province kill_house_ware_house = kill_house_ware_houses.filter(kill_house=kill_house) steward_allocation = steward_allocations.filter(ware_house__in=kill_house_ware_house) total_allocated_quantity = \ steward_allocation.aggregate(total=Sum('real_number_of_carcasses'))[ 'total'] or 0 total_allocated_weight = \ steward_allocation.aggregate(total=Sum('real_weight_of_carcasses'))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 33, 37, 'EBF1DE') # out_province kill_house_free_bar = kill_house_free_bars.filter(kill_house=kill_house) total_quantity = kill_house_free_bar.aggregate(total=Sum('number_of_carcasses'))[ 'total'] or 0 total_weight = kill_house_free_bar.aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 37, 41, 'DDD9C4') # remain_ total_remain_quantity = \ kill_house_ware_house.aggregate(total=Sum('remain_total_number_of_carcasses'))[ 'total'] or 0 total_remain_weight = \ kill_house_ware_house.aggregate(total=Sum('remain_total_weight_of_carcasses'))[ 'total'] or 0 cell_color_changer(worksheet, l + 1, 41, 44, 'C5D9F1') list1 = [ m, kill_house.name, kill_house.kill_house_operator.user.fullname, kill_house.kill_house_operator.user.mobile, killer_type, len_province_kill_request, quantity_province_kill_request, weight_province_kill_request, len(province_kill_request_goverment), quantity_province_kill_request_goverment, weight_province_kill_request_goverment, str(round(weight_province_kill_request_goverment / quantity_province_kill_request_goverment, 1) if weight_province_kill_request_goverment > 0 else 0), len(province_kill_request_free), quantity_province_kill_request_free, weight_province_kill_request_free, str(round(weight_province_kill_request_free / quantity_province_kill_request_free, 1) if weight_province_kill_request_free > 0 else 0), len(province_kill_request_direct_buying), quantity_province_kill_request_direct_buying, weight_province_kill_request_direct_buying, str(round(weight_province_kill_request_direct_buying / quantity_province_kill_request_direct_buying, 1) if weight_province_kill_request_direct_buying > 0 else 0), len(kill_house_request), quantity_kill_house_request, weight_kill_house_request, str(round(weight_kill_house_request / quantity_kill_house_request, 1) if weight_kill_house_request > 0 else 0), len(assignment_state_archive), quantity_kill_house_request_assignment, weight_kill_house_request_assignment, str(round(weight_kill_house_request_assignment / quantity_kill_house_request_assignment, 1) if weight_kill_house_request_assignment > 0 else 0), len(ware_house_confirmation), quantity_kill_house_request_ware_house, weight_kill_house_request_ware_house, str(round(weight_kill_house_request_ware_house / quantity_kill_house_request_ware_house, 1) if weight_kill_house_request_ware_house > 0 else 0), len(steward_allocation), total_allocated_quantity, total_allocated_weight, str(round(total_allocated_weight / total_allocated_quantity, 1) if total_allocated_weight > 0 else 0), len(kill_house_free_bar), total_quantity, total_weight, str(round(int(total_weight) / total_quantity, 1) if total_weight > 0 and total_quantity > 0 else 0), total_remain_quantity, total_remain_weight, str(round(total_remain_weight / total_remain_quantity, 1) if total_remain_weight > 0 else 0), ] create_value(worksheet, list1, l + 1, 1, border_style='thin', height=25) m += 1 l += 1 province_kill_request_goverment1 = province_requests.filter( province_request__poultry_request__free_sale_in_province=False) quantity_province_kill_request_goverment = \ province_kill_request_goverment1.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_goverment = \ province_kill_request_goverment1.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 province_kill_request_free = province_requests.filter( province_request__poultry_request__free_sale_in_province=True) quantity_province_kill_request_free = \ province_kill_request_free.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_free = \ province_kill_request_free.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 province_kill_request_direct_buying = province_requests.filter( province_request__poultry_request__direct_buying=True) quantity_province_kill_request_direct_buying = \ province_kill_request_direct_buying.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 weight_province_kill_request_direct_buying = \ province_kill_request_direct_buying.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 quantity_kill_house_request = \ kill_house_requests.aggregate( total=Sum('quantity'))[ 'total'] or 0 weight_kill_house_request = \ kill_house_requests.aggregate( total=Sum(F('quantity') * F('province_request__poultry_request__Index_weight')))[ 'total'] or 0 # assignment_state_archive assignment_state_archive = kill_house_requests.filter(assignment_state_archive='True') quantity_kill_house_request_assignment = \ assignment_state_archive.aggregate( total=Sum('accepted_real_quantity'))[ 'total'] or 0 weight_kill_house_request_assignment = \ assignment_state_archive.aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 ware_house_confirmation = kill_house_requests.filter(ware_house_confirmation=True) quantity_kill_house_request_ware_house = \ ware_house_confirmation.aggregate( total=Sum('ware_house_accepted_real_quantity'))[ 'total'] or 0 weight_kill_house_request_ware_house = \ ware_house_confirmation.aggregate( total=Sum('ware_house_accepted_real_weight'))[ 'total'] or 0 total_allocated_quantity = \ steward_allocations.aggregate(total=Sum('real_number_of_carcasses'))[ 'total'] or 0 total_allocated_weight = \ steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[ 'total'] or 0 total_quantity = kill_house_free_bars.aggregate(total=Sum('number_of_carcasses'))[ 'total'] or 0 total_weight = kill_house_free_bars.aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 total_remain_quantity = \ kill_house_ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))[ 'total'] or 0 total_remain_weight = \ kill_house_ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))[ 'total'] or 0 list2 = [ 'مجموع==>', '', '', '', '', all_len_province_kill_request, all_quantity_province_kill_request, all_weight_province_kill_request, len(province_kill_request_goverment1), quantity_province_kill_request_goverment, weight_province_kill_request_goverment, str(round(weight_province_kill_request_goverment / quantity_province_kill_request_goverment, 1) if weight_province_kill_request_goverment > 0 else 0), len(province_kill_request_free), quantity_province_kill_request_free, weight_province_kill_request_free, str(round(weight_province_kill_request_free / quantity_province_kill_request_free, 1) if weight_province_kill_request_free > 0 else 0), len(province_kill_request_direct_buying), quantity_province_kill_request_direct_buying, weight_province_kill_request_direct_buying, str(round(weight_province_kill_request_direct_buying / quantity_province_kill_request_direct_buying, 1) if weight_province_kill_request_direct_buying > 0 else 0), len(kill_house_requests), quantity_kill_house_request, weight_kill_house_request, str(round(weight_kill_house_request / quantity_kill_house_request, 1) if weight_kill_house_request > 0 else 0), len(assignment_state_archive), quantity_kill_house_request_assignment, weight_kill_house_request_assignment, str(round(weight_kill_house_request_assignment / quantity_kill_house_request_assignment, 1) if weight_kill_house_request_assignment > 0 else 0), len(ware_house_confirmation), quantity_kill_house_request_ware_house, weight_kill_house_request_ware_house, str(round(weight_kill_house_request_ware_house / quantity_kill_house_request_ware_house, 1) if weight_kill_house_request_ware_house > 0 else 0), len(steward_allocations), total_allocated_quantity, total_allocated_weight, str(round(total_allocated_weight / total_allocated_quantity, 1) if total_allocated_weight > 0 else 0), len(kill_house_free_bars), total_quantity, total_weight, str(round(total_weight / total_quantity, 1) if total_weight > 0 else 0), total_remain_quantity, total_remain_weight, str(round(total_remain_weight / total_remain_quantity, 1) if total_remain_weight > 0 else 0), ] create_value(worksheet, list2, l + 1, 1, color='green') list2 = [ 'مجموع==>', '', '', '', '', all_len_province_kill_request, all_quantity_province_kill_request, all_weight_province_kill_request, str(round(all_weight_province_kill_request / all_quantity_province_kill_request, 1) if all_weight_province_kill_request > 0 else 0), len(kill_house_requests), quantity_kill_house_request, weight_kill_house_request, len(ware_house_confirmation), quantity_kill_house_request_ware_house, weight_kill_house_request_ware_house, len(steward_allocations), total_allocated_quantity, total_allocated_weight, len(kill_house_free_bars), total_quantity, total_weight, total_remain_quantity, total_remain_weight, ] create_value(worksheet, list2, header_row - 1, 4, color='blue') for kill_house_id in killhouse_user: kill_house = KillHouse.objects.get(trash=False, id=kill_house_id) sheet_name = kill_house.name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') filtered_kill_reqs = kill_house_requests.filter( killhouse_user=kill_house).order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'province_kill_request__province_request__poultry_request__out', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'bar_document_status__title').values( 'province_request__poultry_request__poultry__user__fullname', 'province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_confirmation', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'province_kill_request__province_request__poultry_request__out', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'bar_document_status__title' ) poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values( 'province_request__poultry_request')) .only('quantity', 'Index_weight')).annotate( total_quantity=Sum('quantity'), total_weight=Sum(F('quantity') * F('Index_weight')) ) excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'نوع کشتار', 'کدسفارش مرغدار', 'نام و نام خانوادگی مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'نام فارم', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', 'کشتارکن اختصاصی', 'تلفن کشتارکن اختصاصی', ' محل کشتار ', 'قیمت کشتارگاه(ریال)', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'وضعیت', 'وضعیت سند', 'وضعیت ورود انبار', 'تعداد لاشه', 'وزن لاشه', 'درصد افت', 'کشور مقصد', ] from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) header_list = [ 'تعداد بارهای ایجاد شده', 'تعداد بارهای دارای کشتارکن اختصاصی', 'مجموع حجم بارها', 'مجموع وزن بارها', 'میانگین وزن ', 'کمترین سن', 'بیشترین سن', 'میانگین سنی', 'تعداد بارهای دارای کد قرنطینه', 'حجم بارهای دارای کد قرنطینه', 'تعداد بار احراز شده از قرنطینه', 'مجموع تعداد قطعه احراز شده از قرنطینه', 'تعداد بار فاقد قرنطینه', 'حجم بار فاقد قرنطینه', ' تعداد بارهایی که در قرنطینه و رصدیار اختلاف دارند', 'تعداد تخلیه شده دامپزشک', 'مجموع تعداد تخلیه شده دامپزشک', 'مجموع وزن تخلیه شده دامپزشک', 'تعداد بارهای تکمیل شده', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'تعداد بار های وارد شده در انبار', 'مجموع تعداد لاشه', 'مجموع وزن لاشه', 'میانگین درصد افت لاشه', ] header_list2 = [ 'تعداد درخواست مرغداران', ' مجموع تعداد قطعه درخواست مرغداران', ' مجموع وزن درخواست مرغداران', ] header_list3 = [ 'درصد بارهای دارای کد قرنطینه', 'درصد تعداد بارهای احراز شده از قرنطینه', 'درصد تعداد بارهای تکمیل شده کشتارگاه', 'درصد وزن نهایی در کشتارگاه نسبت به وزن کل', 'درصد بارهای فاقد کد قرنطینه', 'درصد بارهای اختلاف دار در قرنطینه و رصدیار', 'درصد تعداد بارهای ورودی به انبار', 'درصد وزن لاشه ها در انبار نسبت به وزن کل', 'درصد وزن لاشه در انبار نسبت به وزن نهایی در کشتارگاه', ] create_header(worksheet, header_list, 9, 2, height=21.8) create_header(worksheet, header_list2, 6, 2, height=21.8, color='green') create_header(worksheet, header_list3, 6, 5, height=43, color='orange', text_color='0D0D0D') create_header_freez(worksheet, excel_options, 1, 8, 9, height=21, len_with=True) excel_description(worksheet, 'B1', f'گزارش بارهای ایجاد شده کشتارگاه {kill_house.name} در فرآیند کشتار مرغ گوشتی', color='red', row2='E1') kill_keys = [kill.get('key') for kill in filtered_kill_reqs] vet_checks = VetCheckRequest.objects.filter( trash=False, kill_house_request__key__in=kill_keys ).only('create_date', 'kill_house_request__key').values( 'create_date', 'kill_house_request__key') assignments = KillHouseAssignmentInformation.objects.filter( kill_house_request__key__in=kill_keys, trash=False ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key') vet_check_mapping = {vc['kill_house_request__key']: vc['create_date'] for vc in vet_checks} assignment_mapping = { assignment.kill_house_request.key: ( int(assignment.net_weight), assignment.real_quantity, assignment.create_date) for assignment in assignments } if filtered_kill_reqs.exists(): name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name'] worksheet['B2'] = f'استان {name}' excel_description(worksheet, 'B2', f'استان {name}', color='red', row2='D2') excel_description(worksheet, 'B3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='D3') l = 8 m = 1 all_age = [] all_real_quantity = 0 all_net_weighte = 0 all_weighte = 0 poultry_ids = [req.get('province_request__poultry_request__poultry') for req in filtered_kill_reqs] vet_farms = VetFarm.objects.filter(poultry__in=poultry_ids, trash=False).select_related('vet__user') vet_farm_mapping = { vet_farm.poultry_id: (vet_farm.vet.user.fullname, vet_farm.vet.user.mobile) for vet_farm in vet_farms } if filtered_kill_reqs: for kill in filtered_kill_reqs: age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if age not in all_age: all_age.append(age) if (kill['assignment_state_archive']) == 'True' or kill[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' l += 1 vet_farm_id = kill.get('province_request__poultry_request__poultry') vet_farm_name, vet_farm_mobile = vet_farm_mapping.get(vet_farm_id, ('-', '-')) kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'), trash=False).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() code = kill.get('clearance_code') if kill.get('clearance_code') else '-' if kill.get('quantity'): quantity = kill.get('quantity') else: quantity = '-' send_date = kill.get('province_request__poultry_request__send_date') date_of_poultry_request = convert_to_shamsi(year=send_date.year, month=send_date.month, day=send_date.day, ) killers = 'کشتارکن' name_killer_exclusive = '-' mobile_killer_exclusive = '-' if kill.get('killhouse_user__killer') == False: killers = 'کشتارگاه' if kill.get('killer') != None: name_killer_exclusive = kill['killer__name'] mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile']) key = kill.get('key') kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' net_weighte, real_quantity, vet_check_date = assignment_mapping.get(key, ('-', '-', None)) all_real_quantity += real_quantity if real_quantity != '-' else 0 all_net_weighte += net_weighte if net_weighte != '-' else 0 vet_check_date = vet_check_mapping.get(key, vet_check_date) date_of_inner_bar = convert_to_shamsi(datetime=vet_check_date) if vet_check_date else '-' if kill.get('kill_request__slaughter_house') is not None: kill_place = kill.get('kill_request__slaughter_house__name') else: kill_place = '-' vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-' vet_wight = int(kill['vet_accepted_real_weight']) if kill['vet_accepted_real_weight'] else '-' weight = int(kill.get('quantity') * kill.get( 'province_kill_request__province_request__poultry_request__Index_weight')) quarantine_quantity = '-' if kill['quarantine_quantity'] != None: quarantine_quantity = kill['quarantine_quantity'] else: if kill['quarantine_code_state'] == 'contradiction': quarantine_quantity = 'مغایرت کد رهگیری' elif kill['quarantine_code_state'] == 'noclearance': quarantine_quantity = 'فاقد کد رهگیری' elif kill['quarantine_code_state'] == 'notconfirmed': quarantine_quantity = 'عدم تایید راهداری' elif kill['quarantine_code_state'] == 'merge': quarantine_quantity = 'ادغام' export_country = '-' sale_type = 'دولتی' if kill[ 'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد' if kill['province_kill_request__province_request__poultry_request__out'] == True: type = 'خارج از استان' elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' elif kill['province_request__poultry_request__freezing'] == True: type = 'انجماد' elif kill['province_request__poultry_request__export'] == True: type = 'صادرات' export_country = kill['kill_request__export_country'] else: type = 'عادی' age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if kill['message'] is not None: state_delete = 'بار حذف شده' else: state_delete = 'فعال' all_weighte += weight ware_house_accepted_real_quantity = kill['ware_house_accepted_real_quantity'] ware_house_accepted_real_weight = kill['ware_house_accepted_real_weight'] weight_loss = round(kill['weight_loss'], 2) if kill['weight_loss'] > 0 else 0 if kill['ware_house_confirmation'] == True: state_ware_house_confirmation = 'ورود به انبار' else: state_ware_house_confirmation = '-' list1 = [ m, str(kill.get('bar_code')), str(date_of_poultry_request), type, str(kill.get('province_request__poultry_request__order_code')), kill.get('province_request__poultry_request__poultry__user__fullname'), str(kill.get('province_request__poultry_request__poultry__user__mobile')), kill.get('province_request__poultry_request__poultry__user__city__name'), kill.get('province_request__poultry_request__poultry__unit_name'), sale_type, age, kill.get('province_request__poultry_request__amount') if kill.get( 'province_request__poultry_request__amount') else '-', kill.get('province_request__poultry_request__chicken_breed'), vet_farm_name, vet_farm_mobile, killers, kill.get('killhouse_user__name'), kill.get('killhouse_user__kill_house_operator__user__mobile'), kill.get('killhouse_user__system_address__city__name'), name_killer_exclusive, mobile_killer_exclusive, kill_place, kill.get('province_kill_request__kill_house_price'), kill_house_vet_name, kill_house_vet_mobile, kill.get('add_car__driver__driver_name'), kill.get('add_car__driver__driver_mobile'), kill.get('add_car__driver__type_car'), str(kill.get('traffic_code')), quantity, weight, code, quarantine_quantity, state, str(date_of_inner_bar), vet_quantity, vet_wight, real_quantity, net_weighte, kill['accepted_real_quantity'], int(kill['accepted_real_weight']), state_delete, kill['bar_document_status__title'] if kill['bar_document_status'] else '-', state_ware_house_confirmation, ware_house_accepted_real_quantity, int(ware_house_accepted_real_weight), f'%{weight_loss}', export_country, ] m += 1 create_value(worksheet, list1, l, 1, height=20, different_cell=40, different_value='بار حذف شده') killer_exclusive = len(filtered_kill_reqs.filter(killer__isnull=False)) all_state_ware_house_confirmation = len(filtered_kill_reqs.filter(ware_house_confirmation=True)) total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] or 0 total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0 aggregate_filtered_kill_reqs = filtered_kill_reqs.aggregate( total_accepted_real_quantity=Sum('accepted_real_quantity'), total_accepted_real_weight=Sum('accepted_real_weight'), total_quantity=Sum('quantity'), total_vet_accepted_real_quantity=Sum('vet_accepted_real_quantity'), total_vet_accepted_real_weight=Sum('vet_accepted_real_weight'), total_quarantine_quantity=Sum('quarantine_quantity'), total_ware_house_accepted_real_quantity=Sum('ware_house_accepted_real_quantity'), total_ware_house_accepted_real_weight=Sum('ware_house_accepted_real_weight'), total_weight_loss=Sum('weight_loss'), ) all_vet_state_accepted = len( filtered_kill_reqs.filter(vet_state='accepted')) bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True') accepted_real_quantity = aggregate_filtered_kill_reqs['total_accepted_real_quantity'] or 0 accepted_real_wight = aggregate_filtered_kill_reqs['total_accepted_real_weight'] or 0 all_kill_request_quantity = aggregate_filtered_kill_reqs['total_quantity'] or 0 all_quarantine_quantity = aggregate_filtered_kill_reqs['total_quarantine_quantity'] or 0 all_vet_accepted_real_quantity = aggregate_filtered_kill_reqs['total_vet_accepted_real_quantity'] or 0 all_vet_accepted_real_weight = aggregate_filtered_kill_reqs['total_vet_accepted_real_weight'] or 0 has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False)) all_ware_house_accepted_real_quantity = aggregate_filtered_kill_reqs[ 'total_ware_house_accepted_real_quantity'] or 0 all_ware_house_accepted_real_weight = aggregate_filtered_kill_reqs['total_ware_house_accepted_real_weight'] or 0 all_weight_loss = aggregate_filtered_kill_reqs['total_weight_loss'] or 0 has_code1 = filtered_kill_reqs.filter(clearance_code__isnull=False).aggregate( total_quantity=Sum('quantity'), ) all_quarantine_quantity_has_code = has_code1['total_quantity'] or 0 hasnt_code1 = filtered_kill_reqs.filter(clearance_code__isnull=True) hasnt_code = hasnt_code1.aggregate( total_quantity=Sum('quantity') ) all_quarantine_quantity_hasnt_code = hasnt_code['total_quantity'] or 0 difference_bar = len(filtered_kill_reqs.filter( Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')))) all_weight_loss = round(int(all_weight_loss) / all_state_ware_house_confirmation, 2) if all_weight_loss > 0 else 0 all_age1 = sorted(all_age) has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False)) value_header_list = [ len(poultry_request), total_requests_quantity, int(total_requests_weight), len(filtered_kill_reqs), killer_exclusive, all_kill_request_quantity, int(all_weighte), round(all_weighte / all_kill_request_quantity, 1) if all_weighte > 0 and all_kill_request_quantity > 0 else 0, all_age1[0] if len(all_age1) > 0 else '-', all_age1[len(all_age1) - 1] if len(all_age1) > 0 else '-', int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-', has_code, all_quarantine_quantity_has_code, has_qarantine, all_quarantine_quantity, len(hasnt_code1), all_quarantine_quantity_hasnt_code, difference_bar, all_vet_state_accepted, all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), len(bar_complete), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, all_state_ware_house_confirmation, all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), f'%{all_weight_loss}' ] create_value(worksheet, value_header_list, 3, 6) value_header_list2 = [ f'%{round((has_code * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((has_qarantine * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((len(bar_complete) * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((int(all_net_weighte) * 100) / int(all_weighte), 2) if int(all_weighte) > 0 else 0}', f'%{round((len(hasnt_code1) * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((difference_bar * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((all_state_ware_house_confirmation * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((int(all_ware_house_accepted_real_weight) * 100) / int(all_weighte), 2) if int(all_weighte) > 0 else 0}', f'%{round((int(all_ware_house_accepted_real_weight) * 100) / int(all_net_weighte), 2) if int(all_net_weighte) > 0 else 0}' ] create_value(worksheet, value_header_list2, 6, 6) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_kill_request_quantity, int(all_weighte), '', all_quarantine_quantity if all_quarantine_quantity != None else 0, '', '', all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, '', '', '', all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), f'%{all_weight_loss}', '' ] create_value(worksheet, list2, l + 3, 1, color='green') 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 all_distribution_province(request): sheet_names2 = [ 'اطلاعات کلی', 'تخصیصات کشتارگاه به مباشر و صنف', 'تخصیصات مباشر به صنف', # 'تخصیصات مباشر به مباشر', 'تخصیصات صنف به صنف', 'تخصیصات سرد خانه', 'عملکرد مباشرین', 'تراکنش های صنوف', ] output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) for name in sheet_names2: sheet_name = name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) if sheet_name == 'اطلاعات کلی': if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) excel_description(worksheet, 'B2', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='E2') excel_description(worksheet, 'B1', f'اطلاعات کلی', row2='E1') header_list2 = [ 'ماهیت', 'اطلاعات فروشنده', 'مانده در انبار قبل از توزیع', 'وزن ورودی به انبار فروشنده ', 'تعداد کل توزیع شده', ' وزن کل خروجی از انبار (توزیع شده)', 'کل وزن فروش به خارج از استان', 'تعداد توزیع به مباشرین', 'وزن توزیع به مباشرین', 'تعداد توزیع به صنف', 'وزن توزیع به صنف', 'درصد توزیع فروشنده', 'مانده انبار', ] create_header(worksheet, header_list2, 3, 4, border_style='thin', width=20) kill_houses = KillHouse.objects.filter(trash=False, out_province=False) l = 5 for kill_house in kill_houses: if kill_house.killer == True and kill_house.type == 'exclusive': parent = KillHousePercentage.objects.get(kill_house=kill_house, trash=False) killer_type = f'کشتارکن اختصاصی {parent.kill_house_for_killer.name}' elif kill_house.killer == True and kill_house.type == 'public': killer_type = 'کشتارکن عمومی' else: killer_type = 'کشتارگاه' if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() kill_house_request = KillHouseRequest.objects.filter( Q(killhouse_user=kill_house) | Q(killer=kill_house), ware_house_confirmation=True, trash=False, calculate_status=True , kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2) kill_house_free_buying_bars = KillHouseFreeBarInformation.objects.filter( kill_house=kill_house, trash=False, calculate_status=True, date__date__gte=date1, date__date__lte=date2, ware_house=True) allocations = StewardAllocation.objects.filter( receiver_state__in=('pending', 'accepted'), trash=False, date__date__gte=date1, date__date__lte=date2, kill_house=kill_house).order_by('id') kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter( kill_house=kill_house, trash=False, calculate_status=True, date__date__gte=date1, date__date__lte=date2, ) else: kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter( kill_house=kill_house, trash=False, calculate_status=True) kill_house_free_buying_bars = KillHouseFreeBarInformation.objects.filter( kill_house=kill_house, trash=False, calculate_status=True, ware_house=True) kill_house_request = KillHouseRequest.objects.filter( Q(killhouse_user=kill_house) | Q(killer=kill_house), ware_house_confirmation=True, trash=False, calculate_status=True ) allocations = StewardAllocation.objects.filter( trash=False, kill_house=kill_house, receiver_state__in=('pending', 'accepted')).order_by('id') kill_house_to_stw = allocations.filter(allocation_type='killhouse_steward') quantity_allocations = allocations.aggregate( total_quantity=Sum('real_number_of_carcasses')).get( 'total_quantity') or 0 quantity_kill_house_free_sale_bars = kill_house_free_sale_bars.aggregate( total_quantity=Sum('real_number_of_carcasses')).get( 'total_quantity') or 0 weight_allocations = allocations.aggregate( total_quantity=Sum('real_weight_of_carcasses')).get( 'total_quantity') or 0 weight_kill_house_free_sale_bars = kill_house_free_sale_bars.aggregate( total_quantity=Sum('real_weight_of_carcasses')).get( 'total_quantity') or 0 quantity_kill_house_to_stw = kill_house_to_stw.aggregate( total_quantity=Sum('real_number_of_carcasses')).get( 'total_quantity') or 0 weight_kill_house_to_stw = kill_house_to_stw.aggregate( total_quantity=Sum('real_weight_of_carcasses')).get( 'total_quantity') or 0 kill_house_to_guild = allocations.filter(allocation_type='killhouse_guild') quantity_kill_house_to_guild = kill_house_to_guild.aggregate( total_quantity=Sum('real_number_of_carcasses')).get( 'total_quantity') or 0 weight_kill_house_to_guild = kill_house_to_guild.aggregate( total_quantity=Sum('real_weight_of_carcasses')).get( 'total_quantity') or 0 ware_house_accepted_real_weight = kill_house_request.aggregate( total_quantity=Sum('ware_house_accepted_real_weight')).get( 'total_quantity') or 0 weight_of_carcasses = kill_house_free_buying_bars.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 product = RolesProducts.objects.filter(trash=False, kill_house=kill_house).first() if product: total_remain_weight = product.total_remain_weight else: total_remain_weight = 0 list1 = [ killer_type, f"{kill_house.name}-{kill_house.kill_house_operator.user.mobile}-{kill_house.kill_house_operator.user.city.name}", ((weight_allocations + weight_kill_house_free_sale_bars) - ( ware_house_accepted_real_weight + weight_of_carcasses) + total_remain_weight), ware_house_accepted_real_weight + weight_of_carcasses, len(allocations), weight_allocations + weight_kill_house_free_sale_bars, weight_kill_house_free_sale_bars, len(kill_house_to_stw), weight_kill_house_to_stw, len(kill_house_to_guild), weight_kill_house_to_guild, f"%{int((weight_allocations + weight_kill_house_free_sale_bars) * 100 / (ware_house_accepted_real_weight + weight_of_carcasses)) if (ware_house_accepted_real_weight + weight_of_carcasses) > 0 else 0}", total_remain_weight ] create_value(worksheet, list1, l, 3, border_style='thin', width=20) l += 1 l += 7 create_header(worksheet, header_list2, 3, l, border_style='thin', width=20) stewards = Guilds.objects.filter(trash=False, steward=True) for steward in stewards: if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() allocations = StewardAllocation.objects.filter( Q(to_steward=steward) | Q(steward=steward), trash=False, date__date__gte=date1, date__date__lte=date2, calculate_status=True ).order_by('id') guild_steward_free_buying_bars = StewardFreeBarInformation.objects.filter( Q(guild=steward) | Q(steward=steward), trash=False, date__date__gte=date1, date__date__lte=date2) guild_steward_free_sale_bars = StewardFreeSaleBarInformation.objects.filter( Q(guild=steward) | Q(steward=steward), trash=False, date__date__gte=date1, date__date__lte=date2) else: allocations = StewardAllocation.objects.filter( Q(to_steward=steward) | Q(steward=steward), trash=False, calculate_status=True).order_by('id') guild_steward_free_buying_bars = StewardFreeBarInformation.objects.filter( Q(guild=steward) | Q(steward=steward), trash=False) guild_steward_free_sale_bars = StewardFreeSaleBarInformation.objects.filter( Q(guild=steward) | Q(steward=steward), trash=False) product = RolesProducts.objects.filter(trash=False, guild=steward).first() if product: total_remain_weight = product.total_remain_weight else: total_remain_weight = 0 recive_allocation = allocations.filter(to_steward=steward, receiver_state='accepted') allocate_allocation = allocations.filter(steward=steward) real_weight_of_carcasses = recive_allocation.aggregate( total_quantity=Sum('real_weight_of_carcasses')).get( 'total_quantity') or 0 number_of_carcasses_guild_steward_free_buying_bars = guild_steward_free_buying_bars.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 weight_guild_steward_free_buying_bars = guild_steward_free_sale_bars.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 number_of_carcasses_guild_steward_free_buying_bars = guild_steward_free_sale_bars.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 real_number_of_carcasses_allocate_allocation = allocate_allocation.aggregate( total_quantity=Sum('real_number_of_carcasses')).get( 'total_quantity') or 0 real_weight_of_carcasses_allocate_allocation = allocate_allocation.aggregate( total_quantity=Sum('real_weight_of_carcasses')).get( 'total_quantity') or 0 kill_house_to_stw = allocations.filter(allocation_type='steward_steward') quantity_kill_house_to_stw = kill_house_to_stw.aggregate( total_quantity=Sum('real_number_of_carcasses')).get( 'total_quantity') or 0 weight_kill_house_to_stw = kill_house_to_stw.aggregate( total_quantity=Sum('real_weight_of_carcasses')).get( 'total_quantity') or 0 kill_house_to_guild = allocations.filter(allocation_type='steward_guild') quantity_kill_house_to_guild = kill_house_to_guild.aggregate( total_quantity=Sum('real_number_of_carcasses')).get( 'total_quantity') or 0 weight_kill_house_to_guild = kill_house_to_guild.aggregate( total_quantity=Sum('real_weight_of_carcasses')).get( 'total_quantity') or 0 if real_weight_of_carcasses + real_weight_of_carcasses_allocate_allocation > 0: list1 = [ 'مباشر', f"{steward.guilds_name}-{steward.user.mobile}-{steward.user.city.name}", ((real_weight_of_carcasses + weight_guild_steward_free_buying_bars) - ( real_weight_of_carcasses_allocate_allocation + number_of_carcasses_guild_steward_free_buying_bars) + total_remain_weight), real_weight_of_carcasses + weight_guild_steward_free_buying_bars, len(allocations), real_weight_of_carcasses_allocate_allocation + number_of_carcasses_guild_steward_free_buying_bars, weight_guild_steward_free_buying_bars, len(kill_house_to_stw), weight_kill_house_to_stw, len(kill_house_to_guild), weight_kill_house_to_guild, f"%{int((real_weight_of_carcasses_allocate_allocation + number_of_carcasses_guild_steward_free_buying_bars) * 100 / (real_weight_of_carcasses + weight_guild_steward_free_buying_bars)) if (real_weight_of_carcasses + weight_guild_steward_free_buying_bars) > 0 else 0}", total_remain_weight ] create_value(worksheet, list1, l + 1, 3, border_style='thin', width=20) l += 1 l += 5 list5 = ['شهر'] kill_house_name = KillHouse.objects.filter(trash=False, out_province=False).order_by('id').values_list( 'name', flat=True) list5.extend(kill_house_name) list5.append('مجموع') create_header(worksheet, list5, 3, l, border_style='thin', width=20) cities = City.objects.filter(trash=False).order_by('id') for city in cities: if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() result = get_kill_house_distribution_info(city, date1, date2) result1 = all_get_kill_house_distribution_info(city, date1, date2) else: result = get_kill_house_distribution_info(city) result1 = all_get_kill_house_distribution_info(city) create_value(worksheet, result, l + 1, 3, border_style='thin', width=20) create_value(worksheet, [result1], l + 1, int(len(list5) + 2), border_style='thin', width=20) l += 1 if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() result = get_kill_house_distribution_out_province_info(date1, date2) else: result = get_kill_house_distribution_out_province_info() create_value(worksheet, result, l + 1, 3, border_style='thin', width=20) elif sheet_name == 'تخصیصات کشتارگاه به مباشر و صنف': if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() allocations = StewardAllocation.objects.filter( allocation_type__in=('killhouse_steward', 'killhouse_guild'), trash=False, date__date__gte=date1, date__date__lte=date2, kill_house__isnull=False, calculate_status=True).order_by('id') else: allocations = StewardAllocation.objects.filter( allocation_type__in=('killhouse_steward', 'killhouse_guild'), trash=False, kill_house__isnull=False, calculate_status=True).order_by('id') excel_options = [ 'ردیف', 'نام کشتارگاه', 'نام مالک', 'شماره مالک', 'شهر مالک', 'تاریخ ثبت', 'نوع تخصیص', 'خریدار', 'تلفن خریدار', 'شهر خریدار', 'نوع فروش', 'قیمت هر کیلو(ریال)', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', 'کد احراز', 'وضعیت کد احراز', 'وضعیت', ] blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد تخصیصات', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'تخصیصات کشتارگاه به مباشرین ', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if allocations: for allocation in allocations: l += 1 if allocation.allocation_type == 'killhouse_steward': allocation_type = 'کشتارگاه به مباشر' buyer_name = allocation.to_steward.guilds_name buyer_mobile = allocation.to_steward.user.mobile buyer_city = allocation.to_steward.user.city.name elif allocation.allocation_type == 'killhouse_guild': allocation_type = 'کشتارگاه به صنف' buyer_name = allocation.to_guilds.guilds_name if allocation.to_guilds else '-' buyer_mobile = allocation.to_guilds.user.mobile if allocation.to_guilds else '-' buyer_city = allocation.to_guilds.user.city.name if allocation.to_guilds else '-' else: allocation_type = '' buyer_name = '' buyer_mobile = '' buyer_city = '' if allocation.sell_type == 'exclusive': sell_type = 'اختصاصی' else: sell_type = '' system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده' state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده' list1 = [ m, allocation.kill_house.name, allocation.kill_house.kill_house_operator.user.fullname, allocation.kill_house.kill_house_operator.user.mobile, allocation.kill_house.kill_house_operator.user.city.name, str(convert_to_shamsi(datetime=allocation.date)), allocation_type, buyer_name, buyer_mobile, buyer_city, sell_type, allocation.amount, allocation.total_amount, allocation.weight_of_carcasses, allocation.receiver_real_weight_of_carcasses, allocation.registration_code, system_registration_code, state, ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) total_amount_allocations = allocations.aggregate( total_quantity=Sum('total_amount')).get( 'total_quantity') or 0 number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 receiver_real_number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_number_of_carcasses')).get( 'total_quantity') or 0 receiver_real_weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_weight_of_carcasses')).get( 'total_quantity') or 0 value_header_list2 = [ len(allocations), total_amount_allocations, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', total_amount_allocations, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, '', '', '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'تخصیصات سرد خانه': if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() allocations = StewardAllocation.objects.filter( allocation_type='ColdHouse', trash=False, date__date__gte=date1, date__date__lte=date2, kill_house__isnull=False, calculate_status=True).order_by('id') else: allocations = StewardAllocation.objects.filter( allocation_type='ColdHouse', trash=False, kill_house__isnull=False, calculate_status=True).order_by('id') excel_options = [ 'ردیف', 'فروشنده', 'نام فروشنده', 'شماره فروشنده', 'شهر فروشنده', 'تاریخ ثبت', 'نوع تخصیص', 'خریدار', 'تلفن خریدار', 'شهر خریدار', 'نوع فروش', 'قیمت هر کیلو(ریال)', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', 'کد احراز', 'وضعیت کد احراز', 'وضعیت', ] blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد تخصیصات', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'تخصیصات سردخانه', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if allocations: for allocation in allocations: l += 1 if allocation.allocation_type == 'killhouse_steward': allocation_type = 'کشتارگاه به مباشر' buyer_name = allocation.to_steward.guilds_name buyer_mobile = allocation.to_steward.user.mobile buyer_city = allocation.to_steward.user.city.name elif allocation.allocation_type == 'killhouse_guild': allocation_type = 'کشتارگاه به صنف' buyer_name = allocation.to_guilds.guilds_name buyer_mobile = allocation.to_guilds.user.mobile buyer_city = allocation.to_guilds.user.city.name elif allocation.allocation_type == 'ColdHouse': allocation_type = 'کشتارگاه به سردخانه' if allocation.to_cold_house.kill_house: buyer_name = allocation.to_cold_house.kill_house.name buyer_mobile = allocation.to_cold_house.kill_house.kill_house_operator.user.mobile buyer_city = allocation.to_cold_house.kill_house.kill_house_operator.user.city.name else: buyer_name = allocation.to_cold_house.live_stock_support.user.name buyer_mobile = allocation.to_cold_house.live_stock_support.user.mobile buyer_city = allocation.to_cold_house.live_stock_support.user.city.name elif allocation.allocation_type == 'killhouse_killhouse': allocation_type = 'کشتارگاه به کشتارگاه' buyer_name = allocation.to_kill_house.kill_house.name buyer_mobile = allocation.to_kill_house.kill_house_operator.user.mobile buyer_city = allocation.to_kill_house.kill_house_operator.user.city.name else: allocation_type = '' buyer_name = '' buyer_mobile = '' buyer_city = '' if allocation.sell_type == 'exclusive': sell_type = 'اختصاصی' else: sell_type = 'آزاد' system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده' state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده' list1 = [ m, allocation.kill_house.name, allocation.kill_house.kill_house_operator.user.fullname, allocation.kill_house.kill_house_operator.user.mobile, allocation.kill_house.kill_house_operator.user.city.name, str(convert_to_shamsi(datetime=allocation.date)), allocation_type, buyer_name, buyer_mobile, buyer_city, sell_type, allocation.amount, allocation.total_amount, allocation.weight_of_carcasses, allocation.receiver_real_weight_of_carcasses, allocation.registration_code, system_registration_code, state, ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) total_amount_allocations = allocations.aggregate( total_quantity=Sum('total_amount')).get( 'total_quantity') or 0 number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 receiver_real_number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_number_of_carcasses')).get( 'total_quantity') or 0 receiver_real_weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_weight_of_carcasses')).get( 'total_quantity') or 0 value_header_list2 = [ len(allocations), total_amount_allocations, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', total_amount_allocations, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, '', '', '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'تخصیصات مباشر به صنف': if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() allocations = StewardAllocation.objects.filter( allocation_type='steward_guild', trash=False, date__date__gte=date1, date__date__lte=date2, calculate_status=True).order_by('id') else: allocations = StewardAllocation.objects.filter( allocation_type='steward_guild', trash=False, calculate_status=True).order_by('id') excel_options = [ 'ردیف', 'فروشنده', 'نام فروشنده', 'شماره فروشنده', 'شهر فروشنده', 'تاریخ ثبت', 'نوع تخصیص', 'خریدار', 'تلفن خریدار', 'شهر خریدار', 'نوع فروش', 'قیمت هر کیلو(ریال)', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', 'کد احراز', 'وضعیت کد احراز', 'وضعیت', ] blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد تخصیصات', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'تخصیصات مباشر به صنف ', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if allocations: for allocation in allocations: l += 1 if allocation.allocation_type == 'killhouse_steward': allocation_type = 'کشتارگاه به مباشر' buyer_name = allocation.to_steward.guilds_name buyer_mobile = allocation.to_steward.user.mobile buyer_city = allocation.to_steward.user.city.name elif allocation.allocation_type == 'killhouse_guild' or allocation.allocation_type == 'steward_guild': allocation_type = 'مباشر به صنف' buyer_name = allocation.to_guilds.guilds_name buyer_mobile = allocation.to_guilds.user.mobile buyer_city = allocation.to_guilds.user.city.name else: allocation_type = '' buyer_name = '' buyer_mobile = '' buyer_city = '' if allocation.sell_type == 'exclusive': sell_type = 'اختصاصی' else: sell_type = '' system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده' state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده' list1 = [ m, allocation.steward.guilds_name, allocation.steward.user.fullname, allocation.steward.user.mobile, allocation.steward.user.city.name, str(convert_to_shamsi(datetime=allocation.date)), allocation_type, buyer_name, buyer_mobile, buyer_city, sell_type, allocation.amount, allocation.total_amount, allocation.weight_of_carcasses, allocation.receiver_real_weight_of_carcasses, allocation.registration_code, system_registration_code, state, ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) total_amount_allocations = allocations.aggregate( total_quantity=Sum('total_amount')).get( 'total_quantity') or 0 number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 receiver_real_number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_number_of_carcasses')).get( 'total_quantity') or 0 receiver_real_weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_weight_of_carcasses')).get( 'total_quantity') or 0 value_header_list2 = [ len(allocations), total_amount_allocations, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', total_amount_allocations, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, '', '', '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'تخصیصات صنف به صنف': if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() allocations = StewardAllocation.objects.filter( allocation_type='guild_guild', trash=False, date__date__gte=date1, date__date__lte=date2, calculate_status=True).order_by('id') else: allocations = StewardAllocation.objects.filter( allocation_type='guild_guild', trash=False, calculate_status=True).order_by('id') excel_options = [ 'ردیف', 'فروشنده', 'نام فروشنده', 'شماره فروشنده', 'شهر فروشنده', 'تاریخ ثبت', 'نوع تخصیص', 'خریدار', 'تلفن خریدار', 'شهر خریدار', 'نوع فروش', 'قیمت هر کیلو(ریال)', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', 'کد احراز', 'وضعیت کد احراز', 'وضعیت', ] blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد تخصیصات', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'تخصیصات صنف به صنف ', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if allocations: for allocation in allocations: l += 1 if allocation.allocation_type == 'killhouse_steward': allocation_type = 'کشتارگاه به مباشر' buyer_name = allocation.to_steward.guilds_name buyer_mobile = allocation.to_steward.user.mobile buyer_city = allocation.to_steward.user.city.name elif allocation.allocation_type == 'killhouse_guild' or allocation.allocation_type == 'steward_guild' or \ allocation.allocation_type == 'guild_guild': allocation_type = 'صنف به صنف' buyer_name = allocation.to_guilds.guilds_name buyer_mobile = allocation.to_guilds.user.mobile buyer_city = allocation.to_guilds.user.city.name else: allocation_type = '' buyer_name = '' buyer_mobile = '' buyer_city = '' if allocation.sell_type == 'exclusive': sell_type = 'اختصاصی' else: sell_type = '' system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده' state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده' list1 = [ m, allocation.steward.guilds_name, allocation.steward.user.fullname, allocation.steward.user.mobile, allocation.steward.user.city.name, str(convert_to_shamsi(datetime=allocation.date)), allocation_type, buyer_name, buyer_mobile, buyer_city, sell_type, allocation.amount, allocation.total_amount, allocation.weight_of_carcasses, allocation.receiver_real_weight_of_carcasses, allocation.registration_code, system_registration_code, state, ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) total_amount_allocations = allocations.aggregate( total_quantity=Sum('total_amount')).get( 'total_quantity') or 0 number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 receiver_real_number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_number_of_carcasses')).get( 'total_quantity') or 0 receiver_real_weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_weight_of_carcasses')).get( 'total_quantity') or 0 value_header_list2 = [ len(allocations), total_amount_allocations, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', total_amount_allocations, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, '', '', '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") # elif sheet_name == 'تخصیصات مباشر به مباشر': # # if 'date1' in request.GET and request.GET['date1']: # # date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() # # date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() # # allocations = StewardAllocation.objects.filter( # allocation_type='steward_guild', # trash=False, date__date__gte=date1, # date__date__lte=date2, kill_house__isnull=False, calculate_status=True).order_by('id') # else: # allocations = StewardAllocation.objects.filter( # allocation_type='steward_guild', # trash=False, kill_house__isnull=False, calculate_status=True).order_by('id') # # excel_options = [ # 'ردیف', # 'نام کشتارگاه', # 'نام مالک', # 'شماره مالک', # 'شهر مالک', # 'تاریخ ثبت', # 'نوع تخصیص', # 'خریدار', # 'تلفن خریدار', # 'شهر خریدار', # 'نوع فروش', # 'قیمت هر کیلو(ریال)', # 'قیمت کل', # 'حجم تخصیصی', # 'وزن تخصیصی', # 'حجم تایید شده', # 'وزن تایید شده', # 'کد احراز', # 'وضعیت کد احراز', # 'وضعیت', # # ] # # blue_fill = PatternFill(start_color="1E487B", fill_type="solid") # cell = worksheet.cell(row=1, column=1) # cell.alignment = Alignment(horizontal='center', vertical='center') # red_font = Font(color="C00000", bold=True) # if 'date1' in request.GET: # date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() # date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() # from_date_1 = shamsi_date(date1) # to_date_1 = shamsi_date(date2) # worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' # header_list2 = [ # 'تعداد تخصیصات', # 'قیمت کل', # 'حجم تخصیصی', # 'وزن تخصیصی', # 'حجم تایید شده', # 'وزن تایید شده', # # ] # # for col_num, option in enumerate(header_list2, 5): # cell = worksheet.cell(row=2, column=col_num, value=option) # cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) # cell.fill = PatternFill(start_color="00B050", fill_type="solid") # cell.font = Font(size=9, bold=True, color='D9FFFFFF') # worksheet.row_dimensions[2].height = 20.8 # create_header_freez(worksheet, excel_options, 1, 6, 7, 20) # # excel_description(worksheet, 'A1', f'تخصیصات مباشر به صنف ', size=11, color='red', # row2='D1') # # worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') # worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') # worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') # merge_range1 = 'B1:D1' # merge_range2 = 'B2:D2' # merge_range = 'B3:D3' # worksheet.merge_cells(merge_range1) # worksheet.merge_cells(merge_range) # worksheet.merge_cells(merge_range2) # worksheet['B1'].font = red_font # worksheet['B3'].font = Font(size=11) # worksheet['B2'].font = Font(size=10, bold=True, color="C00000") # # l = 5 # m = 1 # # if allocations: # for allocation in allocations: # l += 1 # if allocation.allocation_type == 'killhouse_steward' : # allocation_type = 'کشتارگاه به مباشر' # buyer_name = allocation.to_steward.guilds_name # buyer_mobile = allocation.to_steward.user.mobile # buyer_city = allocation.to_steward.user.city.name # elif allocation.allocation_type == 'killhouse_guild' or allocation.allocation_type == 'steward_guild': # allocation_type = 'کشتارگاه به صنف' # buyer_name = allocation.to_guilds.guilds_name # buyer_mobile = allocation.to_guilds.user.mobile # buyer_city = allocation.to_guilds.user.city.name # # else: # allocation_type = '' # buyer_name = '' # buyer_mobile = '' # buyer_city = '' # # if allocation.sell_type == 'exclusive': # sell_type = 'اختصاصی' # else: # sell_type = '' # system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده' # state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده' # list1 = [ # m, # allocation.kill_house.name, # allocation.kill_house.kill_house_operator.user.fullname, # allocation.kill_house.kill_house_operator.user.mobile, # allocation.kill_house.kill_house_operator.user.city.name, # str(convert_to_shamsi(datetime=allocation.date)), # allocation_type, # buyer_name, # buyer_mobile, # buyer_city, # sell_type, # allocation.amount, # allocation.total_amount, # allocation.number_of_carcasses, # allocation.weight_of_carcasses, # allocation.receiver_real_number_of_carcasses, # allocation.receiver_real_weight_of_carcasses, # allocation.registration_code, # system_registration_code, # state, # # ] # m += 1 # create_value(worksheet,list1,l+1,1,height=20,width=30) # # total_amount_allocations = allocations.aggregate( # total_quantity=Sum('total_amount')).get( # 'total_quantity') or 0 # number_of_carcasses_allocations = allocations.aggregate( # total_quantity=Sum('number_of_carcasses')).get( # 'total_quantity') or 0 # weight_of_carcasses_allocations = allocations.aggregate( # total_quantity=Sum('weight_of_carcasses')).get( # 'total_quantity') or 0 # receiver_real_number_of_carcasses_allocations = allocations.aggregate( # total_quantity=Sum('receiver_real_number_of_carcasses')).get( # 'total_quantity') or 0 # receiver_real_weight_of_carcasses_allocations = allocations.aggregate( # total_quantity=Sum('receiver_real_weight_of_carcasses')).get( # 'total_quantity') or 0 # # value_header_list2 = [ # len(allocations), # total_amount_allocations, # number_of_carcasses_allocations, # weight_of_carcasses_allocations, # receiver_real_number_of_carcasses_allocations, # receiver_real_weight_of_carcasses_allocations, # # ] # for item in range(len(value_header_list2)): # cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) # value = value_header_list2[item] # # Check if the value is a number before formatting # if isinstance(value, (int, float)): # if value != 0: # cell.number_format = '#,###' # Apply general number format # else: # cell.value = value # Keep as text for other values # # cell.alignment = Alignment(horizontal='center') # cell.font = Font(size=10, bold=True) # list2 = [ # 'مجموع==>', # '', # '', # '', # '', # '', # '', # '', # '', # '', # total_amount_allocations, # number_of_carcasses_allocations, # weight_of_carcasses_allocations, # receiver_real_number_of_carcasses_allocations, # receiver_real_weight_of_carcasses_allocations, # '', # '', # '', # # ] # for item in range(len(list2)): # cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) # value = list2[item] # if isinstance(value, (int, float)): # cell.number_format = '#,###' # Apply general number format # else: # cell.value = value # Keep as text for other values # # cell.alignment = Alignment(horizontal='center') # cell.font = Font(size=10, bold=True) # cell.font = Font(bold=True) # cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'عملکرد مباشرین': if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() allocations = StewardAllocation.objects.filter( allocation_type__in=('killhouse_steward', 'killhouse_guild'), trash=False, date__date__gte=date1, date__date__lte=date2, calculate_status=True).order_by('id') else: allocations = StewardAllocation.objects.filter( allocation_type__in=('killhouse_steward', 'killhouse_guild'), trash=False, calculate_status=True).order_by('id') user_value = list(allocations.values_list('to_steward__user__user', flat=True).distinct()) user_value2 = list(allocations.values_list('to_guilds__user__user', flat=True).distinct()) user_value3 = list(set(user_value + user_value2)) excel_options = [ 'ردیف', 'خریدار', 'تلفن خریدار', 'شهر خریدار', 'وزن تخصیصی', 'وزن تایید شده', 'تخصیص دهنده', ] blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد مباشرین', 'وزن تخصیصی', 'وزن تایید شده', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'عملکرد مباشرین', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if allocations: for user in user_value3: user_new = SystemUserProfile.objects.filter(trash=False, user=user).first() guilds = Guilds.objects.filter(trash=False, user=user_new).first() new_allocation = allocations.filter(Q(to_steward=guilds) | Q(to_guilds=guilds)) kill_house_name = new_allocation.values_list('kill_house__name', flat=True).distinct() kill_house_names = [str(name) for name in kill_house_name if name is not None] if kill_house_names: kill_house_name_str = ' / '.join(set(kill_house_names)) else: kill_house_name_str = '-' weight_of_carcasses_allocations = new_allocation.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 receiver_real_number_of_carcasses_allocations = new_allocation.aggregate( total_quantity=Sum('receiver_real_number_of_carcasses')).get( 'total_quantity') or 0 receiver_real_weight_of_carcasses_allocations = new_allocation.aggregate( total_quantity=Sum('receiver_real_weight_of_carcasses')).get( 'total_quantity') or 0 if guilds: l += 1 list1 = [ m, guilds.guilds_name if guilds else '-', user_new.mobile if user_new else '-', user_new.city.name if user_new else '-', weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, kill_house_name_str ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 receiver_real_number_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_number_of_carcasses')).get( 'total_quantity') or 0 receiver_real_weight_of_carcasses_allocations = allocations.aggregate( total_quantity=Sum('receiver_real_weight_of_carcasses')).get( 'total_quantity') or 0 # value_header_list2 = [ len(user_value3), weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") # elif sheet_name == 'تخصیصات مباشرین به صنوف': # # if 'date1' in request.GET and request.GET['date1']: # # date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() # # date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() # # allocations = StewardAllocation.objects.filter(allocation_type__in=('steward_guild', 'steward_steward'), # trash=False, date__date__gte=date1, # date__date__lte=date2, calculate_status=True # ).order_by('id') # else: # allocations = StewardAllocation.objects.filter(allocation_type__in=('steward_guild', 'steward_steward'), # trash=False, calculate_status=True).order_by('id') # # excel_options = [ # 'ردیف', # 'ماهیت', # 'نام مالک', # 'شماره مالک', # 'شهر مالک', # 'تاریخ ثبت', # 'نوع تخصیص', # 'خریدار', # 'تلفن خریدار', # 'شهر خریدار', # 'نوع فروش', # 'قیمت هر کیلو(ریال)', # 'قیمت کل', # 'حجم تخصیصی', # 'وزن تخصیصی', # 'حجم تایید شده', # 'وزن تایید شده', # 'کد احراز', # 'وضعیت کد احراز', # 'وضعیت', # # ] # # cell = worksheet.cell(row=1, column=1) # cell.alignment = Alignment(horizontal='center', vertical='center') # red_font = Font(color="C00000", bold=True) # if 'date1' in request.GET: # date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() # date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() # from_date_1 = shamsi_date(date1) # to_date_1 = shamsi_date(date2) # worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' # header_list2 = [ # 'تعداد تخصیصات', # 'قیمت کل', # 'حجم تخصیصی', # 'وزن تخصیصی', # 'حجم تایید شده', # 'وزن تایید شده', # # ] # # for col_num, option in enumerate(header_list2, 5): # cell = worksheet.cell(row=2, column=col_num, value=option) # cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) # cell.fill = PatternFill(start_color="00B050", fill_type="solid") # cell.font = Font(size=9, bold=True, color='D9FFFFFF') # worksheet.row_dimensions[2].height = 20.8 # create_header_freez(worksheet, excel_options, 1, 6, 7, 20) # # excel_description(worksheet, 'A1', f'تخصیصات کشتارگاه به صنف ', size=11, color='red', # row2='D1') # # worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') # worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') # worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') # merge_range1 = 'B1:D1' # merge_range2 = 'B2:D2' # merge_range = 'B3:D3' # worksheet.merge_cells(merge_range1) # worksheet.merge_cells(merge_range) # worksheet.merge_cells(merge_range2) # worksheet['B1'].font = red_font # worksheet['B3'].font = Font(size=11) # worksheet['B2'].font = Font(size=10, bold=True, color="C00000") # # l = 5 # m = 1 # # if allocations: # for allocation in allocations: # l += 1 # if allocation.allocation_type == 'killhouse_steward': # allocation_type = 'کشتارگاه به مباشر' # buyer_name = allocation.to_steward.guilds_name # buyer_mobile = allocation.to_steward.user.mobile # buyer_city = allocation.to_steward.user.city.name # elif allocation.allocation_type == 'killhouse_guild': # allocation_type = 'کشتارگاه به صنف' # buyer_name = allocation.to_guilds.guilds_name # buyer_mobile = allocation.to_guilds.user.mobile # buyer_city = allocation.to_guilds.user.city.name # elif allocation.allocation_type == 'steward_guild': # allocation_type = 'مباشر به صنف' # buyer_name = allocation.to_guilds.guilds_name # buyer_mobile = allocation.to_guilds.user.mobile # buyer_city = allocation.to_guilds.user.city.name # elif allocation.allocation_type == 'steward_steward': # allocation_type = 'مباشر به مباشر' # buyer_name = allocation.to_steward.guilds_name # buyer_mobile = allocation.to_steward.user.mobile # buyer_city = allocation.to_steward.user.city.name # else: # allocation_type = '' # buyer_name = '' # buyer_mobile = '' # buyer_city = '' # # if allocation.sell_type == 'exclusive': # sell_type = 'اختصاصی' # else: # sell_type = '' # system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده' # state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده' # type = 'مباشر' if allocation.steward.steward == True else 'صنف' # list1 = [ # m, # type, # allocation.steward.user.fullname, # allocation.steward.user.mobile, # allocation.steward.user.city.name, # str(convert_to_shamsi(datetime=allocation.date)), # allocation_type, # buyer_name, # buyer_mobile, # buyer_city, # sell_type, # allocation.amount, # allocation.total_amount, # allocation.number_of_carcasses, # allocation.weight_of_carcasses, # allocation.receiver_real_number_of_carcasses, # allocation.receiver_real_weight_of_carcasses, # allocation.registration_code, # system_registration_code, # state, # # ] # m += 1 # create_value(worksheet, list1, l + 1, 1, height=20, width=30) # # total_amount_allocations = allocations.aggregate( # total_quantity=Sum('total_amount')).get( # 'total_quantity') or 0 # number_of_carcasses_allocations = allocations.aggregate( # total_quantity=Sum('number_of_carcasses')).get( # 'total_quantity') or 0 # weight_of_carcasses_allocations = allocations.aggregate( # total_quantity=Sum('weight_of_carcasses')).get( # 'total_quantity') or 0 # receiver_real_number_of_carcasses_allocations = allocations.aggregate( # total_quantity=Sum('receiver_real_number_of_carcasses')).get( # 'total_quantity') or 0 # receiver_real_weight_of_carcasses_allocations = allocations.aggregate( # total_quantity=Sum('receiver_real_weight_of_carcasses')).get( # 'total_quantity') or 0 # # value_header_list2 = [ # len(allocations), # total_amount_allocations, # number_of_carcasses_allocations, # weight_of_carcasses_allocations, # receiver_real_number_of_carcasses_allocations, # receiver_real_weight_of_carcasses_allocations, # # ] # for item in range(len(value_header_list2)): # cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) # value = value_header_list2[item] # # Check if the value is a number before formatting # if isinstance(value, (int, float)): # if value != 0: # cell.number_format = '#,###' # Apply general number format # else: # cell.value = value # Keep as text for other values # # cell.alignment = Alignment(horizontal='center') # cell.font = Font(size=10, bold=True) # list2 = [ # 'مجموع==>', # '', # '', # '', # '', # '', # '', # '', # '', # '', # '', # '', # total_amount_allocations, # number_of_carcasses_allocations, # weight_of_carcasses_allocations, # receiver_real_number_of_carcasses_allocations, # receiver_real_weight_of_carcasses_allocations, # '', # '', # '', # # ] # for item in range(len(list2)): # cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) # value = list2[item] # if isinstance(value, (int, float)): # cell.number_format = '#,###' # Apply general number format # else: # cell.value = value # Keep as text for other values # # cell.alignment = Alignment(horizontal='center') # cell.font = Font(size=10, bold=True) # cell.font = Font(bold=True) # cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'تراکنش های صنوف': if 'date1' in request.GET and 'date2' in request.GET: date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date() date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date() guilds = Guilds.objects.filter( id__in=PosMachineTransactions.objects.filter( trash=False, date__date__gte=date1, date__date__lte=date2, pos__guild__isnull=False, paid=True ).values_list('pos__guild__id', flat=True).distinct() ) else: guilds = Guilds.objects.filter( id__in=PosMachineTransactions.objects.filter( trash=False, pos__guild__isnull=False, paid=True ).values_list('pos__guild__id', flat=True).distinct() ) serializer = GuildsPosMachineForTransactionsSerializer(guilds, many=True, context={'request': request}) excel_options = [ 'ردیف', 'نام واحد صنفی', 'موبایل', 'شهر', 'تعداد تراکنش ها', 'مبلغ کل تراکنش ها', 'کل ورودی به انبار(کیلوگرم)', 'کل فروش(کیلوگرم)', 'مانده انبار(کیلوگرم)', ] cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد تراکنش ها', 'تعداد صنوف', 'مبلغ کل تراکنش ها', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'تراکنش های صنف ', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if serializer.data: for data in serializer.data: l += 1 list1 = [ m, data['guilds_name'], data['user']['mobile'], data['user']['city']['name'], data['transaction']['len_transaction'], data['transaction']['total_price'], data['transaction']['total_carcasses_weight'], data['transaction']['real_allocated_weight'], data['transaction']['total_remain_weight'], ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) pos = PosMachineTransactions.objects.filter(trash=False, pos__guild__in=guilds, paid=True) total_price = pos.aggregate(total=Sum('price'))[ 'total'] or 0 value_header_list2 = [ len(pos), len(guilds), total_price, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) len_transaction = sum(item['transaction'].get('len_transaction', 0) for item in serializer.data) total_price = sum(item['transaction'].get('total_price', 0) for item in serializer.data) total_carcasses_weight = sum( item['transaction'].get('total_carcasses_weight', 0) for item in serializer.data) real_allocated_weight = sum(item['transaction'].get('real_allocated_weight', 0) for item in serializer.data) total_remain_weight = sum(item['transaction'].get('total_remain_weight', 0) for item in serializer.data) list2 = [ 'مجموع==>', '', '', '', len_transaction, total_price, total_carcasses_weight, real_allocated_weight, total_remain_weight, ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 login_user_excel(request): if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None accesstokens = AccessToken.objects.filter(created__date__gte=date1, created__date__lte=date2).select_related( 'user').order_by('-id') else: accesstokens = AccessToken.objects.filter(created__date__gt='2024-12-15').select_related('user').order_by('-id') 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_CELL m = 1 create_header_freez(worksheet, excel_options, 1, 1, 2, 20, width=30) l = 2 for accesstoken in accesstokens: user = SystemUserProfile.objects.get(user=accesstoken.user) role_list = [role.name for role in user.role.all()] date = convert_to_shamsi(datetime=accesstoken.created) list1 = [ m, user.fullname, user.mobile, str(date), accesstoken.token, str(role_list), user.city.name if user.city else '-' ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=20) m += 1 l += 1 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 sub_section_of_cooperative_share_detail(request): total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_sell_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id') province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user__in=kill_houses, trash=False, archive_wage=False, return_to_province=False, state__in=('pending', 'accepted'), first_car_allocated_quantity=0).order_by('id') kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q( Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False, trash=False, calculate_status=True ) total_province_live_weight = province_kill_requests.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 total_province_live_quantity = province_kill_requests.aggregate(total=Sum('total_killed_quantity'))[ 'total'] or 0 total_province_live_weight += kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 total_province_live_quantity += kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0 total_province_carcasses_weight = total_province_live_weight * 0.75 total_pure_province_carcasses_weight = total_province_carcasses_weight - get_difference_carcasses_weight( kill_houses) # return Response(total_pure_province_carcasses_weight) internal_total_pure_province_carcasses_weight = ( total_pure_province_carcasses_weight / total_province_carcasses_weight) * total_province_carcasses_weight external_total_pure_province_carcasses_weight = total_province_carcasses_weight - internal_total_pure_province_carcasses_weight total_pure_province_carcasses_price = internal_total_pure_province_carcasses_weight * province_live_wage_amount total_out_selling_province_carcasses_price = external_total_pure_province_carcasses_weight * free_sell_carcesses_weight_amount poultries = Poultry.objects.filter(trash=False, city_operator__isnull=False).order_by('id') hatchings = PoultryHatching.objects.filter(poultry__in=poultries, killed_quantity__gt=0, trash=False).order_by( 'poultry') hatching_quantity = hatchings.aggregate(total=Sum('quantity'))[ 'total'] or 0 poultry_requests = PoultryRequest.objects.filter(trash=False, state_process__in=('pending', 'accepted'), province_state__in=('pending', 'accepted'), out=True, out_province_request_cancel=False, temporary_trash=False, has_wage=True, wage_pay=True, temporary_deleted=False, hatching__in=hatchings) out_province_poultry_request_quantity = poultry_requests.aggregate(total=Sum('quantity'))[ 'total'] or 0 out_province_poultry_request_weight = poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 union_out_province_poultry_request_amount = poultry_requests.aggregate(total=Sum('union_share'))[ 'total'] or 0 percentages_wage_type = PercentageOfWageType.objects.filter(trash=False) union_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='union').first().percent / 100 union_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='union').first().percent / 100 union_province_kill_request_wage = total_pure_province_carcasses_price * union_province_kill_request_percent union_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * union_free_sell_carcasses_percent city_percent_province_kill_request = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='province-kill-request').first().percent / 100 city_percent_out_poultry_request = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='poultry-sell-out-province').first().percent / 100 city_percent_out_sell_carcasses = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='carcasse-sell').first().percent / 100 union_total_wage = union_province_kill_request_wage + union_out_province_poultry_request_amount + union_free_sell_carcasses_wage hatching_killing_percent = (( out_province_poultry_request_quantity + total_province_live_quantity) / hatching_quantity) * 100 city_province_kill_request_wage = union_province_kill_request_wage * city_percent_province_kill_request city_out_province_poultry_request = union_out_province_poultry_request_amount * city_percent_out_poultry_request city_out_province_sell_carcasses = union_free_sell_carcasses_wage * city_percent_out_sell_carcasses city_total_wage = city_province_kill_request_wage + city_out_province_poultry_request + city_out_province_sell_carcasses city_operator_deposit = SubSectorTransactions.objects.filter(trash=False) city_deposit = city_operator_deposit.aggregate(total=Sum('amount'))['total'] or 0 city_total_remain_wage_amount = city_total_wage - city_deposit 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_CELL header_list = [ 'تعداد فارم', 'تعداد کل جوجه ریزی', 'حجم کل جوجه ریزی', 'حجم کل کشتارشده داخل استان', 'وزن کل کشتار شده داخل استان', 'وزن لاشه کشتار شده داخل استان', 'وزن کل لاشه توزیع داخل استان', 'وزن کل لاشه توزیع خارج استان', 'حجم کل فروش به خارج استان', 'وزن کل فروش به خارج از استان', 'حجم کل کشتار شده', 'درصد کشتار شده نسبت به جوجه ریزی', 'تعرفه زنده خارج از استان(اتحادیه)', 'تعرفه کشتار و توزیع داخل استان(اتحادیه)', 'تعرفه کشتار و توزیع خارج ازاستان(اتحادیه)', 'کل تعرفه سهم اتحادیه استان', 'تعرفه سهم زیر بخش ها', 'واریزی اتحادیه به زیر بخش ها', 'مانده تعرفه', ] create_header(worksheet, header_list, 4, 2, 21, 16.01) excel_description(worksheet, 'A1', 'گزارش جزئیات تعرفه سهم تعاونی ها', size=11, color='red', row2='C1') m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) city_operators = CityOperator.objects.filter(address__province=user.province, trash=False) if 'operators' in request.GET: serializer = CityOperatorForSubSectorTransactionsSerializer(city_operators, many=True, context={'request': request}) else: serializer = CityOperatorForSubSectorSerializer(city_operators, many=True, context={'request': request}) for data in serializer.data: list1 = [ m, data['unit_name'], data['user']['city'], data['user']['fullname'], data['user']['mobile'], data['wage_info']['poultries'], data['wage_info']['hatchings'], data['wage_info']['hatchings_quantity'], data['wage_info']['total_province_kill_requests_quantity'], data['wage_info']['total_province_kill_requests_weight'], data['wage_info']['total_province_carcasses_weight'], data['wage_info']['total_pure_internal_province_carcasses_weight'], data['wage_info']['total_pure_external_province_carcasses_weight'], data['wage_info']['out_province_poultry_request_quantity'], data['wage_info']['out_province_poultry_request_weight'], data['wage_info']['total_killed_quantity'], data['wage_info']['hatching_killing_percent'], data['wage_info']['out_province_poultry_request_amount'], data['wage_info']['total_pure_internal_province_carcasses_amount'], data['wage_info']['total_pure_external_province_carcasses_amount'], data['wage_info']['total_wage_amount'], data['wage_info']['city_deposit'], data['wage_info']['total_remain_wage_amount'], ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 value_header_list = [ len(poultries), len(hatchings), hatching_quantity, total_province_live_quantity, total_province_live_weight, total_province_carcasses_weight, internal_total_pure_province_carcasses_weight, external_total_pure_province_carcasses_weight, out_province_poultry_request_quantity, out_province_poultry_request_weight, out_province_poultry_request_quantity + total_province_live_quantity, hatching_killing_percent, union_free_sell_carcasses_wage, union_province_kill_request_wage, union_out_province_poultry_request_amount, union_total_wage, city_total_wage, city_deposit, city_total_remain_wage_amount, ] create_value(worksheet, value_header_list, 3, 4) poultries = sum(item['wage_info'].get('poultries', 0) for item in serializer.data) hatchings = sum(item['wage_info'].get('hatchings', 0) for item in serializer.data) hatchings_quantity = sum(item['wage_info'].get('hatchings_quantity', 0) for item in serializer.data) total_province_kill_requests_quantity = sum( item['wage_info'].get('total_province_kill_requests_quantity', 0) for item in serializer.data) total_province_kill_requests_weight = sum( item['wage_info'].get('total_province_kill_requests_weight', 0) for item in serializer.data) total_province_carcasses_weight = sum( item['wage_info'].get('total_province_carcasses_weight', 0) for item in serializer.data) total_pure_internal_province_carcasses_weight = sum( item['wage_info'].get('total_pure_internal_province_carcasses_weight', 0) for item in serializer.data) total_pure_external_province_carcasses_weight = sum( item['wage_info'].get('total_pure_external_province_carcasses_weight', 0) for item in serializer.data) out_province_poultry_request_quantity = sum( item['wage_info'].get('out_province_poultry_request_quantity', 0) for item in serializer.data) out_province_poultry_request_weight = sum( item['wage_info'].get('out_province_poultry_request_weight', 0) for item in serializer.data) total_killed_quantity = sum(item['wage_info'].get('total_killed_quantity', 0) for item in serializer.data) hatching_killing_percent = sum(item['wage_info'].get('hatching_killing_percent', 0) for item in serializer.data) out_province_poultry_request_amount = sum( item['wage_info'].get('out_province_poultry_request_amount', 0) for item in serializer.data) total_pure_internal_province_carcasses_amount = sum( item['wage_info'].get('total_pure_internal_province_carcasses_amount', 0) for item in serializer.data) total_pure_external_province_carcasses_amount = sum( item['wage_info'].get('total_pure_external_province_carcasses_amount', 0) for item in serializer.data) total_wage_amount = sum(item['wage_info'].get('total_wage_amount', 0) for item in serializer.data) city_deposit = sum(item['wage_info'].get('city_deposit', 0) for item in serializer.data) total_remain_wage_amount = sum(item['wage_info'].get('total_remain_wage_amount', 0) for item in serializer.data) list2 = [ 'مجموع==>', '', '', '', '', poultries, hatchings, hatchings_quantity, total_province_kill_requests_quantity, total_province_kill_requests_weight, total_province_carcasses_weight, total_pure_internal_province_carcasses_weight, total_pure_external_province_carcasses_weight, out_province_poultry_request_quantity, out_province_poultry_request_weight, total_killed_quantity, hatching_killing_percent, out_province_poultry_request_amount, total_pure_internal_province_carcasses_amount, total_pure_external_province_carcasses_amount, total_wage_amount, city_deposit, total_remain_wage_amount, ] create_value(worksheet, list2, l + 1, 1, color='green') 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 city_operator_for_sub_sector_excel(request): output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) sheet_name = 'اطلاعات کلی' worksheet = workbook.create_sheet(sheet_name) user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) city_operators = CityOperator.objects.filter(address__province=user.province, trash=False) if sheet_name == 'اطلاعات کلی': worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') header_list = [ 'تعرفه زنده خارج از استان', 'تعرفه کشتار و توزیع داخل استان', 'تعرفه کشتار و توزیع خارج استان', 'مجموع تعرفه', 'واریزی اتحادیه', 'مانده تعرفه', ] create_header(worksheet, header_list, 4, 2, height=25, width=25, border_style='thin', color='C00000') total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_sell_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id') province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user__in=kill_houses, trash=False, archive_wage=False, return_to_province=False, state__in=('pending', 'accepted'), first_car_allocated_quantity=0).order_by('id') kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q( Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False, trash=False, calculate_status=True ) total_province_live_weight = province_kill_requests.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 total_province_live_quantity = province_kill_requests.aggregate(total=Sum('total_killed_quantity'))[ 'total'] or 0 total_province_live_weight += kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 total_province_live_quantity += kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0 total_province_carcasses_weight = total_province_live_weight * 0.75 total_pure_province_carcasses_weight = total_province_carcasses_weight - get_difference_carcasses_weight( kill_houses) internal_total_pure_province_carcasses_weight = ( total_pure_province_carcasses_weight / total_province_carcasses_weight) * total_province_carcasses_weight external_total_pure_province_carcasses_weight = total_province_carcasses_weight - internal_total_pure_province_carcasses_weight total_pure_province_carcasses_price = internal_total_pure_province_carcasses_weight * province_live_wage_amount total_out_selling_province_carcasses_price = external_total_pure_province_carcasses_weight * free_sell_carcesses_weight_amount poultries = Poultry.objects.filter(trash=False, city_operator__isnull=False).order_by('id') hatchings = PoultryHatching.objects.filter(poultry__in=poultries, killed_quantity__gt=0, trash=False).order_by( 'poultry') hatching_quantity = hatchings.aggregate(total=Sum('quantity'))[ 'total'] or 0 poultry_requests = PoultryRequest.objects.filter(trash=False, state_process__in=('pending', 'accepted'), province_state__in=('pending', 'accepted'), out=True, out_province_request_cancel=False, temporary_trash=False, has_wage=True, wage_pay=True, temporary_deleted=False, hatching__in=hatchings) out_province_poultry_request_quantity = poultry_requests.aggregate(total=Sum('quantity'))[ 'total'] or 0 out_province_poultry_request_weight = poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 union_out_province_poultry_request_amount = poultry_requests.aggregate(total=Sum('union_share'))[ 'total'] or 0 percentages_wage_type = PercentageOfWageType.objects.filter(trash=False) union_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='union').first().percent / 100 union_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='union').first().percent / 100 union_province_kill_request_wage = total_pure_province_carcasses_price * union_province_kill_request_percent union_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * union_free_sell_carcasses_percent city_percent_province_kill_request = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='province-kill-request').first().percent / 100 city_percent_out_poultry_request = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='poultry-sell-out-province').first().percent / 100 city_percent_out_sell_carcasses = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='carcasse-sell').first().percent / 100 union_total_wage = union_province_kill_request_wage + union_out_province_poultry_request_amount + union_free_sell_carcasses_wage hatching_killing_percent = (( out_province_poultry_request_quantity + total_province_live_quantity) / hatching_quantity) * 100 city_province_kill_request_wage = union_province_kill_request_wage * city_percent_province_kill_request city_out_province_poultry_request = union_out_province_poultry_request_amount * city_percent_out_poultry_request city_out_province_sell_carcasses = union_free_sell_carcasses_wage * city_percent_out_sell_carcasses city_total_wage = city_province_kill_request_wage + city_out_province_poultry_request + city_out_province_sell_carcasses city_operator_deposit = SubSectorTransactions.objects.filter(trash=False) city_deposit = city_operator_deposit.aggregate(total=Sum('amount'))['total'] or 0 city_total_remain_wage_amount = city_total_wage - city_deposit value_header_list = [ city_out_province_poultry_request, city_province_kill_request_wage, city_out_province_sell_carcasses, city_total_wage, city_deposit, city_total_remain_wage_amount, ] create_value(worksheet, value_header_list, 3, 4, border_style='thin') excel_options = [ 'ردیف', 'تعاونی', 'شهر', 'کاربر', 'موبایل کاربر', 'تعرفه زنده خارج از استان', 'تعرفه کشتار و توزیع داخل استان', 'تعرفه کشتار و توزیع خارج از استان', 'مجموع تعرفه', ' تعداد دفعات واریز', 'مجموع واریزی اتحادیه', 'مانده تعرفه', ] # excel_description(worksheet, 'A1', 'گزارش جزئیات تعرفه سهم تعاونی ها', size=11, color='red', row2='C1') m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 if 'operators' in request.GET: serializer = CityOperatorForSubSectorTransactionsSerializer(city_operators, many=True, context={'request': request}) else: serializer = CityOperatorForSubSectorSerializer(city_operators, many=True, context={'request': request}) # todo:مقادیر باید درست شه for data in serializer.data: list1 = [ m, data['unit_name'], data['user']['city'], data['user']['fullname'], data['user']['mobile'], data['wage_info']['out_province_poultry_request_amount'], data['wage_info']['total_pure_internal_province_carcasses_amount'], data['wage_info']['total_pure_external_province_carcasses_weight'], data['wage_info']['total_wage_amount'], data['wage_info']['number_of_city_deposit'], data['wage_info']['city_deposit'], data['wage_info']['total_remain_wage_amount'], ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 for city_operator in city_operators: if SubSectorTransactions.objects.filter(trash=False, city_operator=city_operator).exists(): sheet_name = city_operator.unit_name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') role_type = request.GET['type'] excel_options = [ 'ردیف', 'تعاونی', 'شهر', 'کاربر', 'موبایل کاربر', 'تاریخ واریز', 'شماره حساب مبدا', 'شماره حساب مقصد', 'نوع تراکنش', 'مبلغ تراکنش', ] create_header_freez(worksheet, excel_options, 1, 6, 7, height=22, width=20.01) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) excel_description(worksheet, 'A3', f'واریزی های {city_operator.unit_name} از تاریخ{from_date_1} تا {from_date_2}', color='red', row2='C3') if role_type == 'city': operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, city_operator__isnull=False, trash=False, city_operator=city_operator).order_by( '-date') elif role_type == 'vet': operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, vet__isnull=False, trash=False).order_by('-date') else: operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, city_guild__isnull=False, trash=False, city_operator=city_operator).order_by( '-date') else: excel_description(worksheet, 'A4', f'{city_operator.unit_name}', color='red', row2='B4') if role_type == 'city': operator_transactions = SubSectorTransactions.objects.filter(city_operator__isnull=False, trash=False, city_operator=city_operator).order_by( '-date') elif role_type == 'vet': operator_transactions = SubSectorTransactions.objects.filter(vet__isnull=False, trash=False).order_by( '-date') else: operator_transactions = SubSectorTransactions.objects.filter(city_guild__isnull=False, trash=False).order_by('-date') l = 7 m = 1 for operator_transaction in operator_transactions: if operator_transaction.type == 'online': type = "آنلاین" elif operator_transaction.type == 'bank': type = "توسط بانک" else: type = 'دستی' list1 = [ m, operator_transaction.city_operator.unit_name, operator_transaction.city_operator.user.city.name, operator_transaction.city_operator.user.fullname, operator_transaction.city_operator.user.mobile, str(shamsi_date(operator_transaction.date)), operator_transaction.from_account, operator_transaction.to_account, type, operator_transaction.amount, ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 amount = operator_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 header_list1 = [ 'تعداد تراکنش ها', 'مبلغ تراکنش ها', ] create_header(worksheet, header_list1, 5, 3, border_style='thin', color='C4D79B', height=25) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', amount, ] create_value(worksheet, list2, l + 1, 1, border_style='thin', color='yellow') list3 = [ len(operator_transactions), amount, ] create_value(worksheet, list3, 4, 5, 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 vet_for_sub_sector_excel(request): output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) sheet_list = [ 'اطلاعات کلی', 'واریزی ها' ] for sheet_name in sheet_list: worksheet = workbook.create_sheet(sheet_name) if sheet_name == 'اطلاعات کلی': worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') header_list = [ 'تعرفه زنده خارج از استان', 'تعرفه کشتار و توزیع داخل استان', 'تعرفه فروش به خارج استان', 'مجموع تعرفه', 'واریزی اتحادیه', 'مانده تعرفه', ] create_header(worksheet, header_list, 4, 2, height=25, width=25, border_style='thin', color='C00000') total_quantity = 0 total_weight = 0 total_wage = 0 total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_sell_carcasses_wage_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount out_poultry_request_wage_amount = total_wage_type.filter(en_name='poultry-sell-out-province', trash=False).first().amount kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id') if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None poultry_requests = PoultryRequest.objects.filter(trash=False, state_process__in=('pending', 'accepted'), province_state__in=('pending', 'accepted'), out=True, out_province_request_cancel=False, temporary_trash=False, wage_pay=True, has_wage=True, temporary_deleted=False, vet_farm__isnull=False, quarantine_code__isnull=False, send_date__date__gte=date1, send_date__date__lte=date2) kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q( Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False, province_request__poultry_request__vet_farm__isnull=False, clearance_code__isnull=False, trash=False, calculate_status=True, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2 ) vet_deposit = SubSectorTransactions.objects.filter(trash=False, vet__isnull=False, date__date__gte=date1, date__date__lte=date2) else: poultry_requests = PoultryRequest.objects.filter(trash=False, state_process__in=('pending', 'accepted'), province_state__in=('pending', 'accepted'), out=True, out_province_request_cancel=False, temporary_trash=False, wage_pay=True, has_wage=True, temporary_deleted=False, vet_farm__isnull=False, quarantine_code__isnull=False) kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q( Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False, province_request__poultry_request__vet_farm__isnull=False, clearance_code__isnull=False, trash=False, calculate_status=True ) vet_deposit = SubSectorTransactions.objects.filter(trash=False, vet__isnull=False) percentages_wage_type = PercentageOfWageType.objects.filter(trash=False) other_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='other').first().percent / 100 other_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='other').first().percent / 100 other_out_poultry_request_percent = percentages_wage_type.filter( wage_type__en_name='poultry-sell-out-province', share_type__en_name='other').first().percent / 100 other_province_kill_request_amount = province_live_wage_amount * other_province_kill_request_percent other_free_sell_carcasses_amount = free_sell_carcasses_wage_amount * other_free_sell_carcasses_percent other_out_poultry_request_amount = out_poultry_request_wage_amount * other_out_poultry_request_percent out_province_poultry_request_quantity = poultry_requests.aggregate(total=Sum('quantity'))[ 'total'] or 0 out_province_poultry_request_weight = \ poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 province_live_weight = kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 province_live_quantity = kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))[ 'total'] or 0 total_quantity += province_live_quantity + out_province_poultry_request_quantity total_weight += province_live_weight + out_province_poultry_request_weight province_carcasses_weight = province_live_weight * 0.75 internal_pure_province_carcasses_weight = province_carcasses_weight * get_difference_carcasses_percent() external_pure_province_carcasses_weight = province_carcasses_weight - internal_pure_province_carcasses_weight total_pure_internal_province_carcasses_amount = internal_pure_province_carcasses_weight * other_province_kill_request_amount total_pure_external_province_carcasses_amount = external_pure_province_carcasses_weight * other_free_sell_carcasses_amount out_province_poultry_request_amount = out_province_poultry_request_weight * other_out_poultry_request_amount vet_deposit_amount = vet_deposit.aggregate(total=Sum('amount'))['total'] or 0 total_wage += total_pure_internal_province_carcasses_amount + total_pure_external_province_carcasses_amount + out_province_poultry_request_amount total_remain_wage = total_wage - vet_deposit_amount value_header_list = [ total_pure_internal_province_carcasses_amount, total_pure_external_province_carcasses_amount, out_province_poultry_request_amount, total_wage, vet_deposit_amount, total_remain_wage, ] create_value(worksheet, value_header_list, 3, 4, border_style='thin') excel_options = [ 'ردیف', 'کاربر', 'موبایل کاربر', 'شهر', 'حجم کشتار (دارای کد قرنطینه)', 'وزن کشتار (دارای کد قرنطینه)', 'تعرفه کشتار و توزیع داخل استان (ریال)', 'تعرفه کشتار و توزیع خارج استان (ریال)', 'تعرفه فروش به خارج استان (ریال)', 'مجموع تعرفه (ریال)', 'تعداد دفعات واریز', 'مجموع واریزی اتحادیه(ریال)', 'مانده تعرفه(ریال)', ] # excel_description(worksheet, 'A1', 'گزارش جزئیات تعرفه سهم تعاونی ها', size=11, color='red', row2='C1') m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 vet = Vet.objects.filter(pk__in=VetFarm.objects.all().values_list('vet', flat=True), trash=False).order_by( 'id') serializer = VetForSubSectorSerializerForExcel(vet, many=True, context={'request': request}) for data in serializer.data: list1 = [ m, data['user']['fullname'], data['user']['mobile'], data['user']['city'], data['wage_info']['total_quantity'], data['wage_info']['total_weight'], data['wage_info']['total_pure_internal_province_carcasses_amount'], data['wage_info']['total_pure_external_province_carcasses_amount'], data['wage_info']['out_province_poultry_request_amount'], data['wage_info']['total_wage'], data['wage_info']['number_of_deposit'], data['wage_info']['vet_deposit_amount'], data['wage_info']['total_remain_wage'], ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 else: worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') role_type = request.GET['type'] excel_options = [ 'ردیف', 'کاربر', 'موبایل کاربر', 'شهر', 'تاریخ واریز', 'شماره حساب مبدا', 'شماره حساب مقصد', 'نوع تراکنش', 'مبلغ تراکنش', ] create_header_freez(worksheet, excel_options, 1, 6, 7, height=22, width=20.01) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) excel_description(worksheet, 'A3', f'واریزی ها از تاریخ{from_date_1} تا {from_date_2}', color='red', row2='C3') if role_type == 'city': operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, city_operator__isnull=False, trash=False, ).order_by( '-date') elif role_type == 'vet': operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, vet__isnull=False, trash=False).order_by('-date') else: operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, city_guild__isnull=False, trash=False, ).order_by( '-date') else: excel_description(worksheet, 'A4', f'واریزی های سهم دامپزشک', color='red', row2='B4') if role_type == 'city': operator_transactions = SubSectorTransactions.objects.filter(city_operator__isnull=False, trash=False, ).order_by( '-date') elif role_type == 'vet': operator_transactions = SubSectorTransactions.objects.filter(vet__isnull=False, trash=False).order_by( '-date') else: operator_transactions = SubSectorTransactions.objects.filter(city_guild__isnull=False, trash=False).order_by('-date') l = 7 m = 1 for operator_transaction in operator_transactions: if operator_transaction.type == 'online': type = "آنلاین" elif operator_transaction.type == 'bank': type = "توسط بانک" else: type = 'دستی' list1 = [ m, operator_transaction.vet.user.fullname, operator_transaction.vet.user.mobile, operator_transaction.vet.user.city.name, str(shamsi_date(operator_transaction.date)), operator_transaction.from_account, operator_transaction.to_account, type, operator_transaction.amount, ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 amount = operator_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 header_list1 = [ 'تعداد تراکنش ها', 'مبلغ تراکنش ها', ] create_header(worksheet, header_list1, 5, 3, border_style='thin', color='C4D79B', height=25) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', amount, ] create_value(worksheet, list2, l + 1, 1, border_style='thin', color='yellow') list3 = [ len(operator_transactions), amount, ] create_value(worksheet, list3, 4, 5, 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 guild_for_sub_sector_excel(request): date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) sheet_list = [ 'اطلاعات کلی', 'واریزی ها' ] for sheet_name in sheet_list: worksheet = workbook.create_sheet(sheet_name) if sheet_name == 'اطلاعات کلی': worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') header_list = [ 'کل وزن دریافتی', 'کل وزن فروش رفته', 'تعرفه فروش به خارج استان', 'مجموع تعرفه', 'واریزی اتحادیه', 'مانده تعرفه', ] create_header(worksheet, header_list, 4, 2, height=25, width=25, border_style='thin', color='C00000') total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount percentages_wage_type = PercentageOfWageType.objects.filter(trash=False) other_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='other').first().percent / 100 if date1: allocations = StewardAllocation.objects.filter(trash=False, to_guilds__isnull=False, calculate_status=True, temporary_trash=False, temporary_deleted=False, receiver_state='accepted', date__date__gte=date1, date__date__lte=date2) transactions = PosMachineTransactions.objects.filter(paid=True, trash=False, date__date__gte=date1, date__date__lte=date2) sub_transactions = SubSectorTransactions.objects.filter(trash=False, city_guild__isnull=False, date__date__gte=date1, date__date__lte=date2) else: allocations = StewardAllocation.objects.filter(trash=False, to_guilds__isnull=False, calculate_status=True, temporary_trash=False, temporary_deleted=False, receiver_state='accepted') transactions = PosMachineTransactions.objects.filter(paid=True, trash=False) sub_transactions = SubSectorTransactions.objects.filter(trash=False, city_guild__isnull=False) allocations_weight = allocations.aggregate(total=Sum('real_weight_of_carcasses'))[ 'total'] or 0 transactions_weight = transactions.aggregate(total=Sum('weight'))[ 'total'] or 0 transactions_weight = transactions_weight / 1000 if transactions_weight > 0 else 0 total_wage = transactions_weight * (province_live_wage_amount * other_province_kill_request_percent) sub_transactions_amount = sub_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 remain_wage = total_wage - sub_transactions_amount value_header_list = [ allocations_weight, transactions_weight, total_wage, sub_transactions_amount, remain_wage ] create_value(worksheet, value_header_list, 3, 4, border_style='thin') excel_options = [ 'ردیف', 'کاربر', 'موبایل کاربر', 'شهر', 'کل وزن دریافتی', 'کل وزن فروش رفته', 'مجموع تعرفه (ریال)', 'مجموع واریزی اتحادیه(ریال)', 'مانده تعرفه(ریال)', ] # excel_description(worksheet, 'A1', 'گزارش جزئیات تعرفه سهم تعاونی ها', size=11, color='red', row2='C1') m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 city_guilds = CityGuild.objects.filter(trash=False) serializer = CityGuildForSubSectorSerializerForExcel(city_guilds, many=True, context={'request': request}) for data in serializer.data: list1 = [ m, data['user']['fullname'], data['user']['mobile'], data['user']['city'], data['wage_info']['buy_weight'], data['wage_info']['sell_weight'], data['wage_info']['total_wage'], data['wage_info']['guild_deposit'], data['wage_info']['remain_wage'], ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 else: worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') role_type = request.GET['type'] excel_options = [ 'ردیف', 'کاربر', 'موبایل کاربر', 'شهر', 'تاریخ واریز', 'شماره حساب مبدا', 'شماره حساب مقصد', 'نوع تراکنش', 'مبلغ تراکنش', ] create_header_freez(worksheet, excel_options, 1, 6, 7, height=22, width=20.01) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date1 = reversed(to_date.split("-")) separate = "-" from_date_2 = separate.join(reversed_date1) excel_description(worksheet, 'A3', f'واریزی ها از تاریخ{from_date_1} تا {from_date_2}', color='red', row2='C3') if role_type == 'city': operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, city_operator__isnull=False, trash=False, ).order_by( '-date') elif role_type == 'vet': operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, vet__isnull=False, trash=False).order_by('-date') else: operator_transactions = SubSectorTransactions.objects.filter(date__date__gte=date1, date__date__lte=date2, city_guild__isnull=False, trash=False, ).order_by( '-date') else: excel_description(worksheet, 'A4', f'واریزی های سهم صنف', color='red', row2='B4') if role_type == 'city': operator_transactions = SubSectorTransactions.objects.filter(city_operator__isnull=False, trash=False, ).order_by( '-date') elif role_type == 'vet': operator_transactions = SubSectorTransactions.objects.filter(vet__isnull=False, trash=False).order_by( '-date') else: operator_transactions = SubSectorTransactions.objects.filter(city_guild__isnull=False, trash=False).order_by('-date') l = 7 m = 1 for operator_transaction in operator_transactions: if operator_transaction.type == 'online': type = "آنلاین" elif operator_transaction.type == 'bank': type = "توسط بانک" else: type = 'دستی' list1 = [ m, operator_transaction.city_guild.user.fullname, operator_transaction.city_guild.user.mobile, operator_transaction.city_guild.user.city.name, str(shamsi_date(operator_transaction.date)), operator_transaction.from_account, operator_transaction.to_account, type, operator_transaction.amount, ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 amount = operator_transactions.aggregate(total=Sum('amount'))[ 'total'] or 0 header_list1 = [ 'تعداد تراکنش ها', 'مبلغ تراکنش ها', ] create_header(worksheet, header_list1, 5, 3, border_style='thin', color='C4D79B', height=25) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', amount, ] create_value(worksheet, list2, l + 1, 1, border_style='thin', color='yellow') list3 = [ len(operator_transactions), amount, ] create_value(worksheet, list3, 4, 5, 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 all_guilds_transaction_excel(request): output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) filterset_class = GuildsForPostationFilterSet date1 = request.GET.get('date1') date2 = request.GET.get('date2') if date1 and date2: date1 = datetime.datetime.strptime(date1, '%Y-%m-%d').date() date2 = datetime.datetime.strptime(date2, '%Y-%m-%d').date() guilds = Guilds.objects.filter( Q( id__in=PosMachineTransactions.objects.filter( trash=False, date__date__gte=date1, date__date__lte=date2, pos__guild__isnull=False, paid=True ).values_list('pos__guild__id', flat=True) ) | Q( id__in=StewardAllocation.objects.filter( date__date__gte=date1, date__date__lte=date2, to_guilds__isnull=False, to_cold_house__isnull=True, temporary_trash=False, trash=False, calculate_status=True ).values_list('to_guilds__id', flat=True) ) ).annotate( transaction_count=Count( 'guild_pos__roles_products_pos_transactions', filter=Q( guild_pos__roles_products_pos_transactions__trash=False, guild_pos__roles_products_pos_transactions__paid=True, guild_pos__roles_products_pos_transactions__date__date__gte=date1, guild_pos__roles_products_pos_transactions__date__date__lte=date2 ), distinct=True ) ).order_by('-transaction_count') else: guilds = Guilds.objects.filter( Q( id__in=PosMachineTransactions.objects.filter( trash=False, paid=True, pos__guild__isnull=False ).values_list('pos__guild__id', flat=True) ) | Q( id__in=StewardAllocation.objects.filter( to_guilds__isnull=False, to_cold_house__isnull=True, temporary_trash=False, trash=False, calculate_status=True ).values_list('to_guilds__id', flat=True) ) ).annotate( transaction_count=Count( 'guild_pos__roles_products_pos_transactions', filter=Q( guild_pos__roles_products_pos_transactions__trash=False, guild_pos__roles_products_pos_transactions__paid=True ), distinct=True ) ).order_by('-transaction_count') value = request.GET.get('value') search = request.GET.get('search') if value and search == 'filter': if value != 'undefined' and value.strip(): guilds = guilds.filter( build_query(filterset_class.Meta.fields, value) ) serializer = GuildsPosMachineForTransactionsNewSerializer(guilds, many=True, context={'request': request}) excel_options = [ 'ردیف', 'نام واحد صنفی', 'موبایل', 'شهر', 'کل ورودی به انبار(کیلوگرم)', 'کل فروش(کیلوگرم)', 'مانده انبار(کیلوگرم)', 'تعداد تراکنش ها', 'مبلغ کل تراکنش ها', ] cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) excel_description(worksheet, 'B3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='D3') header_list2 = [ 'کل ورودی به انبار(کیلوگرم)', 'کل فروش(کیلوگرم)', 'مانده انبار(کیلوگرم)', 'تعداد تراکنش ها', 'مبلغ کل تراکنش ها', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'مدیریت انبار صنوف', size=11, color='red', row2='D1') l = 5 m = 1 datas = serializer.data datas = sorted(datas, key=lambda x: x['transaction']['total_carcasses_weight'], reverse=True) for data in datas: l += 1 list1 = [ m, data['guilds_name'], data['user']['mobile'], data['user']['city']['name'], data['transaction']['total_carcasses_weight'], str(data['transaction']['real_allocated_weight']), data['transaction']['total_remain_weight'], data['transaction']['len_transaction'], data['transaction']['total_price'], ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) len_transaction = sum(item['transaction'].get('len_transaction', 0) for item in serializer.data) total_price = sum(item['transaction'].get('total_price', 0) for item in serializer.data) total_carcasses_weight = sum(item['transaction'].get('total_carcasses_weight', 0) for item in serializer.data) real_allocated_weight = sum(item['transaction'].get('real_allocated_weight', 0) for item in serializer.data) total_remain_weight = sum(item['transaction'].get('total_remain_weight', 0) for item in serializer.data) list2 = [ 'مجموع==>', '', '', '', total_carcasses_weight, real_allocated_weight, total_remain_weight, len_transaction, total_price, ] create_value(worksheet, list2, l + 3, 1, color='green') value_header_list2 = [ total_carcasses_weight, real_allocated_weight, total_remain_weight, len_transaction, total_price, ] create_value(worksheet, value_header_list2, 3, 5) 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 detail_guilds_transaction_excel(request): output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) guild = Guilds.objects.get(key=request.GET['key']) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() transactions = PosMachineTransactions.objects.filter(trash=False, date__date__gte=date1, date__date__lte=date2, pos__guild=guild, paid=True).order_by('-date') else: transactions = PosMachineTransactions.objects.filter(trash=False, pos__guild=guild, paid=True).order_by('-date') serializer = PosMachineTransactionsForInspectionSerializer(transactions, many=True) excel_options = [ 'ردیف', 'وضعیت تراکنش', 'تاریخ تراکنش', 'محصول', 'قیمت واحد', 'وزن (گرم)', 'مبلغ(ریال)', 'از سرویس', ] cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) excel_description(worksheet, 'B3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='D3') header_list2 = [ 'تعداد تراکنش ها', 'وزن کل(گرم)', 'مبلغ کل تراکنش ها(ریال)', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) if guild: name = guild.guilds_name else: name = '' excel_description(worksheet, 'A1', f'تراکنش های صنف {name}', size=11, color='red', row2='D1') l = 5 m = 1 for data in serializer.data: l += 1 paid = 'موفق' if data['paid'] == True else 'ناموفق' posProvider = 'سامان کیش' if data['posProvider'] == "SEP" else '-' date = '-' if data['date']: try: date = datetime.datetime.strptime(str(data['date']), '%Y-%m-%dT%H:%M:%S.%f') except ValueError: date = datetime.datetime.strptime(str(data['date']), '%Y-%m-%dT%H:%M:%S') date = shamsi_date(date, in_value=True) list1 = [ m, paid, str(date), (data.get('product') or {}).get('name') or '-', data.get('price') or 0, data.get('weight') or 0, data.get('current_price') or 0, posProvider, ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) pos = PosMachineTransactions.objects.filter(trash=False, pos__guild=guild, paid=True) total_price = pos.aggregate(total=Sum('price'))[ 'total'] or 0 weight = sum(item['weight'] for item in serializer.data) value_header_list2 = [ len(pos), weight, total_price, ] create_value(worksheet, value_header_list2, 3, 5) len_transaction = sum(item['price'] for item in serializer.data) total_carcasses_weight = sum(item['current_price'] for item in serializer.data) list2 = [ 'مجموع==>', '', '', '', len_transaction, weight, total_carcasses_weight, '' ] create_value(worksheet, list2, l + 3, 1, color='green') 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 class GetExcel(APIView): throttle_classes = [AnonRateThrottle, UserRateThrottle] def get(self, request): excel_name = request.GET.get('name') return Response(f'https://{base_url_for_sms_report}backend.rasadyaar.ir/{excel_name}/?{request.query_params}') def management_hatching_excel(request): output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) poultry_hatching = PoultryHatching.objects.filter(state__in=('pending', 'complete'), archive=False, allow_hatching='pending', trash=False).order_by('-chicken_age').select_related( 'poultry') excel_options = [ 'ردیف', 'شهرستان', 'نام واحد', 'نام مالک', 'تاریخ جوجه ریزی', 'تعداد جوجه ریزی', 'سن', 'نود درصد جوجه ریزی', 'مانده در سالن', ] cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) excel_description(worksheet, 'B3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='D3') header_list2 = [ 'تعداد کل جوجه ریزی', 'تعداد قطعه بین 42تا 50روزگی', 'تعداد قطعه بین 51تا 54روزگی', 'تعداد قطعه بین 55تا 60روزگی', 'تعداد قطعه بالای 60روزگی', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 9, 10, 20) # excel_description(worksheet, 'A1', f'تراکنش های صنف {name}', size=11, color='red', # row2='D1') l = 8 m = 1 for data in poultry_hatching: l += 1 age = data.chicken_age if age > 60: color = RED_CELL elif 60 > age > 54: color = LIGHT_GREEN_CELL elif 54 > age > 49: color = GREEN_CELL elif 49 > age > 47: color = VERY_LIGHT_GREEN_CELL else: color = None list1 = [ m, data.poultry.address.city.name, data.poultry.unit_name, data.poultry.user.fullname, convert_to_shamsi(date=data.date), data.quantity, data.chicken_age, int(data.quantity * 0.9), data.left_over ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, m=m, item_num=6, item_color=color, border_style='thin') quantity = poultry_hatching.aggregate(total=Sum('quantity'))[ 'total'] or 0 beetwen_43_50 = poultry_hatching.filter(chicken_age__range=(43, 50)).aggregate(total=Sum('quantity'))[ 'total'] or 0 beetwen_51_54 = poultry_hatching.filter(chicken_age__range=(51, 54)).aggregate(total=Sum('quantity'))[ 'total'] or 0 beetwen_55_60 = poultry_hatching.filter(chicken_age__range=(55, 60)).aggregate(total=Sum('quantity'))[ 'total'] or 0 gt_60 = poultry_hatching.filter(chicken_age__gt=60).aggregate(total=Sum('quantity'))[ 'total'] or 0 value_header_list2 = [ quantity, beetwen_43_50, beetwen_51_54, beetwen_55_60, gt_60 ] create_value(worksheet, value_header_list2, 3, 5) # # len_transaction = sum(item['price'] for item in serializer.data) # total_carcasses_weight = sum(item['current_price'] for item in serializer.data) # left_over = poultry_hatching.aggregate(total=Sum('left_over'))[ 'total'] or 0 list2 = [ 'مجموع==>', '', '', '', '', quantity, '', int(quantity * 0.9), left_over ] create_value(worksheet, list2, l + 3, 1, color='green') 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 user_without_role_excel(request): users = SystemUserProfile.objects.filter(role__isnull=True, trash=False).only('fullname', 'create_date', 'fullname').order_by('-create_date') 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_CELL m = 1 create_header_freez(worksheet, excel_options, 1, 1, 2, 20, width=30) l = 2 for user in users: list1 = [ m, user.fullname, user.mobile, convert_to_shamsi(date=user.create_date), ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=20) m += 1 l += 1 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 sub_section_of_cooperative_share_detail_with_date_excel(request): date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_sell_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id') province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user__in=kill_houses, trash=False, archive_wage=False, return_to_province=False, state__in=('pending', 'accepted'), first_car_allocated_quantity=0, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2).order_by( 'id') kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q( Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False, trash=False, calculate_status=True, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2 ) total_province_live_weight = province_kill_requests.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 total_province_live_quantity = province_kill_requests.aggregate(total=Sum('total_killed_quantity'))[ 'total'] or 0 total_province_live_weight += kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 total_province_live_quantity += kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0 total_province_carcasses_weight = total_province_live_weight * 0.75 total_pure_province_carcasses_weight = total_province_carcasses_weight - get_difference_carcasses_weight( kill_houses) # return Response(total_pure_province_carcasses_weight) internal_total_pure_province_carcasses_weight = (( total_pure_province_carcasses_weight / total_province_carcasses_weight) if total_province_carcasses_weight > 0 else 0) * total_province_carcasses_weight external_total_pure_province_carcasses_weight = total_province_carcasses_weight - internal_total_pure_province_carcasses_weight total_pure_province_carcasses_price = internal_total_pure_province_carcasses_weight * province_live_wage_amount total_out_selling_province_carcasses_price = external_total_pure_province_carcasses_weight * free_sell_carcesses_weight_amount poultries = Poultry.objects.filter(trash=False, city_operator__isnull=False).order_by('id') hatchings = PoultryHatching.objects.filter(poultry__in=poultries, killed_quantity__gt=0, trash=False).order_by( 'poultry') hatching_quantity = hatchings.aggregate(total=Sum('quantity'))[ 'total'] or 0 poultry_requests = PoultryRequest.objects.filter(trash=False, state_process__in=('pending', 'accepted'), province_state__in=('pending', 'accepted'), out=True, out_province_request_cancel=False, temporary_trash=False, has_wage=True, wage_pay=True, temporary_deleted=False, hatching__in=hatchings, send_date__date__gte=date1, send_date__date__lte=date2) out_province_poultry_request_quantity = poultry_requests.aggregate(total=Sum('quantity'))[ 'total'] or 0 out_province_poultry_request_weight = poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 union_out_province_poultry_request_amount = poultry_requests.aggregate(total=Sum('union_share'))[ 'total'] or 0 percentages_wage_type = PercentageOfWageType.objects.filter(trash=False) union_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='union').first().percent / 100 union_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='union').first().percent / 100 union_province_kill_request_wage = total_pure_province_carcasses_price * union_province_kill_request_percent union_free_sell_carcasses_wage = total_out_selling_province_carcasses_price * union_free_sell_carcasses_percent city_percent_province_kill_request = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='province-kill-request').first().percent / 100 city_percent_out_poultry_request = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='poultry-sell-out-province').first().percent / 100 city_percent_out_sell_carcasses = SubSectorPercentageOfWageType.objects.filter( percentage_of_wage_type__wage_type__en_name='carcasse-sell').first().percent / 100 union_total_wage = union_province_kill_request_wage + union_out_province_poultry_request_amount + union_free_sell_carcasses_wage hatching_killing_percent = (( out_province_poultry_request_quantity + total_province_live_quantity) / hatching_quantity) * 100 city_province_kill_request_wage = union_province_kill_request_wage * city_percent_province_kill_request city_out_province_poultry_request = union_out_province_poultry_request_amount * city_percent_out_poultry_request city_out_province_sell_carcasses = union_free_sell_carcasses_wage * city_percent_out_sell_carcasses city_total_wage = city_province_kill_request_wage + city_out_province_poultry_request + city_out_province_sell_carcasses city_operator_deposit = SubSectorTransactions.objects.filter(trash=False, date__date__gte=date1, date__date__lte=date2) city_deposit = city_operator_deposit.aggregate(total=Sum('amount'))['total'] or 0 city_total_remain_wage_amount = city_total_wage - city_deposit 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_CELL header_list = [ 'تعداد فارم', 'تعداد کل جوجه ریزی', 'حجم کل جوجه ریزی', 'حجم کل کشتارشده داخل استان', 'وزن کل کشتار شده داخل استان', 'وزن لاشه کشتار شده داخل استان', 'وزن کل لاشه توزیع داخل استان', 'وزن کل لاشه توزیع خارج استان', 'حجم کل فروش به خارج استان', 'وزن کل فروش به خارج از استان', 'حجم کل کشتار شده', 'درصد کشتار شده نسبت به جوجه ریزی', 'تعرفه زنده خارج از استان(اتحادیه)', 'تعرفه کشتار و توزیع داخل استان(اتحادیه)', 'تعرفه کشتار و توزیع خارج ازاستان(اتحادیه)', 'کل تعرفه سهم اتحادیه استان', 'تعرفه سهم زیر بخش ها', 'واریزی اتحادیه به زیر بخش ها', 'مانده تعرفه', ] create_header(worksheet, header_list, 4, 2, 21, 16.01) from_date_1 = shamsi_date(date1) from_date_2 = shamsi_date(date2) excel_description(worksheet, 'A1', f'گزارش جزئیات تعرفه سهم تعاونی ها ار تاریخ {from_date_1} تا تاریخ {from_date_2}', size=11, color='red', row2='E1') m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 # user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) city_operators = CityOperator.objects.filter(trash=False) if 'operators' in request.GET: serializer = CityOperatorForSubSectorTransactionsSerializer(city_operators, many=True, context={'request': request}) else: serializer = CityOperatorForSubSectorSerializerForExcel(city_operators, many=True, context={'request': request}) if serializer.data: for data in serializer.data: list1 = [ m, data['unit_name'], data['user']['city'], data['user']['fullname'], data['user']['mobile'], data['wage_info']['poultries'], data['wage_info']['hatchings'], data['wage_info']['hatchings_quantity'], data['wage_info']['total_province_kill_requests_quantity'], data['wage_info']['total_province_kill_requests_weight'], data['wage_info']['total_province_carcasses_weight'], data['wage_info']['total_pure_internal_province_carcasses_weight'], data['wage_info']['total_pure_external_province_carcasses_weight'], data['wage_info']['out_province_poultry_request_quantity'], data['wage_info']['out_province_poultry_request_weight'], data['wage_info']['total_killed_quantity'], data['wage_info']['hatching_killing_percent'], data['wage_info']['out_province_poultry_request_amount'], data['wage_info']['total_pure_internal_province_carcasses_amount'], data['wage_info']['total_pure_external_province_carcasses_amount'], data['wage_info']['total_wage_amount'], data['wage_info']['city_deposit'], data['wage_info']['total_remain_wage_amount'], ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 value_header_list = [ len(poultries), len(hatchings), hatching_quantity, total_province_live_quantity, total_province_live_weight, total_province_carcasses_weight, internal_total_pure_province_carcasses_weight, external_total_pure_province_carcasses_weight, out_province_poultry_request_quantity, out_province_poultry_request_weight, out_province_poultry_request_quantity + total_province_live_quantity, hatching_killing_percent, union_free_sell_carcasses_wage, union_province_kill_request_wage, union_out_province_poultry_request_amount, union_total_wage, city_total_wage, city_deposit, city_total_remain_wage_amount, ] create_value(worksheet, value_header_list, 3, 4) poultries = sum(item['wage_info'].get('poultries', 0) for item in serializer.data) hatchings = sum(item['wage_info'].get('hatchings', 0) for item in serializer.data) hatchings_quantity = sum(item['wage_info'].get('hatchings_quantity', 0) for item in serializer.data) total_province_kill_requests_quantity = sum( item['wage_info'].get('total_province_kill_requests_quantity', 0) for item in serializer.data) total_province_kill_requests_weight = sum( item['wage_info'].get('total_province_kill_requests_weight', 0) for item in serializer.data) total_province_carcasses_weight = sum( item['wage_info'].get('total_province_carcasses_weight', 0) for item in serializer.data) total_pure_internal_province_carcasses_weight = sum( item['wage_info'].get('total_pure_internal_province_carcasses_weight', 0) for item in serializer.data) total_pure_external_province_carcasses_weight = sum( item['wage_info'].get('total_pure_external_province_carcasses_weight', 0) for item in serializer.data) out_province_poultry_request_quantity = sum( item['wage_info'].get('out_province_poultry_request_quantity', 0) for item in serializer.data) out_province_poultry_request_weight = sum( item['wage_info'].get('out_province_poultry_request_weight', 0) for item in serializer.data) total_killed_quantity = sum(item['wage_info'].get('total_killed_quantity', 0) for item in serializer.data) hatching_killing_percent = sum(item['wage_info'].get('hatching_killing_percent', 0) for item in serializer.data) out_province_poultry_request_amount = sum( item['wage_info'].get('out_province_poultry_request_amount', 0) for item in serializer.data) total_pure_internal_province_carcasses_amount = sum( item['wage_info'].get('total_pure_internal_province_carcasses_amount', 0) for item in serializer.data) total_pure_external_province_carcasses_amount = sum( item['wage_info'].get('total_pure_external_province_carcasses_amount', 0) for item in serializer.data) total_wage_amount = sum(item['wage_info'].get('total_wage_amount', 0) for item in serializer.data) city_deposit = sum(item['wage_info'].get('city_deposit', 0) for item in serializer.data) total_remain_wage_amount = sum(item['wage_info'].get('total_remain_wage_amount', 0) for item in serializer.data) list2 = [ 'مجموع==>', '', '', '', '', poultries, hatchings, hatchings_quantity, total_province_kill_requests_quantity, total_province_kill_requests_weight, total_province_carcasses_weight, total_pure_internal_province_carcasses_weight, total_pure_external_province_carcasses_weight, out_province_poultry_request_quantity, out_province_poultry_request_weight, total_killed_quantity, hatching_killing_percent, out_province_poultry_request_amount, total_pure_internal_province_carcasses_amount, total_pure_external_province_carcasses_amount, total_wage_amount, city_deposit, total_remain_wage_amount, ] create_value(worksheet, list2, l + 1, 1, color='green') 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 vet_for_sub_sector_with_date_excel(request): date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else None date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date2' in request.GET else None vet = Vet.objects.filter(pk__in=VetFarm.objects.all().values_list('vet', flat=True), trash=False).order_by('id') serializer = VetForSubSectorSerializer(vet, many=True, context={'request': request}) 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_CELL header_list = [ 'تعرفه کشتار و توزیع داخل استان', 'تعرفه کشتار و توزیع خارج استان', 'تعرفه فروش به خارج استان', 'مجموع تعرفه', 'واریزی اتحادیه', 'مانده تعرفه' ] create_header(worksheet, header_list, 4, 2, 21, 16.01) from_date_1 = shamsi_date(date1) from_date_2 = shamsi_date(date2) excel_description(worksheet, 'A1', f'گزارش جزئیات تعرفه سهم تعاونی ها ار تاریخ {from_date_1} تا تاریخ {from_date_2}', size=11, color='red', row2='E1') m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 # user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) if serializer.data: for data in serializer.data: list1 = [ m, data['user']['fullname'], # کاربر data['user']['city'], # شهر data['wage_info']['province_live_quantity'], # حجم کشتار (دارای کد قرنطینه) 🔺 data['wage_info']['province_live_weight'], # وزن کشتار (دارای کد قرنطینه) data['wage_info']['total_pure_internal_province_carcasses_amount'], # تعرفه کشتارو توزیع داخل استان (ریال) data['wage_info']['total_pure_external_province_carcasses_amount'], # تعرفه کشتارو توزیع خارج از استان (ریال) data['wage_info']['out_province_poultry_request_amount'], # تعرفه فروش به خارج از استان (ریال) data['wage_info']['total_wage'], # مجموع تعرفه (ریال) data['wage_info']['number_of_deposit'], # تعداد دفعات واریز data['wage_info']['vet_deposit_amount'], # مجموع واریزی اتحادیه (ریال) data['wage_info']['total_remain_wage'] # مانده تعرفه (ریال) ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 total_quantity = 0 total_weight = 0 total_wage = 0 total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_sell_carcasses_wage_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount out_poultry_request_wage_amount = total_wage_type.filter(en_name='poultry-sell-out-province', trash=False).first().amount percentages_wage_type = PercentageOfWageType.objects.filter(trash=False) other_province_kill_request_percent = percentages_wage_type.filter( wage_type__en_name='province-kill-request', share_type__en_name='other').first().percent / 100 other_free_sell_carcasses_percent = percentages_wage_type.filter(wage_type__en_name='carcasse-sell', share_type__en_name='other').first().percent / 100 other_out_poultry_request_percent = percentages_wage_type.filter(wage_type__en_name='poultry-sell-out-province', share_type__en_name='other').first().percent / 100 other_province_kill_request_amount = province_live_wage_amount * other_province_kill_request_percent other_free_sell_carcasses_amount = free_sell_carcasses_wage_amount * other_free_sell_carcasses_percent other_out_poultry_request_amount = out_poultry_request_wage_amount * other_out_poultry_request_percent kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id') poultry_requests = PoultryRequest.objects.filter(trash=False, state_process__in=('pending', 'accepted'), province_state__in=('pending', 'accepted'), out=True, out_province_request_cancel=False, temporary_trash=False, wage_pay=True, has_wage=True, temporary_deleted=False, vet_farm__isnull=False, ) # quarantine_code__isnull=False) out_province_poultry_request_quantity = poultry_requests.aggregate(total=Sum('quantity'))[ 'total'] or 0 out_province_poultry_request_weight = poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 kill_house_requests = KillHouseRequest.objects.filter( Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q( Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False, province_request__poultry_request__vet_farm__isnull=False, # clearance_code__isnull=False, clearance_code__isnull=False, trash=False, calculate_status=True ) province_live_weight = kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0 province_live_quantity = kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))[ 'total'] or 0 difference_requests = BarDifferenceRequest.objects.filter(kill_house__in=kill_houses, trash=False, state='accepted') province_live_weight += \ difference_requests.aggregate(total=Sum('weight'))['total'] or 0 total_quantity += province_live_quantity + out_province_poultry_request_quantity total_weight += province_live_weight + out_province_poultry_request_weight province_carcasses_weight = province_live_weight * 0.75 internal_pure_province_carcasses_weight = province_carcasses_weight * get_difference_carcasses_percent() external_pure_province_carcasses_weight = province_carcasses_weight - internal_pure_province_carcasses_weight total_pure_internal_province_carcasses_amount = internal_pure_province_carcasses_weight * other_province_kill_request_amount total_pure_external_province_carcasses_amount = external_pure_province_carcasses_weight * other_free_sell_carcasses_amount out_province_poultry_request_amount = out_province_poultry_request_weight * other_out_poultry_request_amount vet_deposit = SubSectorTransactions.objects.filter(trash=False, vet__isnull=False) vet_deposit_amount = vet_deposit.aggregate(total=Sum('amount'))['total'] or 0 total_wage += total_pure_internal_province_carcasses_amount + total_pure_external_province_carcasses_amount + out_province_poultry_request_amount total_remain_wage = total_wage - vet_deposit_amount value_header_list = [ total_pure_internal_province_carcasses_amount, # تعرفه کشتار و توزیع داخل استان total_pure_external_province_carcasses_amount, # تعرفه کشتار و توزیع خارج استان out_province_poultry_request_amount, # تعرفه فروش به خارج استان total_wage, # مجموع تعرفه vet_deposit_amount, # واریزی اتحادیه total_remain_wage # مانده تعرفه ] create_value(worksheet, value_header_list, 3, 4) # list2 = [ # 'مجموع==>', # '', # '', # '', # '', # poultries, # hatchings, # hatchings_quantity, # total_province_kill_requests_quantity, # total_province_kill_requests_weight, # total_province_carcasses_weight, # total_pure_internal_province_carcasses_weight, # total_pure_external_province_carcasses_weight, # out_province_poultry_request_quantity, # out_province_poultry_request_weight, # total_killed_quantity, # hatching_killing_percent, # out_province_poultry_request_amount, # total_pure_internal_province_carcasses_amount, # total_pure_external_province_carcasses_amount, # total_wage_amount, # city_deposit, # total_remain_wage_amount, # # ] # create_value(worksheet, list2, l + 1, 1, color='green') 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 dashboard_monitoring_bar_and_killing_excel(request): now = datetime.datetime.now().date() date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else now date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date1' in request.GET else now output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment_CELL sheet_names2 = ['اطلاعات کشتار', 'اطلاعات بار', 'تخصیصات بدون بار', 'خرید زنده خارج از استان', 'خرید لاشه خارج استان', 'فروش زنده به خارج استان', 'اطلاعات کشتارگاه ها'] for name in sheet_names2: sheet_name = name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) if sheet_name == 'اطلاعات کشتار': filtered_province_kill_reqs = PoultryRequest.objects.filter(state_process__in=('pending', 'accepted'), province_state__in=('pending', 'accepted'), final_state='pending', trash=False, out=False, send_date__date__gte=date1, send_date__date__lte=date2).select_related( 'poultry', 'poultry__user').order_by( '-send_date') excel_options = [ 'ردیف', 'کد سفارش', 'تاریخ ثبت درخواست', 'تاریخ کشتار', 'فروش', 'نام و نام خانوادگی مرغدار', 'نام فارم', 'موبایل', 'کشتارگاه های پیشنهادی', 'آدرس', 'سن مرغ', 'تعداد درخواست کشتار', 'مانده در سالن', 'میانگین وزنی هر قطعه(کیلوگرم)', 'وزن کل درخواست(کیلوگرم)', 'قیمت هرکیلو مرغ زنده(ریال)', 'تایید شده', ] worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') header_list = [ 'تعداد درخواست', 'مجموع تعداد قطعه', 'وزن تقریبی کل درخواست', 'مجموع مانده در سالن', 'میانگین سنی', ] create_header(worksheet, header_list, 4, 2, height=17) excel_description(worksheet, 'A2', 'درخواست کشتار مرغداران', size=11, row2='B2') from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', color='red', row2='C3') m = 1 create_header_freez(worksheet, excel_options, 1, 5, 6, height=23, width=21.01) l = 4 all_quantity = 0 all_wight = 0 all_left_over = 0 all_age = [] if filtered_province_kill_reqs: for filtered_poultry_kill_request in filtered_province_kill_reqs: all_quantity += filtered_poultry_kill_request.quantity all_wight += int( filtered_poultry_kill_request.quantity * filtered_poultry_kill_request.Index_weight) l += 1 date_of_create = jdatetime.date.fromgregorian( day=filtered_poultry_kill_request.create_date.day, month=filtered_poultry_kill_request.create_date.month, year=filtered_poultry_kill_request.create_date.year ) date_of_kill = jdatetime.date.fromgregorian( day=filtered_poultry_kill_request.send_date.day, month=filtered_poultry_kill_request.send_date.month, year=filtered_poultry_kill_request.send_date.year ) state = 'تایید شده' if filtered_poultry_kill_request.state == 'pending': state = 'در انتظار تایید' kill_house = '-' if filtered_poultry_kill_request.kill_house_list is not None: for name in filtered_poultry_kill_request.kill_house_list: kill_house += name + '/' age = ( filtered_poultry_kill_request.send_date.date() - filtered_poultry_kill_request.hatching.date.date()).days + 1 if age not in all_age: all_age.append(age) sale_type = 'دولتی' if filtered_poultry_kill_request.free_sale_in_province == False else 'آزاد' all_left_over += filtered_poultry_kill_request.hatching.left_over list1 = [ m, str(filtered_poultry_kill_request.order_code), str(date_of_create), str(date_of_kill), sale_type, filtered_poultry_kill_request.poultry.user.fullname, filtered_poultry_kill_request.poultry.unit_name, filtered_poultry_kill_request.poultry.user.mobile, kill_house, filtered_poultry_kill_request.poultry.address.city.name, str(age), filtered_poultry_kill_request.quantity, filtered_poultry_kill_request.hatching.left_over, filtered_poultry_kill_request.Index_weight, int(filtered_poultry_kill_request.quantity * filtered_poultry_kill_request.Index_weight), filtered_poultry_kill_request.amount, state ] m += 1 create_value(worksheet, list1, l + 1, 1) all_age1 = sorted(all_age) value_header_list = [ len(filtered_province_kill_reqs), all_quantity, all_wight, all_left_over, int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-', ] create_value(worksheet, value_header_list, 3, 4) elif sheet_name == 'اطلاعات بار': filtered_kill_request = KillHouseRequest.objects.filter( trash=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2).order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'province_kill_request__province_request__poultry_request__out', 'province_kill_request__kill_house_price', 'price', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'bar_document_status__title').values( 'province_request__poultry_request__poultry__user__fullname', 'province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_confirmation', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'province_kill_request__province_request__poultry_request__out', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'province_kill_request__kill_house_price', 'price', 'bar_document_status__title' ) filtered_kill_reqs = filtered_kill_request poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values( 'province_request__poultry_request')) .only('quantity', 'Index_weight')).annotate( total_quantity=Sum('quantity'), total_weight=Sum(F('quantity') * F('Index_weight')) ) excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'نوع کشتار', 'کدسفارش مرغدار', 'نام و نام خانوادگی مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'نام فارم', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', 'قیمت پیشنهادی کشتارگاه(ریال)', 'قیمت تعاونی(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', 'کشتارکن اختصاصی', 'تلفن کشتارکن اختصاصی', ' محل کشتار ', 'قیمت کشتارگاه(ریال)', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'وضعیت', 'وضعیت سند', 'وضعیت ورود انبار', 'تعداد لاشه', 'وزن لاشه', 'درصد افت در لحظه', 'درصد افت ورود به انبار', 'کشور مقصد', 'اختلاف مجوز', ] from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) header_list = [ 'تعداد بارهای ایجاد شده', 'تعداد بارهای دارای کشتارکن اختصاصی', 'مجموع حجم بارها', 'مجموع وزن بارها', 'میانگین وزن ', 'کمترین سن', 'بیشترین سن', 'میانگین سنی', 'تعداد بارهای دارای کد قرنطینه', 'حجم بارهای دارای کد قرنطینه', 'تعداد بار احراز شده از قرنطینه', 'مجموع تعداد قطعه احراز شده از قرنطینه', 'تعداد بار فاقد قرنطینه', 'حجم بار فاقد قرنطینه', ' تعداد بارهایی که در قرنطینه و رصدیار اختلاف دارند', 'تعداد تخلیه شده دامپزشک', 'مجموع تعداد تخلیه شده دامپزشک', 'مجموع وزن تخلیه شده دامپزشک', 'تعداد بارهای تکمیل شده', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'تعداد بار های وارد شده در انبار', 'مجموع تعداد لاشه', 'مجموع وزن لاشه', 'میانگین درصد افت لاشه ورود به انبار', ] header_list2 = [ 'تعداد درخواست مرغداران', ' مجموع تعداد قطعه درخواست مرغداران', ' مجموع وزن درخواست مرغداران', ] header_list3 = [ 'درصد بارهای دارای کد قرنطینه', 'درصد تعداد بارهای احراز شده از قرنطینه', 'درصد تعداد بارهای تکمیل شده کشتارگاه', 'درصد وزن نهایی در کشتارگاه نسبت به وزن کل', 'درصد بارهای فاقد کد قرنطینه', 'درصد بارهای اختلاف دار در قرنطینه و رصدیار', 'درصد تعداد بارهای ورودی به انبار', 'درصد وزن لاشه ها در انبار نسبت به وزن کل', 'درصد وزن لاشه در انبار نسبت به وزن نهایی در کشتارگاه', ] create_header(worksheet, header_list, 9, 2, height=21.8) create_header(worksheet, header_list2, 6, 2, height=21.8, color='green') create_header(worksheet, header_list3, 6, 5, height=43, color='orange', text_color='0D0D0D') create_header_freez(worksheet, excel_options, 1, 8, 9, height=21, len_with=True) excel_description(worksheet, 'B1', 'گزارش بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی', color='red', row2='D1') kill_keys = [kill.get('key') for kill in filtered_kill_reqs] vet_checks = VetCheckRequest.objects.filter( trash=False, kill_house_request__key__in=kill_keys ).only('create_date', 'kill_house_request__key').values( 'create_date', 'kill_house_request__key') assignments = KillHouseAssignmentInformation.objects.filter( kill_house_request__key__in=kill_keys, trash=False ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key') vet_check_mapping = {vc['kill_house_request__key']: vc['create_date'] for vc in vet_checks} assignment_mapping = { assignment.kill_house_request.key: ( int(assignment.net_weight), assignment.real_quantity, assignment.create_date) for assignment in assignments } if filtered_kill_reqs.exists(): name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name'] worksheet['B2'] = f'استان {name}' excel_description(worksheet, 'B2', f'استان {name}', color='red', row2='D2') excel_description(worksheet, 'B3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='D3') l = 8 m = 1 all_age = [] all_real_quantity = 0 all_net_weighte = 0 all_weighte = 0 poultry_ids = [req.get('province_request__poultry_request__poultry') for req in filtered_kill_reqs] vet_farms = VetFarm.objects.filter(poultry__in=poultry_ids, trash=False).select_related('vet__user') vet_farm_mapping = { vet_farm.poultry_id: (vet_farm.vet.user.fullname, vet_farm.vet.user.mobile) for vet_farm in vet_farms } if filtered_kill_reqs: for kill in filtered_kill_reqs: age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if age not in all_age: all_age.append(age) if (kill['assignment_state_archive']) == 'True' or kill[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' l += 1 vet_farm_id = kill.get('province_request__poultry_request__poultry') vet_farm_name, vet_farm_mobile = vet_farm_mapping.get(vet_farm_id, ('-', '-')) kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'), trash=False).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() code = kill.get('clearance_code') if kill.get('clearance_code') else '-' if kill.get('quantity'): quantity = kill.get('quantity') else: quantity = '-' send_date = kill.get('province_request__poultry_request__send_date') date_of_poultry_request = convert_to_shamsi(year=send_date.year, month=send_date.month, day=send_date.day, ) killers = 'کشتارکن' name_killer_exclusive = '-' mobile_killer_exclusive = '-' if kill.get('killhouse_user__killer') == False: killers = 'کشتارگاه' if kill.get('killer') != None: name_killer_exclusive = kill['killer__name'] mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile']) key = kill.get('key') kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' net_weighte, real_quantity, vet_check_date = assignment_mapping.get(key, ('-', '-', None)) all_real_quantity += real_quantity if real_quantity != '-' else 0 all_net_weighte += net_weighte if net_weighte != '-' else 0 vet_check_date = vet_check_mapping.get(key, vet_check_date) date_of_inner_bar = convert_to_shamsi(datetime=vet_check_date) if vet_check_date else '-' if kill.get('kill_request__slaughter_house') is not None: kill_place = kill.get('kill_request__slaughter_house__name') else: kill_place = '-' vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-' vet_wight = int(kill['vet_accepted_real_weight']) if kill['vet_accepted_real_weight'] else '-' weight = int(kill.get('quantity') * kill.get( 'province_kill_request__province_request__poultry_request__Index_weight')) quarantine_quantity = '-' if kill['quarantine_quantity'] != None: quarantine_quantity = kill['quarantine_quantity'] else: if kill['quarantine_code_state'] == 'contradiction': quarantine_quantity = 'مغایرت کد رهگیری' elif kill['quarantine_code_state'] == 'noclearance': quarantine_quantity = 'فاقد کد رهگیری' elif kill['quarantine_code_state'] == 'notconfirmed': quarantine_quantity = 'عدم تایید راهداری' elif kill['quarantine_code_state'] == 'merge': quarantine_quantity = 'ادغام' export_country = '-' sale_type = 'دولتی' if kill[ 'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد' if kill['province_kill_request__province_request__poultry_request__out'] == True: type = 'خارج از استان' elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' elif kill['province_request__poultry_request__freezing'] == True: type = 'انجماد' elif kill['province_request__poultry_request__export'] == True: type = 'صادرات' export_country = kill['kill_request__export_country'] else: type = 'عادی' age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if kill['message'] is not None: state_delete = 'بار حذف شده' else: state_delete = 'فعال' all_weighte += weight ware_house_accepted_real_quantity = kill['ware_house_accepted_real_quantity'] ware_house_accepted_real_weight = kill['ware_house_accepted_real_weight'] weight_loss = round(kill['weight_loss'], 2) if kill['weight_loss'] > 0 else 0 if kill['ware_house_confirmation'] == True: state_ware_house_confirmation = 'ورود به انبار' else: state_ware_house_confirmation = '-' weight_loss1 = kill['accepted_real_weight'] - kill['ware_house_accepted_real_weight'] if kill[ 'ware_house_accepted_real_weight'] > 0 else 0 if weight_loss1 < 0: weight_loss1 = weight_loss1 * -1 total_weight_loss = (weight_loss1 / kill['accepted_real_weight']) * 100 if weight_loss1 != 0 else 0 list1 = [ m, str(kill.get('bar_code')), str(date_of_poultry_request), type, str(kill.get('province_request__poultry_request__order_code')), kill.get('province_request__poultry_request__poultry__user__fullname'), str(kill.get('province_request__poultry_request__poultry__user__mobile')), kill.get('province_request__poultry_request__poultry__user__city__name'), kill.get('province_request__poultry_request__poultry__unit_name'), sale_type, age, kill.get('province_request__poultry_request__amount') if kill.get( 'province_request__poultry_request__amount') else '-', kill.get('province_kill_request__kill_house_price') if kill.get( 'province_kill_request__kill_house_price') else '-', kill.get('price') if kill.get( 'price') else '-', kill.get('province_request__poultry_request__chicken_breed'), vet_farm_name, vet_farm_mobile, killers, kill.get('killhouse_user__name'), kill.get('killhouse_user__kill_house_operator__user__mobile'), kill.get('killhouse_user__system_address__city__name'), name_killer_exclusive, mobile_killer_exclusive, kill_place, kill.get('province_kill_request__kill_house_price'), kill_house_vet_name, kill_house_vet_mobile, kill.get('add_car__driver__driver_name'), kill.get('add_car__driver__driver_mobile'), kill.get('add_car__driver__type_car'), str(kill.get('traffic_code')), quantity, weight, code, quarantine_quantity, state, str(date_of_inner_bar), vet_quantity, vet_wight, real_quantity, net_weighte, kill['accepted_real_quantity'], int(kill['accepted_real_weight']), state_delete, kill['bar_document_status__title'] if kill['bar_document_status'] else '-', state_ware_house_confirmation, ware_house_accepted_real_quantity, int(ware_house_accepted_real_weight), f'%{round(total_weight_loss, 2)}', f'%{weight_loss}', export_country, kill['accepted_real_quantity'] - quarantine_quantity if kill[ 'quarantine_quantity'] != None else quarantine_quantity ] m += 1 create_value(worksheet, list1, l, 1, height=20, different_cell=40, different_value='بار حذف شده') killer_exclusive = len(filtered_kill_reqs.filter(killer__isnull=False)) all_state_ware_house_confirmation = len(filtered_kill_reqs.filter(ware_house_confirmation=True)) total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] or 0 total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0 aggregate_filtered_kill_reqs = filtered_kill_reqs.aggregate( total_accepted_real_quantity=Sum('accepted_real_quantity'), total_accepted_real_weight=Sum('accepted_real_weight'), total_quantity=Sum('quantity'), total_vet_accepted_real_quantity=Sum('vet_accepted_real_quantity'), total_vet_accepted_real_weight=Sum('vet_accepted_real_weight'), total_quarantine_quantity=Sum('quarantine_quantity'), total_ware_house_accepted_real_quantity=Sum('ware_house_accepted_real_quantity'), total_ware_house_accepted_real_weight=Sum('ware_house_accepted_real_weight'), total_weight_loss=Sum('weight_loss'), ) all_vet_state_accepted = len( filtered_kill_reqs.filter(vet_state='accepted')) bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True') accepted_real_quantity = aggregate_filtered_kill_reqs['total_accepted_real_quantity'] or 0 accepted_real_wight = aggregate_filtered_kill_reqs['total_accepted_real_weight'] or 0 all_kill_request_quantity = aggregate_filtered_kill_reqs['total_quantity'] or 0 all_quarantine_quantity = aggregate_filtered_kill_reqs['total_quarantine_quantity'] or 0 all_vet_accepted_real_quantity = aggregate_filtered_kill_reqs['total_vet_accepted_real_quantity'] or 0 all_vet_accepted_real_weight = aggregate_filtered_kill_reqs['total_vet_accepted_real_weight'] or 0 has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False)) all_ware_house_accepted_real_quantity = aggregate_filtered_kill_reqs[ 'total_ware_house_accepted_real_quantity'] or 0 all_ware_house_accepted_real_weight = aggregate_filtered_kill_reqs[ 'total_ware_house_accepted_real_weight'] or 0 all_weight_loss = aggregate_filtered_kill_reqs['total_weight_loss'] or 0 has_code1 = filtered_kill_reqs.filter(clearance_code__isnull=False).aggregate( total_quantity=Sum('quantity'), ) all_quarantine_quantity_has_code = has_code1['total_quantity'] or 0 hasnt_code1 = filtered_kill_reqs.filter(clearance_code__isnull=True) hasnt_code = hasnt_code1.aggregate( total_quantity=Sum('quantity') ) all_quarantine_quantity_hasnt_code = hasnt_code['total_quantity'] or 0 difference_bar = len(filtered_kill_reqs.filter( Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')))) all_weight_loss = round(int(all_weight_loss) / all_state_ware_house_confirmation, 2) if all_weight_loss > 0 else 0 all_age1 = sorted(all_age) has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False)) value_header_list = [ len(poultry_request), total_requests_quantity, int(total_requests_weight), len(filtered_kill_reqs), killer_exclusive, all_kill_request_quantity, int(all_weighte), round(all_weighte / all_kill_request_quantity, 1) if all_weighte > 0 and all_kill_request_quantity > 0 else 0, all_age1[0] if len(all_age1) > 0 else '-', all_age1[len(all_age1) - 1] if len(all_age1) > 0 else '-', int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-', has_code, all_quarantine_quantity_has_code, has_qarantine, all_quarantine_quantity, len(hasnt_code1), all_quarantine_quantity_hasnt_code, difference_bar, all_vet_state_accepted, all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), len(bar_complete), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, all_state_ware_house_confirmation, all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), f'%{all_weight_loss}' ] create_value(worksheet, value_header_list, 3, 6) value_header_list2 = [ f'%{round((has_code * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((has_qarantine * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((len(bar_complete) * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((int(all_net_weighte) * 100) / int(all_weighte), 2) if int(all_weighte) > 0 else 0}', f'%{round((len(hasnt_code1) * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((difference_bar * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((all_state_ware_house_confirmation * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((int(all_ware_house_accepted_real_weight) * 100) / int(all_weighte), 2) if int(all_weighte) > 0 else 0}', f'%{round((int(all_ware_house_accepted_real_weight) * 100) / int(all_net_weighte), 2) if int(all_net_weighte) > 0 else 0}' ] create_value(worksheet, value_header_list2, 6, 6) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_kill_request_quantity, int(all_weighte), '', all_quarantine_quantity if all_quarantine_quantity != None else 0, '', '', all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, '', '', '', all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), '', '', '', '', '', '', ] create_value(worksheet, list2, l + 3, 1, color='green') elif sheet_name == 'تخصیصات بدون بار': wage_type = WageType.objects.filter(en_name='province-kill-request').first() total_check_wage = wage_type.amount percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0, trash=False) for percentage_wage_type in percentages_wage_type: if percentage_wage_type.share_type.en_name == 'union': union_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name == 'company': company_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name == 'guilds': guilds_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name in ['city', 'wallet']: pass else: other_wage_percent = percentage_wage_type.percent / 100 total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_buying_live_weight_amount = total_wage_type.filter(en_name='live-buy', trash=False).first().amount free_buying_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-buy', trash=False).first().amount free_sell_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount worksheet['H3'] = 'در این قسمت تخصیصات فاقد بار نمایش داده میشود' merge_range1 = 'H3:K3' worksheet.merge_cells(merge_range1) worksheet['H3'].font = Font(color="C00000", bold=True) worksheet['H3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) province_kill_request = ProvinceKillRequest.objects.filter( state__in=('pending', 'accepted'), return_to_province=False, archive_wage=False, first_car_allocated_quantity=0, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, trash=False).order_by( 'kill_request__recive_date') if wage_counting_type == 'carcass': header_list = [ 'تعداد سفارشات', 'تعداد کل', 'وزن کل', 'وزن لاشه ملاک تعرفه', 'جمع کل تعرفه', ] else: header_list = [ 'تعداد سفارشات', 'تعداد کل', 'وزن کل', 'وزن ملاک تعرفه', 'جمع کل تعرفه', ] for col_num, option in enumerate(header_list, 3): cell = worksheet.cell(row=3, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[3].height = 20.8 if wage_counting_type == 'carcass': excel_options = [ 'ردیف', 'کد سفارش', 'مرغدار', 'تلفن مرغدار', 'شهر', 'تاریخ کشتار', 'محل کشتار', 'نژاد', 'تعداد(قطعه)', 'وزن(کیلوگرم)', 'میانگین وزنی(کیلوگرم)', 'وزن لاشه ملاک تعرفه ', 'تعرفه (ریال)', 'تعرفه تخصیص(ریال)', ] else: excel_options = [ 'ردیف', 'کد سفارش', 'مرغدار', 'تلفن مرغدار', 'شهر', 'تاریخ کشتار', 'محل کشتار', 'نژاد', 'تعداد(قطعه)', 'وزن(کیلوگرم)', 'میانگین وزنی(کیلوگرم)', 'وزن ملاک تعرفه ', 'تعرفه (ریال)', 'تعرفه تخصیص(ریال)', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str l = 6 m = 1 for province_kill in province_kill_request: kill_date_1 = shamsi_date(province_kill.province_request.poultry_request.send_date) if province_kill.kill_request.slaughter_house is not None: kill_place = province_kill.kill_request.slaughter_house.name else: kill_place = province_kill.kill_request.kill_house.name total_amount = province_kill.total_wage_amount if wage_counting_type == 'carcass': list1 = [ m, str(province_kill.province_request.poultry_request.order_code), province_kill.province_request.poultry_request.poultry.unit_name, province_kill.province_request.poultry_request.poultry.user.mobile, province_kill.province_request.poultry_request.poultry.address.city.name, str(kill_date_1), kill_place, province_kill.province_request.poultry_request.hatching.chicken_breed, province_kill.total_killed_quantity, province_kill.total_killed_weight, province_kill.province_request.poultry_request.Index_weight, province_kill.total_killed_weight * 0.75, province_live_wage_amount, (province_kill.total_killed_weight * 0.75) * province_live_wage_amount, ] else: list1 = [ m, str(province_kill.province_request.poultry_request.order_code), province_kill.province_request.poultry_request.poultry.unit_name, province_kill.province_request.poultry_request.poultry.user.mobile, province_kill.province_request.poultry_request.poultry.address.city.name, str(kill_date_1), kill_place, province_kill.province_request.poultry_request.hatching.chicken_breed, province_kill.total_killed_quantity, province_kill.total_killed_weight, province_kill.province_request.poultry_request.Index_weight, province_kill.total_killed_weight, province_live_wage_amount, (province_kill.total_killed_weight) * province_live_wage_amount, ] for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') l += 1 m += 1 total_weight = \ province_kill_request.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 total_killed_quantity = \ province_kill_request.aggregate(total=Sum('total_killed_quantity'))[ 'total'] or 0 total_wage_amount = \ province_kill_request.aggregate(total=Sum('total_wage_amount'))[ 'total'] or 0 if wage_counting_type == 'carcass': value_list = [ m - 1, total_killed_quantity, total_weight, total_weight * 0.75, (total_weight * 0.75) * province_live_wage_amount, ] else: value_list = [ m - 1, total_killed_quantity, total_weight, total_weight, (total_weight) * province_live_wage_amount, ] for item in range(len(value_list)): cell = worksheet.cell(row=4, column=item + 3, value=value_list[item]) value = value_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') if wage_counting_type == 'carcass': list2 = [ 'مجموع==>', '', '', '', '', '', '', '', total_killed_quantity, total_weight, '', total_weight * 0.75, province_live_wage_amount, (total_weight * 0.75) * province_live_wage_amount, ] else: list2 = [ 'مجموع==>', '', '', '', '', '', '', '', total_killed_quantity, total_weight, '', total_weight, province_live_wage_amount, (total_weight) * province_live_wage_amount, ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'خرید زنده خارج از استان': user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) type = 'live' if request.GET['role'] in ['KillHouse', 'KillHouseVet']: if request.GET['role'] == 'KillHouse': kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False) else: kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house', flat=True) kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False) kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house__in=kill_houses, date__date__gte=date1, date__date__lte=date2, buy_type=type, trash=False).order_by('-date') else: kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter( date__date__gte=date1, date__date__lte=date2, buy_type=type, trash=False).order_by('-date') excel_options = [ 'ردیف', 'کدسفارش', 'تاریخ خرید', 'ماهیت خریدار', 'خریدار', 'تلفن خریدار', 'فروشنده', 'تلفن فروشنده', 'نوع خرید', 'استان/شهر', 'دامپزشک فارم', 'تلفن دامپزشک فارم', 'وضعیت دامپزشک', 'ماشین', 'راننده', 'تلفن راننده', 'کدقرنطینه', 'تعداد قطعه زنده', 'وزن زنده (کیلوگرم)', 'تعداد لاشه', 'وزن لاشه (کیلوگرم)', 'حجم تایید شده', 'وزن تایید شده', 'تایید/رد کننده', 'تاریخ تایید/ رد', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) header_list2 = [ 'تعداد بارها', ' تعداد بار های درانتظار تایید', 'مجموع قطعه زنده در انتظار تایید', 'مجموع وزن زنده (کیلوگرم) درانتظار تایید', 'مجموع تعداد لاشه درانتظار تایید', 'مجموع وزن لاشه (کیلوگرم) درانتظار تایید', ' تعداد بار های رد شده', 'مجموع قطعه زنده رد شده', 'مجموع وزن زنده (کیلوگرم) رد شده', 'مجموع تعداد لاشه رد شده', 'مجموع وزن لاشه (کیلوگرم) رد شده', ' تعداد بار های تایید شده', 'مجموع قطعه زنده تایید شده', 'مجموع وزن زنده (کیلوگرم) تایید شده', 'مجموع تعداد لاشه تایید شده', 'مجموع وزن لاشه (کیلوگرم) تایید شده', 'حجم تایید شده دامپزشک', 'وزن تایید شده دامپزشک', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str type = 'زنده' if type == 'live' else 'لاشه' worksheet['B1'] = f'گزارش بار {type} خرید از استان' if kill_house_free_bar_info.exists(): name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if kill_house_free_bar_info: for kill in kill_house_free_bar_info: l += 1 if kill.kill_house_vet_state == 'accepted': state = 'تایید شده' elif kill.kill_house_vet_state == 'pending': state = 'درانتظار تایید' else: state = 'رد شده' if kill.buy_type == 'live': buy_type = 'زنده' else: buy_type = 'لاشه' date_of_buy = jdatetime.date.fromgregorian( day=kill.date.day, month=kill.date.month, year=kill.date.year ) if kill.date_of_accept_reject: date_of_reject_accepted = jdatetime.date.fromgregorian( day=kill.date_of_accept_reject.day, month=kill.date_of_accept_reject.month, year=kill.date_of_accept_reject.year ) else: date_of_reject_accepted = '-' if kill.exclusive_killer: killer_type = f'کشتارکن اختصاصی {kill.kill_house.name}' kill_house_name = kill.exclusive_killer.name kill_house_mobile = kill.exclusive_killer.kill_house_operator.user.mobile elif kill.kill_house.killer == True and kill.kill_house.type == 'public': killer_type = 'کشتارکن عمومی' kill_house_name = kill.kill_house.name kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile else: killer_type = 'کشتارگاه' kill_house_name = kill.kill_house.name kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile bar_code = str(kill.bar_code) if kill.bar_code else '-' list1 = [ m, bar_code, str(date_of_buy), killer_type, kill_house_name, kill_house_mobile, kill.poultry_name, kill.poultry_mobile, buy_type, f'{kill.province} / {kill.city}', kill.vet_farm_name, kill.vet_farm_mobile, state, kill.car, kill.driver_name, kill.driver_mobile, kill.bar_clearance_code, kill.quantity, kill.live_weight, kill.number_of_carcasses, kill.weight_of_carcasses, kill.kill_house_vet_quantity, kill.kill_house_vet_weight, kill.acceptor_rejector, str(date_of_reject_accepted) ] m += 1 create_value(worksheet, list1, l + 1, 1, height=20, width=30) bar_pending = kill_house_free_bar_info.filter(kill_house_vet_state='pending') bar_pending_quantity = bar_pending.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_pending_live_weight = bar_pending.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_pending_number_of_carcasses = bar_pending.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_pending_weight_of_carcasses = bar_pending.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected') bar_rejected_quantity = bar_rejected.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_rejected_live_weight = bar_rejected.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_rejected_number_of_carcasses = bar_rejected.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_rejected_weight_of_carcasses = bar_rejected.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted') bar_accepted_quantity = bar_accepted.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_accepted_live_weight = bar_accepted.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_accepted_number_of_carcasses = bar_accepted.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_accepted_weight_of_carcasses = bar_accepted.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_accepted_kill_house_vet_quantity = bar_accepted.aggregate( total_quantity=Sum('kill_house_vet_quantity')).get( 'total_quantity') or 0 bar_accepted_kill_house_vet_weight = bar_accepted.aggregate( total_quantity=Sum('kill_house_vet_weight')).get( 'total_quantity') or 0 bar_quantity = kill_house_free_bar_info.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_live_weight = kill_house_free_bar_info.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_number_of_carcasses = kill_house_free_bar_info.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_weight_of_carcasses = kill_house_free_bar_info.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_kill_house_vet_quantity = kill_house_free_bar_info.aggregate( total_quantity=Sum('kill_house_vet_quantity')).get( 'total_quantity') or 0 bar_kill_house_vet_weight = kill_house_free_bar_info.aggregate( total_quantity=Sum('kill_house_vet_weight')).get( 'total_quantity') or 0 value_header_list2 = [ m - 1, len(bar_pending), int(bar_pending_quantity), int(bar_pending_live_weight), int(bar_pending_number_of_carcasses), int(bar_pending_weight_of_carcasses), len(bar_rejected), int(bar_rejected_quantity), int(bar_rejected_live_weight), int(bar_rejected_number_of_carcasses), int(bar_rejected_weight_of_carcasses), len(bar_accepted), int(bar_accepted_quantity), int(bar_accepted_live_weight), int(bar_accepted_number_of_carcasses), int(bar_accepted_weight_of_carcasses), int(bar_accepted_kill_house_vet_quantity), int(bar_accepted_kill_house_vet_weight) ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', bar_quantity, bar_live_weight, int(bar_number_of_carcasses), int(bar_weight_of_carcasses), int(bar_kill_house_vet_quantity), bar_kill_house_vet_weight, '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'خرید لاشه خارج استان': user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) type = 'carcass' if request.GET['role'] in ['KillHouse', 'KillHouseVet']: if request.GET['role'] == 'KillHouse': kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False) else: kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house', flat=True) kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False) kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house__in=kill_houses, date__date__gte=date1, date__date__lte=date2, buy_type=type, trash=False).order_by('-date') else: kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter( date__date__gte=date1, date__date__lte=date2, buy_type=type, trash=False).order_by('-date') excel_options = [ 'ردیف', 'وضعیت دامپزشک', 'کشتارگاه', 'فروشنده', 'نوع خرید', 'استان/شهر', 'تاریخ خرید', 'دامپزشک فارم', 'تلفن دامپزشک فارم', 'ماشین', 'راننده', 'تلفن راننده', 'کدقرنطینه', 'تعداد قطعه زنده', 'وزن زنده (کیلوگرم)', 'تعداد لاشه', 'وزن لاشه (کیلوگرم)', 'حجم تایید شده', 'وزن تایید شده', 'تایید/رد کننده', 'تاریخ تایید/ رد', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) header_list2 = [ 'تعداد بارها', ' تعداد بار های درانتظار تایید', 'مجموع قطعه زنده در انتظار تایید', 'مجموع وزن زنده (کیلوگرم) درانتظار تایید', 'مجموع تعداد لاشه درانتظار تایید', 'مجموع وزن لاشه (کیلوگرم) درانتظار تایید', ' تعداد بار های رد شده', 'مجموع قطعه زنده رد شده', 'مجموع وزن زنده (کیلوگرم) رد شده', 'مجموع تعداد لاشه رد شده', 'مجموع وزن لاشه (کیلوگرم) رد شده', ' تعداد بار های تایید شده', 'مجموع قطعه زنده تایید شده', 'مجموع وزن زنده (کیلوگرم) تایید شده', 'مجموع تعداد لاشه تایید شده', 'مجموع وزن لاشه (کیلوگرم) تایید شده', 'حجم تایید شده دامپزشک', 'وزن تایید شده دامپزشک', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str type = 'زنده' if type == 'live' else 'لاشه' worksheet['B1'] = f'گزارش بار {type} خرید از استان' if kill_house_free_bar_info.exists(): name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if kill_house_free_bar_info: for kill in kill_house_free_bar_info: l += 1 if kill.kill_house_vet_state == 'accepted': state = 'تایید شده' elif kill.kill_house_vet_state == 'pending': state = 'درانتظار تایید' else: state = 'رد شده' if kill.buy_type == 'live': buy_type = 'زنده' else: buy_type = 'لاشه' date_of_buy = jdatetime.date.fromgregorian( day=kill.date.day, month=kill.date.month, year=kill.date.year ) if kill.date_of_accept_reject: date_of_reject_accepted = jdatetime.date.fromgregorian( day=kill.date_of_accept_reject.day, month=kill.date_of_accept_reject.month, year=kill.date_of_accept_reject.year ) else: date_of_reject_accepted = '-' list1 = [ m, state, kill.kill_house.name, kill.poultry_name, buy_type, f'{kill.province} / {kill.city}', str(date_of_buy), kill.vet_farm_name, kill.vet_farm_mobile, kill.car, kill.driver_name, kill.driver_mobile, kill.bar_clearance_code, kill.quantity, kill.live_weight, kill.number_of_carcasses, kill.weight_of_carcasses, kill.kill_house_vet_quantity, kill.kill_house_vet_weight, kill.acceptor_rejector, str(date_of_reject_accepted) ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] if isinstance(value, (int)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') bar_pending = kill_house_free_bar_info.filter(kill_house_vet_state='pending') bar_pending_quantity = bar_pending.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_pending_live_weight = bar_pending.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_pending_number_of_carcasses = bar_pending.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_pending_weight_of_carcasses = bar_pending.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected') bar_rejected_quantity = bar_rejected.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_rejected_live_weight = bar_rejected.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_rejected_number_of_carcasses = bar_rejected.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_rejected_weight_of_carcasses = bar_rejected.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted') bar_accepted_quantity = bar_accepted.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_accepted_live_weight = bar_accepted.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_accepted_number_of_carcasses = bar_accepted.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_accepted_weight_of_carcasses = bar_accepted.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_accepted_kill_house_vet_quantity = bar_accepted.aggregate( total_quantity=Sum('kill_house_vet_quantity')).get( 'total_quantity') or 0 bar_accepted_kill_house_vet_weight = bar_accepted.aggregate( total_quantity=Sum('kill_house_vet_weight')).get( 'total_quantity') or 0 bar_quantity = kill_house_free_bar_info.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity') or 0 bar_live_weight = kill_house_free_bar_info.aggregate( total_quantity=Sum('live_weight')).get( 'total_quantity') or 0 bar_number_of_carcasses = kill_house_free_bar_info.aggregate( total_quantity=Sum('number_of_carcasses')).get( 'total_quantity') or 0 bar_weight_of_carcasses = kill_house_free_bar_info.aggregate( total_quantity=Sum('weight_of_carcasses')).get( 'total_quantity') or 0 bar_kill_house_vet_quantity = kill_house_free_bar_info.aggregate( total_quantity=Sum('kill_house_vet_quantity')).get( 'total_quantity') or 0 bar_kill_house_vet_weight = kill_house_free_bar_info.aggregate( total_quantity=Sum('kill_house_vet_weight')).get( 'total_quantity') or 0 value_header_list2 = [ m - 1, len(bar_pending), int(bar_pending_quantity), int(bar_pending_live_weight), int(bar_pending_number_of_carcasses), int(bar_pending_weight_of_carcasses), len(bar_rejected), int(bar_rejected_quantity), int(bar_rejected_live_weight), int(bar_rejected_number_of_carcasses), int(bar_rejected_weight_of_carcasses), len(bar_accepted), int(bar_accepted_quantity), int(bar_accepted_live_weight), int(bar_accepted_number_of_carcasses), int(bar_accepted_weight_of_carcasses), int(bar_accepted_kill_house_vet_quantity), int(bar_accepted_kill_house_vet_weight) ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', bar_quantity, bar_live_weight, int(bar_number_of_carcasses), int(bar_weight_of_carcasses), int(bar_kill_house_vet_quantity), bar_kill_house_vet_weight, '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'فروش زنده به خارج استان': state = 'accepted' user = SystemUserProfile.objects.get(key=request.GET['key']) name_bar = '' if request.GET['role'] == 'VetFarm': vet_farms = VetFarm.objects.filter(vet__user=user, trash=False) poultries = Poultry.objects.filter( pk__in=vet_farms.values('poultry') ) if state == 'pending': poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), poultry__in=poultries, send_date__date__gte=date1, send_date__date__lte=date2, out_province_request_cancel=False, trash=False).order_by('-send_date') elif state == 'accepted': poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False), poultry__in=poultries, send_date__date__gte=date1, send_date__date__lte=date2, out_province_request_cancel=False, trash=False).order_by('-send_date') else: poultry_requests = PoultryRequest.objects.filter( Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True, wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False) | Q( state_process='pending', province_state='pending', final_state='pending', has_wage=False, wage_pay=False, out_province_request_cancel=True), poultry__in=poultries, send_date__date__gte=date1, send_date__date__lte=date2, trash=False).order_by('-send_date') elif request.GET['role'] == 'CityOperator': city_operator = CityOperator.objects.get(user=user) if state == 'pending': poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), poultry__city_operator=city_operator.unit_name, send_date__date__gte=date1, send_date__date__lte=date2, out=True, out_province_request_cancel=False, trash=False).order_by('-send_date') name_bar = 'جدید' elif state == 'accepted': poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False), poultry__city_operator=city_operator.unit_name, send_date__date__gte=date1, send_date__date__lte=date2, out=True, out_province_request_cancel=False, trash=False).order_by('-send_date') name_bar = 'تایید شده' else: poultry_requests = PoultryRequest.objects.filter( Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True, wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False) | Q( state_process='pending', province_state='pending', final_state='pending', has_wage=False, wage_pay=False, out_province_request_cancel=True), poultry__city_operator=city_operator.unit_name, send_date__date__gte=date1, send_date__date__lte=date2, out=True, trash=False).order_by('-send_date') name_bar = 'حذف/رد شده' elif request.GET['role'] in ['CityJahad', 'CityPoultry']: if state == 'pending': poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), poultry__address__city=user.city, send_date__date__gte=date1, send_date__date__lte=date2, out=True, out_province_request_cancel=False, trash=False).order_by('-send_date') name_bar = 'جدید' elif state == 'accepted': poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False), poultry__address__city=user.city, send_date__date__gte=date1, send_date__date__lte=date2, out=True, out_province_request_cancel=False, trash=False).order_by('-send_date') name_bar = 'تایید شده' else: name_bar = 'حذف/رد شده' poultry_requests = PoultryRequest.objects.filter( Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True, wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False) | Q( state_process='pending', province_state='pending', final_state='pending', has_wage=False, wage_pay=False, out_province_request_cancel=True), poultry__address__city=user.city, send_date__date__gte=date1, send_date__date__lte=date2, out=True, trash=False).order_by('-send_date') elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX']: if state == 'pending': poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), send_date__date__gte=date1, send_date__date__lte=date2, out=True, out_province_request_cancel=False, trash=False).order_by('-send_date') name_bar = 'جدید' elif state == 'accepted': poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=False, wage_pay=False), send_date__date__gte=date1, send_date__date__lte=date2, out=True, out_province_request_cancel=False, trash=False).order_by('-send_date') name_bar = 'تایید شده' else: poultry_requests = PoultryRequest.objects.filter( Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True, wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=False, wage_pay=False, out_province_request_cancel=False) | Q( state_process='pending', province_state='pending', final_state='pending', has_wage=False, wage_pay=False, out_province_request_cancel=True), send_date__date__gte=date1, send_date__date__lte=date2, out=True, trash=False).order_by('-send_date') name_bar = 'رد شده' else: poultry_requests = PoultryRequest.objects.filter( Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True, wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending', wage_pay=False), send_date__date__gte=date1, send_date__date__lte=date2, out_province_request_cancel=False, trash=False).order_by('-send_date') poultry_requests_accepted = poultry_requests.filter(province_state='accepted') excel_options = [ 'ردیف', 'وضعیت', 'پرداخت کننده', 'کدسفارش مرغدار', ' تاریخ ثبت درخواست', ' تاریخ کشتار', ' کشتار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', ' استان مرغدار', 'سن مرغ', ' نژاد', 'تعداد درخواست', 'میانگین وزنی', 'وزن درخواست', 'مانده در سالن', 'جوجه ریزی اولیه', ' ماهیت خریدار', 'خریدار', 'تلفن خریدار', ' شهر خریدار', 'استان خریدار', 'محل کشتار', 'کد یکتای کشتارگاه', 'شهر محل کشتار', 'نوع خودرو', 'پلاک', 'نام راننده', 'موبایل راننده', 'کد بهداشتی حمل و نقل', 'کد رهگیری سامانه قرنطینه', 'ثبت کننده کد قرنطینه', 'تاریخ ثبت کد قرنطینه', 'سازنده', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str header_list = [ 'تعداد بارهای تایید شده', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'کمترین سن مرغ', 'بیشترین سن مرغ', 'تعداد بارهای دارای کد قرنطینه', ] for col_num, option in enumerate(header_list, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 worksheet['B1'] = f'گزارش بارهای {name_bar} خارج از استان' if poultry_requests.exists(): name = poultry_requests.first().poultry.user.province.name worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 6 m = 1 all_weighte = 0 all_chicken_quantity = 0 all_age = [] all_quantity = poultry_requests_accepted.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_weighte = poultry_requests_accepted.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] has_code = 0 if poultry_requests: for poultry_request in poultry_requests: if ProvinceKillRequest.objects.filter( province_request__city_request_Poultry__poultry_request=poultry_request, state='accepted').exists(): age = (poultry_request.send_date - poultry_request.hatching.date).days + 1 else: age = (datetime.datetime.now() - poultry_request.hatching.date).days + 1 all_age.append(age) all_chicken_quantity += poultry_request.hatching.quantity create_date_of_poultry_request = jdatetime.date.fromgregorian( day=poultry_request.create_date.day, month=poultry_request.create_date.month, year=poultry_request.create_date.year ) date_of_kill_request = jdatetime.date.fromgregorian( day=poultry_request.send_date.day, month=poultry_request.send_date.month, year=poultry_request.send_date.year ) if poultry_request.quarantine_code_registrar is not None: date_code = poultry_request.quarantine_code_registrar['date'].split('-') date_of_create_code = jdatetime.date.fromgregorian( day=int(date_code[2]), month=int(date_code[1]), year=int(date_code[0]) ) full_name = poultry_request.quarantine_code_registrar['fullname'] mobile = poultry_request.quarantine_code_registrar['mobile'] else: date_of_create_code = '-' full_name = '-' mobile = '-' killing_place = '-' killing_place_city = '-' uniq_id = '-' if poultry_request.out_province_poultry_request_buyer: if poultry_request.out_province_poultry_request_buyer.type == 'killhouse': is_killer = 'کشتارگاه' uniq_id = poultry_request.out_province_poultry_request_buyer.kill_house_unique_id if poultry_request.out_province_poultry_request_buyer.kill_house_unique_id else '-' else: is_killer = 'کشتارکن' killing_place = poultry_request.killer_kill_house_unit_name \ if poultry_request.killer_kill_house_unit_name is not None \ else '-' killing_place_city = poultry_request.killer_kill_house_province \ + '(' + poultry_request.killer_kill_house_city \ + ')' if poultry_request.killer_kill_house_province \ and poultry_request.killer_kill_house_city is not None \ else '-' uniq_id = poultry_request.kill_house_unique_id if poultry_request.kill_house_unique_id else '-' else: is_killer = 'کشتارگاه' if poultry_request.buyer is not None and poultry_request.buyer[ 'buyerType'] == 'killhouse' else 'کشتارکن' if poultry_request.quarantine_code: code = poultry_request.quarantine_code has_code += 1 else: code = '-' freez_state = 'منجمد' if poultry_request.freezing == True else 'عادی' if poultry_request.out_province_poultry_request_buyer is not None: full_name_buyer = poultry_request.out_province_poultry_request_buyer.fullname mobile_buyer = poultry_request.out_province_poultry_request_buyer.user.mobile city_buyer = poultry_request.out_province_poultry_request_buyer.user.city.name province_buyer = poultry_request.out_province_poultry_request_buyer.user.province.name else: full_name_buyer = poultry_request.buyer['firstName'] mobile_buyer = poultry_request.buyer['mobile'] city_buyer = poultry_request.buyer['city'] province_buyer = poultry_request.buyer['province'] if poultry_request.province_state == 'rejected': state1 = 'رد شده' elif poultry_request.province_state == 'pending' and poultry_request.out_province_request_cancel == False: state1 = 'در انتظار تایید' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'در انتظار پرداخت' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == False and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'تایید شده' elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == True and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False: state1 = 'پرداخت شده' else: state1 = 'لغو شده' list1 = [ m, state1, poultry_request.payer_fullname if poultry_request.payer_fullname else '-', str(poultry_request.order_code), str(create_date_of_poultry_request), str(date_of_kill_request), freez_state, poultry_request.poultry.user.fullname, poultry_request.poultry.user.mobile, poultry_request.poultry.user.city.name, poultry_request.poultry.user.province.name, age, poultry_request.hatching.chicken_breed, poultry_request.quantity, poultry_request.Index_weight, int(poultry_request.quantity * poultry_request.Index_weight), poultry_request.hatching.left_over, poultry_request.hatching.quantity, is_killer, full_name_buyer, mobile_buyer, city_buyer, province_buyer, killing_place, uniq_id, killing_place_city, poultry_request.out_province_driver_info[ 'driverCar'] if poultry_request.out_province_driver_info != None else '-', poultry_request.out_province_driver_info[ 'driverPelak'] if poultry_request.out_province_driver_info != None else '-', poultry_request.out_province_driver_info[ 'driverName'] if poultry_request.out_province_driver_info != None else '-', poultry_request.out_province_driver_info[ 'driverMobile'] if poultry_request.out_province_driver_info != None else '-', poultry_request.out_province_driver_info[ 'driverhealthCode'] if poultry_request.out_province_driver_info != None else '-', code, full_name + '(' + mobile + ')', str(date_of_create_code), poultry_request.registrar['fullname'] if poultry_request.registrar else '-' ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') l += 1 # last_age=sorted(reversed(all_age)) all_age = sorted(all_age) value_header_list2 = [ len(poultry_requests_accepted), all_quantity if all_quantity != None else 0, all_weighte if all_weighte != None else 0, all_age[0] if len(all_age) > 0 else None, all_age[len(all_age) - 1] if len(all_age) > 0 else None, has_code, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', all_quantity if all_quantity != None else 0, '', all_weighte, '', all_chicken_quantity, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") else: date1 = request.GET.get('date1') date2 = request.GET.get('date2') date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list( 'kill_house', flat=True) kill_houses = KillHouse.objects.filter(out_province=False, trash=False).exclude( id__in=kill_house_ids).order_by( 'id') serializer = KillHouseForPerformanceDashboardSerializer(kill_houses, many=True, context={'date1': date1, 'date2': date2, }).data excel_options = [ 'ردیف', 'ماهیت', 'کشتارگاه / کشتارکن', 'مالک', 'تلفن', 'شهر', 'تعداد بار داخل استان', 'حجم بار داخل استان', 'وزن بار داخل استان', 'تعداد بار خارج استان', 'حجم بار خارج استان', 'وزن بار خارج استان', 'وزن تخصیصات بدون بار', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str header_list = [ 'تعداد بار داخل استان', 'حجم بار داخل استان', 'وزن بار داخل استان', 'تعداد بار خارج استان', 'حجم بار خارج استان', 'وزن بار خارج استان', 'وزن تخصیصات بدون بار', ] for col_num, option in enumerate(header_list, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 worksheet['B1'] = f'اطلاعات کشتارگاه ها' worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 6 m = 1 if serializer: for data in serializer: killer = 'کشتارگاه' if data['killer'] == False else 'کشتارکن' list1 = [ m, killer, data['name'], data['kill_house_operator']['user']['fullname'], data['kill_house_operator']['user']['mobile'], data['kill_house_operator']['user']['city'], data['killing_info']['kill_house_requests_count'], data['killing_info']['kill_house_requests_quantity'], data['killing_info']['kill_house_requests_weight'], data['killing_info']['kill_house_free_bar_count'], data['killing_info']['kill_house_free_bar_quantity'], data['killing_info']['kill_house_free_bar_weight'], data['killing_info']['province_kill_requests_quantity'], ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') l += 1 total_kill_house_requests_count = sum( data.get('killing_info', {}).get('kill_house_requests_count', 0) for data in serializer ) total_kill_house_requests_quantity = sum( data.get('killing_info', {}).get('kill_house_requests_quantity', 0) for data in serializer ) total_kill_house_requests_weight = sum( data.get('killing_info', {}).get('kill_house_requests_weight', 0) for data in serializer ) total_kill_house_free_bar_count = sum( data.get('killing_info', {}).get('kill_house_free_bar_count', 0) for data in serializer ) total_kill_house_free_bar_quantity = sum( data.get('killing_info', {}).get('kill_house_free_bar_quantity', 0) for data in serializer ) total_kill_house_free_bar_weight = sum( data.get('killing_info', {}).get('kill_house_free_bar_weight', 0) for data in serializer ) total_province_kill_requests_quantity = sum( data.get('killing_info', {}).get('province_kill_requests_quantity', 0) for data in serializer ) # ایجاد لیست از مقادیر جمع‌زده شده totals_list = [ total_kill_house_requests_count, total_kill_house_requests_quantity, total_kill_house_requests_weight, total_kill_house_free_bar_count, total_kill_house_free_bar_quantity, total_kill_house_free_bar_weight, total_province_kill_requests_quantity ] for item in range(len(totals_list)): cell = worksheet.cell(row=3, column=item + 6, value=totals_list[item]) value = totals_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', total_kill_house_requests_count, total_kill_house_requests_quantity, total_kill_house_requests_weight, total_kill_house_free_bar_count, total_kill_house_free_bar_quantity, total_kill_house_free_bar_weight, total_province_kill_requests_quantity ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") workbook.save(output) output.seek(0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response[ 'Content-Disposition'] = f'attachment; filename="داشبورد.xlsx"'.encode( # noqa 'utf-8') response.write(output.getvalue()) return response def steward_allocation_excel(request): user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) role = request.GET.get('role') date1 = request.GET.get('date1') date2 = request.GET.get('date2') value = request.GET.get('value') search = request.GET.get('search') kill_house_key = request.GET.get('kill_house_key') steward_key = request.GET.get('steward_key') allocations_type = request.GET.get('type') trash = request.GET.get('trash') return_trash = request.GET.get('return_trash') filters = { 'to_cold_house__isnull': True, 'calculate_status': True, } if trash == 'true': filters['trash'] = True filters['active_expire_date_time'] = True else: filters['trash'] = False if allocations_type == 'KillHouse': filters['kill_house__isnull'] = False elif allocations_type == 'Steward': filters['steward__isnull'] = False if return_trash == 'true': filters['return_trash'] = True filters['trash'] = False if kill_house_key and kill_house_key != 'all': filters['kill_house__key'] = kill_house_key if steward_key and steward_key != 'all': filters['steward__key'] = steward_key if date1: filters['date__date__gte'] = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() filters['date__date__lte'] = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() if role == 'KillHouse': kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first() filters['kill_house'] = kill_house elif role == 'Steward': steward = Guilds.objects.get(user=user, trash=False) filters['steward'] = steward allocations = StewardAllocation.objects.filter(**filters).order_by('-date') if value and search == 'filter': if value != 'undefined' and value.strip(): allocations = allocations.filter( build_query(StewardAllocationDashboardFilterSet, value) ) serializer = InProvinceAllocationSerializer(allocations, many=True).data 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') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد توزیع', 'وزن کل توزیع', 'وزن توزیع به مباشر', 'وزن توزیع به صنف', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) if trash == 'true': excel_description(worksheet, 'A1', f'تخصیصات حذف شده', size=11, color='red', row2='D1') elif return_trash == 'true': excel_description(worksheet, 'A1', f'تخصیصات برگشت داده شده', size=11, color='red', row2='D1') else: excel_description(worksheet, 'A1', f'تخصیصات صورت گرفته', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if serializer: for allocation in serializer: l += 1 allocation_type = allocation.get('allocation_type', '') seller_name = '' seller_mobile = '' seller_city = '' buyer_name = '' buyer_mobile = '' buyer_city = '' kill_house = (allocation or {}).get('kill_house', {}) or {} steward = allocation.get('steward', {}) or {} kill_house_operator = kill_house.get('kill_house_operator', {}) or {} kill_house_user = kill_house_operator.get('user', {}) or {} kill_house_user_city = kill_house_user.get('city', {}) or {} if allocation_type == 'killhouse_steward': seller_name = kill_house.get('name', '') seller_mobile = kill_house_user.get('mobile', '') seller_city = kill_house_user_city.get('city_name', '') allocation_type = 'کشتارگاه به مباشر' to_steward = allocation.get('to_steward', {}) buyer_name = to_steward.get('guilds_name', '') buyer_mobile = to_steward.get('user', {}).get('mobile', '') buyer_city = to_steward.get('user', {}).get('city_name', '') elif allocation_type == 'killhouse_guild': seller_name = kill_house.get('name', '') seller_mobile = kill_house_user.get('mobile', '') seller_city = kill_house_user_city.get('city_name', '') allocation_type = 'کشتارگاه به صنف' to_guilds = allocation.get('to_guilds', {}) if to_guilds: buyer_name = to_guilds.get('guilds_name', '') buyer_mobile = to_guilds.get('user', {}).get('mobile', '') buyer_city = to_guilds.get('user', {}).get('city_name', '') elif allocation_type == 'steward_guild': seller_name = steward.get('guilds_name', '') seller_mobile = steward.get('user', {}).get('mobile', '') seller_city = steward.get('user', {}).get('city_name', '') allocation_type = 'مباشر به صنف' to_guilds = allocation.get('to_guilds', {}) if to_guilds: buyer_name = to_guilds.get('guilds_name', '') buyer_mobile = to_guilds.get('user', {}).get('mobile', '') buyer_city = to_guilds.get('user', {}).get('city_name', '') elif allocation_type == 'steward_steward': seller_name = steward.get('guilds_name', '') seller_mobile = steward.get('user', {}).get('mobile', '') seller_city = steward.get('user', {}).get('city_name', '') allocation_type = 'مباشر به مباشر' to_steward = allocation.get('to_steward', {}) buyer_name = to_steward.get('guilds_name', '') buyer_mobile = to_steward.get('user', {}).get('mobile', '') buyer_city = to_steward.get('user', {}).get('city_name', '') elif allocation_type == 'killhouse_killhouse': seller_name = kill_house.get('name', '') seller_mobile = kill_house_user.get('mobile', '') seller_city = kill_house_user_city.get('city_name', '') allocation_type = 'کشتارگاه به کشتارگاه' to_kill_house = allocation.get('to_kill_house', {}) buyer_name = to_kill_house.get('name', '') buyer_mobile = to_kill_house.get('kill_house_operator', {}).get('user', {}).get('mobile', '') buyer_city = to_kill_house.get('kill_house_operator', {}).get('user', {}).get('city', {}).get( 'city_name', '') if allocation['sell_type'] == 'exclusive': sell_type = 'اختصاصی' else: sell_type = 'آزاد' system_registration_code = 'ارسال شده' if allocation['system_registration_code'] == True else 'ارسال نشده' if allocation['state'] == 'pending': state = 'در انتظار تایید' elif trash == 'true': state = 'حذف شده' elif return_trash == 'true': state = 'برگشت داده شده' else: state = 'تایید شده' try: date = datetime.datetime.strptime(allocation['date'], '%Y-%m-%dT%H:%M:%S.%f') except ValueError: date = datetime.datetime.strptime(allocation['date'], '%Y-%m-%dT%H:%M:%S') list1 = [ m, str(shamsi_date(date, set_datetime=True)), allocation_type, seller_name, seller_mobile, seller_city, buyer_name, buyer_mobile, allocation.get('interface_number') or '-', buyer_city, allocation.get('steward_pos_status') or 'ندارد', allocation.get('guild_pos_status') or 'ندارد', sell_type, allocation.get('amount', 0), allocation.get('total_amount', 0), allocation.get('weight_of_carcasses', 0), allocation.get('receiver_real_weight_of_carcasses', 0), str(allocation.get('registration_code') or '-'), system_registration_code, state, ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] if isinstance(value, (int)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') total_amount = sum( allocation.get('total_amount', 0) for allocation in serializer) weight_of_carcasses_allocations = sum( allocation.get('weight_of_carcasses', 0) for allocation in serializer) receiver_real_weight_of_carcasses_allocations = sum( allocation.get('receiver_real_weight_of_carcasses', 0) for allocation in serializer) allocations_aggregates = allocations.aggregate( total_count=Count('id'), total_weight=Sum('real_weight_of_carcasses'), total_steward_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False)), total_guild_weight=Sum('real_weight_of_carcasses', filter=Q(to_guilds__isnull=False)), ) value_header_list2 = [ allocations_aggregates['total_count'] or 0, int(allocations_aggregates['total_weight'] or 0), int(allocations_aggregates['total_steward_weight'] or 0), int(allocations_aggregates['total_guild_weight'] or 0), ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', total_amount, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 sevrence_kill_house_steward_allocation_excel(request): filterset_class = StewardAllocationDashboardFilterSet role = request.GET.get('role') date1 = request.GET.get('date1') date2 = request.GET.get('date2') value = request.GET.get('value') search = request.GET.get('search') allocations_type = request.GET.get('type') filters = { 'trash': False, 'to_cold_house__isnull': True } if allocations_type == 'KillHouse': filters['kill_house__isnull'] = False elif allocations_type == 'Steward': filters['steward__isnull'] = False if date1: filters['date__date__gte'] = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() filters['date__date__lte'] = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() allocations = StewardAllocation.objects.filter(**filters) if value and search == 'filter': if value != 'undefined' and value.strip(): allocations = allocations.filter( build_query(filterset_class, value) ) serializer = InProvinceAllocationSerializer(allocations, many=True).data kill_house_names = list({(allocation.get('kill_house') or {}).get('name') for allocation in serializer if (allocation.get('kill_house') or {}).get('name')}) excel_options = [ 'ردیف', 'تاریخ ثبت', 'نوع تخصیص', 'فروشنده', 'تلفن فروشنده', 'خریدار', 'تلفن خریدار', 'نوع فروش', 'قیمت هر کیلو(ریال)', 'قیمت کل', 'وزن تخصیصی', 'وزن تایید شده', 'کد احراز', 'وضعیت کد احراز', 'وضعیت', ] output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) l = 5 m = 1 if serializer: for kill_house_name in kill_house_names: kill_house = KillHouse.objects.get(trash=False, name=kill_house_name) sheet_name = kill_house.name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد توزیع', 'وزن کل توزیع', 'وزن توزیع به مباشر', 'وزن توزیع به صنف', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'توزیع داخل استان کشتارگاه {sheet_name}', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) red_font = Font(color="C00000", bold=True) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") allocations = allocations.filter(kill_house=kill_house) serializer1 = InProvinceAllocationSerializer(allocations, many=True).data for allocation in serializer1: l += 1 allocation_type = allocation.get('allocation_type', '') seller_name = '' seller_mobile = '' buyer_name = '' buyer_mobile = '' kill_house = allocation.get('kill_house', {}) kill_house_operator = kill_house.get('kill_house_operator', {}) kill_house_user = kill_house_operator.get('user', {}) if allocation_type == 'killhouse_steward': seller_name = kill_house.get('name', '') seller_mobile = kill_house_user.get('mobile', '') allocation_type = 'کشتارگاه به مباشر' to_steward = allocation.get('to_steward', {}) buyer_name = to_steward.get('guilds_name', '') buyer_mobile = to_steward.get('user', {}).get('mobile', '') elif allocation_type == 'killhouse_guild': seller_name = kill_house.get('name', '') seller_mobile = kill_house_user.get('mobile', '') allocation_type = 'کشتارگاه به صنف' to_guilds = allocation.get('to_guilds', {}) if to_guilds: buyer_name = to_guilds.get('guilds_name', '') buyer_mobile = to_guilds.get('user', {}).get('mobile', '') elif allocation_type == 'killhouse_killhouse': seller_name = kill_house.get('name', '') seller_mobile = kill_house_user.get('mobile', '') allocation_type = 'کشتارگاه به کشتارگاه' to_kill_house = allocation.get('to_kill_house', {}) buyer_name = to_kill_house.get('name', '') buyer_mobile = to_kill_house.get('kill_house_operator', {}).get('user', {}).get('mobile', '') if allocation['sell_type'] == 'exclusive': sell_type = 'اختصاصی' else: sell_type = 'آزاد' system_registration_code = 'ارسال شده' if allocation[ 'system_registration_code'] == True else 'ارسال نشده' state = 'در انتظار تایید' if allocation['state'] == 'pending' else 'تایید شده' try: date = datetime.datetime.strptime(allocation['date'], '%Y-%m-%dT%H:%M:%S.%f') except ValueError: date = datetime.datetime.strptime(allocation['date'], '%Y-%m-%dT%H:%M:%S') list1 = [ m, str(shamsi_date(date)), allocation_type, seller_name, seller_mobile, buyer_name, buyer_mobile, sell_type, allocation.get('amount', 0), allocation.get('total_amount', 0), allocation.get('weight_of_carcasses', 0), allocation.get('receiver_real_weight_of_carcasses', 0), str(allocation.get('registration_code') or '-'), system_registration_code, state, ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] if isinstance(value, int): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') total_amount = sum( allocation.get('total_amount', 0) for allocation in serializer1) weight_of_carcasses_allocations = sum( allocation.get('weight_of_carcasses', 0) for allocation in serializer1) receiver_real_weight_of_carcasses_allocations = sum( allocation.get('receiver_real_weight_of_carcasses', 0) for allocation in serializer1) allocations_aggregates = allocations.aggregate( total_count=Count('id'), total_weight=Sum('real_weight_of_carcasses'), total_steward_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False)), total_guild_weight=Sum('real_weight_of_carcasses', filter=Q(to_guilds__isnull=False)), ) value_header_list2 = [ allocations_aggregates['total_count'] or 0, int(allocations_aggregates['total_weight'] or 0), int(allocations_aggregates['total_steward_weight'] or 0), int(allocations_aggregates['total_guild_weight'] or 0), ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', total_amount, weight_of_carcasses_allocations, receiver_real_weight_of_carcasses_allocations, '', '', '', ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 free_sale_out_province_excel(request): filterset_fields = [ 'type_car', 'pelak', 'clearance_code', 'kill_house__name', 'kill_house__kill_house_operator__user__fullname', 'kill_house__kill_house_operator__user__first_name', 'kill_house__kill_house_operator__user__last_name', 'kill_house__kill_house_operator__user__mobile', 'buyer__fullname', 'buyer__first_name', 'buyer__last_name', 'buyer__mobile', 'buyer__unit_name', 'buyer_name', 'buyer_mobile', 'province', 'city', ] filterset_class = KillHouseFreeSaleBarInformationFilterSet user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) date1 = request.GET.get('date1') date2 = request.GET.get('date2') if 'type' in request.GET: role = request.GET['role'] if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() if role in ['ProvinceOperator', 'Commerce', 'ProvinceSupervisor''GuildRoom', 'SuperAdmin', 'ImprovingLivestock', 'AdminX', 'Supporter']: kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter( date__date__gte=date1, date__date__lte=date2, trash=False) elif role in ['CityJahad', 'CityPoultry', 'CityOperator']: kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter( kill_house__system_address__city=user.city, date__date__gte=date1, date__date__lte=date2, trash=False) else: kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first() kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter( kill_house=kill_house, date__date__gte=date1, date__date__lte=date2, trash=False) buyers = len(kill_house_free_sale_bar_info.values_list('buyer', flat=True).distinct()) else: if role in ['ProvinceOperator', 'Commerce', 'ProvinceSupervisor''GuildRoom', 'SuperAdmin', 'ImprovingLivestock', 'AdminX', 'Supporter']: kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter( trash=False) elif role in ['CityJahad', 'CityPoultry', 'CityOperator']: kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter( kill_house__system_address__city=user.city, trash=False) else: kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first() kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter( kill_house=kill_house, trash=False) buyers = len(kill_house_free_sale_bar_info.values_list('buyer', flat=True).distinct()) if 'search' in request.GET: kill_house_free_sale_bar_info_list = [] if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined' and request.GET['value'].strip(): for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=kill_house_free_sale_bar_info ) ).filter(): ps = filterset_class(data=query, queryset=kill_house_free_sale_bar_info) kill_house_free_sale_bar_info_list = ps.filter() kill_house_free_sale_bar_info = [] if len( kill_house_free_sale_bar_info_list) == 0 else kill_house_free_sale_bar_info_list else: now = datetime.datetime.now().date() date = datetime.datetime.strptime(str(request.GET['date']), '%Y-%m-%d').date() if 'date' in request.GET else now kill_house = KillHouse.objects.get(key=request.GET['kill_house_key']) kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, date__year=date.year, date__month=date.month, date__day=date.day, trash=False) buyers = len(kill_house_free_sale_bar_info.values_list('buyer', flat=True).distinct()) serializer = KillHouseFreeSaleBarInformationSerializer(kill_house_free_sale_bar_info, many=True).data excel_options = [ 'ردیف', 'تاریخ', 'فروشنده', 'تلفن فروشنده', 'خریدار', 'تلفن خریدار', 'نام واحد', 'استان', 'شهر', 'کد قرنطینه', 'وزن استعلامی', 'وزن لاشه' ] output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد فروش', 'خریدار', 'وزن کل لاشه', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'فروش به خارج از استان', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if serializer: for allocation in serializer: l += 1 date = datetime.datetime.strptime(allocation['date'], '%Y-%m-%dT%H:%M:%S') kill_house = allocation.get('kill_house', {}) kill_house_operator = kill_house.get('kill_house_operator', {}) kill_house_user = kill_house_operator.get('user', {}) buyer = allocation.get('buyer', {}) list1 = [ m, str(shamsi_date(date)), kill_house.get('name', ''), kill_house_user.get('mobile', ''), buyer.get('fullname', ''), buyer.get('mobile', ''), buyer.get('unit_name', ''), buyer.get('province', ''), buyer.get('city', ''), allocation.get('clearance_code', ''), allocation.get('quarantine_weight_of_carcasses', 0), allocation.get('real_weight_of_carcasses', 0), ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] if isinstance(value, (int)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') total_quarantine_weight = sum( allocation.get('quarantine_weight_of_carcasses', 0) for allocation in serializer ) total_real_weight = sum( allocation.get('real_weight_of_carcasses', 0) for allocation in serializer ) total_real_weight = sum( allocation.get('real_weight_of_carcasses', 0) for allocation in serializer ) value_header_list2 = [ len(kill_house_free_sale_bar_info), buyers, total_real_weight, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', total_quarantine_weight, total_real_weight, ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 steward_free_sale_out_province_excel(request): filterset_class = StewardFreeSaleBarInformationFilterSet filterset_fields = [ 'steward__user__fullname', 'steward__user__first_name', 'steward__user__last_name', 'steward__user__mobile', 'buyer__user__fullname', 'buyer__user__first_name', 'buyer__user__last_name', 'buyer__user__mobile', 'province', 'city', 'province' 'buyer_name' 'buyer_mobile' ] user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) filters = {'trash': False} role = request.GET.get('role') date1 = request.GET.get('date1') date2 = request.GET.get('date2') if role == 'Steward': steward = Guilds.objects.get(user=user, trash=False) filters['steward'] = steward if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() filters['date__date__gte'] = date1 filters['date__date__lte'] = date2 bars = StewardFreeSaleBarInformation.objects.filter(**filters).order_by('-date') value = request.GET.get('value') search = request.GET.get('search') if value and search == 'filter': if value != 'undefined' and value.strip(): bars = bars.filter( build_query(filterset_class, value) ) serializer = StewardFreeSaleBarInformationSerializer(bars, many=True).data excel_options = [ 'ردیف', 'تاریخ', 'فروشنده', 'تلفن فروشنده', 'خریدار', 'تلفن خریدار', 'نام واحد', 'استان', 'شهر', 'کد قرنطینه', 'وزن استعلامی', 'وزن لاشه' ] output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) worksheet['B3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' header_list2 = [ 'تعداد فروش', 'خریدار', 'وزن کل لاشه', ] for col_num, option in enumerate(header_list2, 5): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) excel_description(worksheet, 'A1', f'فروش به خارج از استان مباشرین', size=11, color='red', row2='D1') worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 if serializer: for allocation in serializer: l += 1 date = datetime.datetime.strptime(allocation['date'], '%Y-%m-%dT%H:%M:%S') steward = allocation.get('steward', {}) steward_user = steward.get('user', {}) buyer = allocation.get('buyer', {}) list1 = [ m, str(shamsi_date(date, in_value=True)), steward.get('guilds_name', ''), steward_user.get('mobile', ''), buyer.get('fullname', ''), buyer.get('mobile', ''), buyer.get('unit_name', ''), buyer.get('province', ''), buyer.get('city', ''), allocation.get('clearance_code', ''), allocation.get('quarantine_weight_of_carcasses', 0), allocation.get('weight_of_carcasses', 0), ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] if isinstance(value, (int)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') buyers = len(set(bars.values_list('buyer', flat=True).distinct())) total_quarantine_weight = sum( allocation.get('quarantine_weight_of_carcasses', 0) for allocation in serializer ) total_real_weight = sum( allocation.get('weight_of_carcasses', 0) for allocation in serializer ) value_header_list2 = [ len(bars), buyers, bars.aggregate(total=Sum('weight_of_carcasses'))['total'] or 0, ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 5, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', total_quarantine_weight, total_real_weight, ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") 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 total_steward_dashboard_excel(request): output = BytesIO() workbook = Workbook() worksheet = workbook.active worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) date1 = request.GET.get('date1') date2 = request.GET.get('date2') stewards = Guilds.objects.filter(trash=False, steward=True, active=True).select_related('user').only('user', 'guilds_name', 'steward').order_by( 'id') if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() allocation_stewards = stewards.annotate( allocation_count=Count( 'allocation_to_steward', filter=Q(allocation_to_steward__receiver_state__in=['pending', 'accepted'], allocation_to_steward__date__date__gte=date1, allocation_to_steward__date__date__lte=date2) ) ).filter(allocation_count__gt=0).order_by('-allocation_count') free_bar_stewards = stewards.annotate( free_bar_count=Count( 'free_bar_info_steward' ) ).filter(free_bar_count__gt=0).order_by('-free_bar_count') stewards1 = list(set(chain(allocation_stewards, free_bar_stewards))) else: allocation_stewards = stewards.annotate( allocation_count=Count( 'allocation_to_steward', filter=Q(allocation_to_steward__receiver_state__in=['pending', 'accepted']) ) ).filter(allocation_count__gt=0).order_by('-allocation_count') free_bar_stewards = stewards.annotate( free_bar_count=Count( 'free_bar_info_steward' ) ).filter(free_bar_count__gt=0).order_by('-free_bar_count') stewards1 = list(set(chain(allocation_stewards, free_bar_stewards))) serializer = RealGuildsForDashboardSerializer(stewards1, many=True, context={'request': request}).data header_list2 = [ 'ردیف', 'خریدار', 'تلفن خریدار', 'ماهیت', 'شهر', 'مانده انبار فعلی', 'تعداد کل بارها', 'وزن کل بارها', 'تعداد بار وارد شده به انبار', 'کل وزن ورودی به انبار', 'تعداد فروش رفته', 'کل وزن فروش رفته', 'تعداد بار درون استان', 'وزن بار درون استان', 'تعداد بار لاشه خارج استان', 'وزن بار لاشه خارج استان', 'وزن فروش داخل استان', 'وزن فروش خارج استان', ] create_header(worksheet, header_list2, 1, 12, height=21.8, width=20, border_style='thin') excel_description(worksheet, 'A2', f'اطلاعات جامع انبار', size=11, color='red', row2='B4') if serializer: l = 13 m = 1 for data in serializer: steward_type = 'مباشر' if data.get('steward') == True else 'صنف' list1 = [ m, data.get('user', {}).get('fullname', ''), data.get('user', {}).get('mobile', ''), f'{steward_type}({data.get("guilds_name", "")})', data.get("address", {}).get('city', {}).get('name'), data.get('ware_house_info', {}).get('remain_weight', 0), data.get('ware_house_info', {}).get('total_bars_count', 0), data.get('ware_house_info', {}).get('total_bars_weight', 0), data.get('ware_house_info', {}).get('total_entered_bars_count', 0), data.get('ware_house_info', {}).get('total_entered_bars_weight', 0), data.get('ware_house_info', {}).get('total_in_out_province_bars_count', 0), data.get('ware_house_info', {}).get('total_in_out_province_bars_weight', 0), data.get('ware_house_info', {}).get('input_bars_count', 0), data.get('ware_house_info', {}).get('input_bars_weight', 0), data.get('ware_house_info', {}).get('free_bars_count', 0), data.get('ware_house_info', {}).get('free_bars_weight', 0), data.get('ware_house_info', {}).get('in_province_bars_weight', 0), data.get('ware_house_info', {}).get('out_province_bars_weight', 0), ] create_value(worksheet, list1, l, 1, border_style='thin', m=m) m += 1 l += 1 header_list2 = [ 'وزن کل بارها', 'وزن وارد شده به انبار', 'وزن توزیع شده داخل استان', 'وزن توزیع شده خارج استان', 'مانده انبار', ] create_header(worksheet, header_list2, 3, 3, height=21.8, width=20, color='C00000', border_style='thin') date1 = request.GET.get('date1') date2 = request.GET.get('date2') stewards_filter = {'trash': False, 'steward': True, 'active': True} stewards = Guilds.objects.filter(**stewards_filter).select_related('user').only('user', 'guilds_name', 'steward').order_by( 'id') products = RolesProducts.objects.filter(guild__in=stewards, trash=False, name='مرغ گرم').first() date1 = request.GET.get('date1') date2 = request.GET.get('date2') if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() allocation_stewards = stewards.annotate( allocation_count=Count( 'allocation_to_steward', filter=Q(allocation_to_steward__receiver_state__in=['pending', 'accepted'], allocation_to_steward__date__date__gte=date1, allocation_to_steward__date__date__lte=date2, allocation_to_steward__warehouse=True, allocation_to_steward__steward_warehouse=True) ) ).filter(allocation_count__gt=0).order_by('-allocation_count') free_bar_stewards = stewards.annotate( free_bar_count=Count( 'free_bar_info_steward' ) ).filter(free_bar_count__gt=0).order_by('-free_bar_count') stewards = (list(chain(allocation_stewards, free_bar_stewards))) allocations = StewardAllocation.objects.filter( Q(steward__in=stewards) | Q(to_steward__in=stewards), trash=False, calculate_status=True, to_cold_house__isnull=True, date__date__gte=date1, date__date__lte=date2, warehouse=True, steward_warehouse=True) free_bars = StewardFreeBarInformation.objects.filter(steward__in=stewards, trash=False, date__date__gte=date1, date__date__lte=date2, warehouse=True) free_sale_bars = StewardFreeSaleBarInformation.objects.filter(steward__in=stewards, trash=False, date__date__gte=date1, date__date__lte=date2, warehouse=True) segmentations = PosSegmentation.objects.filter(guild__in=stewards, trash=False, warehouse=True, date__date__gte=date1, date__date__lte=date2) transactions = ProductsTransactions.objects.filter(product=products, transaction__paid=True, transaction__date__date__gte=date1, transaction__date__date__lte=date2, trash=False, warehouse=True) archives = WarehouseArchive.objects.filter(Q(steward__in=stewards) | Q(guild__in=stewards), trash=False, date__date__gte=date1, date__lte=date2, warehouse=True) else: allocation_stewards = stewards.annotate( allocation_count=Count( 'allocation_to_steward', filter=Q(allocation_to_steward__receiver_state__in=['pending', 'accepted'], allocation_to_steward__warehouse=True, allocation_to_steward__steward_warehouse=True) ) ).filter(allocation_count__gt=0).order_by('-allocation_count').values_list('id', flat=True) free_bar_stewards = stewards.annotate( free_bar_count=Count( 'free_bar_info_steward' ) ).filter(free_bar_count__gt=0).order_by('-free_bar_count').values_list('id', flat=True) stewards = (list(chain(allocation_stewards, free_bar_stewards))) allocations = StewardAllocation.objects.filter( Q(steward__in=stewards) | Q(to_steward__in=stewards), trash=False, calculate_status=True, to_cold_house__isnull=True, warehouse=True, steward_warehouse=True) free_bars = StewardFreeBarInformation.objects.filter(steward__in=stewards, trash=False, warehouse=True) free_sale_bars = StewardFreeSaleBarInformation.objects.filter(steward__in=stewards, trash=False, warehouse=True) segmentations = PosSegmentation.objects.filter(guild__in=stewards, trash=False, warehouse=True) transactions = ProductsTransactions.objects.filter(product=products, transaction__paid=True, trash=False, warehouse=True) archives = WarehouseArchive.objects.filter(Q(steward__in=stewards) | Q(guild__in=stewards), trash=False, warehouse=True) allocations_aggregates = allocations.aggregate( total_input_bars_count=Count('id', filter=Q(to_steward__isnull=False)), total_input_bars_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False)), total_input_governmental_bars_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False, quota='governmental')), total_input_free_bars_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False, quota='free')), total_output_bars_weight=Sum('real_weight_of_carcasses', filter=Q(steward__isnull=False, receiver_state__in=('pending', 'accepted'))), total_output_governmental_bars_weight=Sum('real_weight_of_carcasses', filter=Q(steward__isnull=False, receiver_state__in=('pending', 'accepted'), quota='governmental')), total_output_free_bars_weight=Sum('real_weight_of_carcasses', filter=Q(steward__isnull=False, receiver_state__in=('pending', 'accepted'), quota='free')), total_input_entered_bars_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False, receiver_state='accepted')), total_input_entered_governmental_bars_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False, receiver_state='accepted', quota='governmental')), total_input_entered_free_bars_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False, receiver_state='accepted', quota='free')), ) free_bars_aggregates = free_bars.aggregate( total_count=Count('id'), total_weight=Sum('weight_of_carcasses') ) free_sale_bars_aggregates = free_sale_bars.aggregate( total_count=Count('id'), total_weight=Sum('weight_of_carcasses'), total_governmental_weight=Sum('weight_of_carcasses', quota='governmental'), total_free_weight=Sum('weight_of_carcasses', quota='free'), ) segmentations_weight = \ segmentations.aggregate(total=Sum('weight'))[ 'total'] or 0 segmentations_governmental_weight = \ segmentations.filter(quota='governmental').aggregate(total=Sum('weight'))[ 'total'] or 0 segmentations_free_weight = \ segmentations.filter(quota='free').aggregate(total=Sum('weight'))[ 'total'] or 0 pos_allocated_weight_info = transactions.aggregate( pos_allocated_weight=Sum('cur_weight'), pos_governmental_allocated_weight=Sum('cur_weight', filter=Q(price_approved=True)), pos_free_allocated_weight=Sum('cur_weight', filter=Q(price_approved=False)), ) archives_info = archives.aggregate( archives_weight=Sum('weight'), archives_governmental_weight=Sum('weight', filter=Q(quota='governmental')), archives_free_weight=Sum('weight', filter=Q(quota='free')), ) pos_allocated_weight = pos_allocated_weight_info['pos_allocated_weight'] or 0 pos_governmental_allocated_weight = pos_allocated_weight_info['pos_governmental_allocated_weight'] or 0 pos_free_allocated_weight = pos_allocated_weight_info['pos_free_allocated_weight'] or 0 total_in_province_governmental_input_weight = allocations_aggregates[ 'total_input_entered_governmental_bars_weight'] or 0 total_in_province_free_input_weight = allocations_aggregates['total_input_entered_free_bars_weight'] or 0 total_free_buying_input_weight = free_bars_aggregates['total_weight'] or 0 total_in_province_governmental_output_weight = allocations_aggregates[ 'total_output_governmental_bars_weight'] or 0 total_in_province_free_output_weight = allocations_aggregates['total_output_free_bars_weight'] or 0 total_governmental_free_sale_weight = free_sale_bars_aggregates['total_governmental_weight'] or 0 total_free_free_sale_weight = free_sale_bars_aggregates['total_free_weight'] or 0 archives_weight = archives_info['archives_weight'] or 0 archives_governmental_weight = archives_info['archives_governmental_weight'] or 0 archives_free_weight = archives_info['archives_free_weight'] or 0 total_governmental_input_weight = total_in_province_governmental_input_weight total_free_input_weight = total_in_province_free_input_weight + total_free_buying_input_weight total_input_weight = total_governmental_input_weight + total_free_input_weight total_governmental_output_weight = total_in_province_governmental_output_weight + total_governmental_free_sale_weight + segmentations_governmental_weight + int( pos_governmental_allocated_weight / 1000) total_free_output_weight = total_in_province_free_output_weight + total_free_free_sale_weight + segmentations_free_weight + int( pos_free_allocated_weight / 1000) total_output_weight = total_governmental_output_weight + total_free_output_weight total_governmental_remain_weight = ( total_governmental_input_weight - total_governmental_output_weight) - archives_governmental_weight if ( ( total_governmental_input_weight - total_governmental_output_weight) - archives_governmental_weight) > 0 else 0 total_free_remain_weight = (total_free_input_weight - total_free_output_weight) - archives_free_weight if ( ( total_free_input_weight - total_free_output_weight) - archives_free_weight) > 0 else 0 total_remain_weight = total_governmental_remain_weight + total_free_remain_weight input_allocations_weight = allocations_aggregates['total_input_bars_weight'] or 0 input_entered_allocations_weight = allocations_aggregates['total_input_entered_bars_weight'] or 0 output_allocations_weight = allocations_aggregates['total_output_bars_weight'] or 0 free_bars_weight = free_bars_aggregates['total_weight'] or 0 free_sale_bars_weight = free_sale_bars_aggregates['total_weight'] or 0 remain_weight = int( (input_entered_allocations_weight + free_bars_weight) - ( free_sale_bars_weight + output_allocations_weight + archives_weight)) if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() shamsi_date1 = shamsi_date(date1) shamsi_date2 = shamsi_date(date2) excel_description(worksheet, 'A2', f' اطلاعات جامع انبار از تاریخ {shamsi_date1} تا تاریخ {shamsi_date2}', size=11, color='red', row2='B4') else: excel_description(worksheet, 'A2', f'اطلاعات جامع انبار', size=11, color='red', row2='B4') result = { "total_bars_weight": int(input_allocations_weight + free_bars_weight), "total_entered_bars_weight": int(input_entered_allocations_weight + free_bars_weight), "in_province_bars_weight": int(output_allocations_weight), "out_province_bars_weight": int(free_sale_bars_weight), "remain_weight": remain_weight, } value_header_list = [ result['total_bars_weight'], result['total_entered_bars_weight'], result['in_province_bars_weight'], result['out_province_bars_weight'], result['remain_weight'], ] create_value(worksheet, value_header_list, 4, 3, border_style='thin') # محاسبه مجموع هر یک از فیلدها sum_remain_weight = sum(data.get('ware_house_info', {}).get('remain_weight', 0) for data in serializer) sum_total_bars_count = sum(data.get('ware_house_info', {}).get('total_bars_count', 0) for data in serializer) sum_total_bars_weight = sum(data.get('ware_house_info', {}).get('total_bars_weight', 0) for data in serializer) sum_total_entered_bars_count = sum( data.get('ware_house_info', {}).get('total_entered_bars_count', 0) for data in serializer) sum_total_entered_bars_weight = sum( data.get('ware_house_info', {}).get('total_entered_bars_weight', 0) for data in serializer) sum_total_in_out_province_bars_count = sum( data.get('ware_house_info', {}).get('total_in_out_province_bars_count', 0) for data in serializer) sum_total_in_out_province_bars_weight = sum( data.get('ware_house_info', {}).get('total_in_out_province_bars_weight', 0) for data in serializer) sum_input_bars_count = sum(data.get('ware_house_info', {}).get('input_bars_count', 0) for data in serializer) sum_input_bars_weight = sum(data.get('ware_house_info', {}).get('input_bars_weight', 0) for data in serializer) sum_free_bars_count = sum(data.get('ware_house_info', {}).get('free_bars_count', 0) for data in serializer) sum_free_bars_weight = sum(data.get('ware_house_info', {}).get('free_bars_weight', 0) for data in serializer) sum_in_province_bars_weight = sum( data.get('ware_house_info', {}).get('in_province_bars_weight', 0) for data in serializer) sum_out_province_bars_weight = sum( data.get('ware_house_info', {}).get('out_province_bars_weight', 0) for data in serializer) sum_warehouse_total_entered_bars = sum( data.get('ware_house_info', {}).get('warehouse_total_entered_bars', 0) for data in serializer) # ایجاد لیست نهایی برای ردیف مجموع summary_list = [ 'جمع کل==>', '', '', '', '', sum_remain_weight, sum_total_bars_count, sum_total_bars_weight, sum_total_entered_bars_count, sum_total_entered_bars_weight, sum_total_in_out_province_bars_count, sum_total_in_out_province_bars_weight, sum_input_bars_count, sum_input_bars_weight, sum_free_bars_count, sum_free_bars_weight, sum_in_province_bars_weight, sum_out_province_bars_weight, ] create_value(worksheet, summary_list, l + 1, 1, color='green') 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 detail_of_killing_and_warehouse_excel(request): output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") red_font = Font(color="C00000", bold=True) sheet_list = [ 'تخصیصات بدون بار', 'بارهای تخلیه نشده', 'بار های در انتظار ورود به انبار' ] date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() for name in sheet_list: sheet_name = name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) if sheet_name == 'تخصیصات بدون بار': wage_type = WageType.objects.filter(en_name='province-kill-request').first() total_check_wage = wage_type.amount percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0, trash=False) for percentage_wage_type in percentages_wage_type: if percentage_wage_type.share_type.en_name == 'union': union_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name == 'company': company_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name == 'guilds': guilds_wage_percent = percentage_wage_type.percent / 100 elif percentage_wage_type.share_type.en_name in ['city', 'wallet']: pass else: other_wage_percent = percentage_wage_type.percent / 100 total_wage_type = WageType.objects.filter(trash=False) province_live_wage_amount = total_wage_type.filter(en_name='province-kill-request', trash=False).first().amount free_buying_live_weight_amount = total_wage_type.filter(en_name='live-buy', trash=False).first().amount free_buying_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-buy', trash=False).first().amount free_sell_carcesses_weight_amount = total_wage_type.filter(en_name='carcasse-sell', trash=False).first().amount worksheet['H3'] = 'در این قسمت تخصیصات فاقد بار نمایش داده میشود' merge_range1 = 'H3:K3' worksheet.merge_cells(merge_range1) worksheet['H3'].font = Font(color="C00000", bold=True) worksheet['H3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) province_kill_request = ProvinceKillRequest.objects.filter( state__in=('pending', 'accepted'), return_to_province=False, archive_wage=False, first_car_allocated_quantity=0, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, trash=False).order_by( 'kill_request__recive_date') if wage_counting_type == 'carcass': header_list = [ 'تعداد سفارشات', 'تعداد کل', 'وزن کل', 'وزن لاشه ملاک تعرفه', 'جمع کل تعرفه', ] else: header_list = [ 'تعداد سفارشات', 'تعداد کل', 'وزن کل', 'وزن ملاک تعرفه', 'جمع کل تعرفه', ] for col_num, option in enumerate(header_list, 3): cell = worksheet.cell(row=3, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[3].height = 20.8 if wage_counting_type == 'carcass': excel_options = [ 'ردیف', 'کد سفارش', 'مرغدار', 'تلفن مرغدار', 'شهر', 'تاریخ کشتار', 'محل کشتار', 'نژاد', 'تعداد(قطعه)', 'وزن(کیلوگرم)', 'میانگین وزنی(کیلوگرم)', 'وزن لاشه ملاک تعرفه ', 'تعرفه (ریال)', 'تعرفه تخصیص(ریال)', ] else: excel_options = [ 'ردیف', 'کد سفارش', 'مرغدار', 'تلفن مرغدار', 'شهر', 'تاریخ کشتار', 'محل کشتار', 'نژاد', 'تعداد(قطعه)', 'وزن(کیلوگرم)', 'میانگین وزنی(کیلوگرم)', 'وزن ملاک تعرفه ', 'تعرفه (ریال)', 'تعرفه تخصیص(ریال)', ] from_date = jdatetime.date.fromgregorian( year=date1.year, month=date1.month, day=date1.day ).strftime('%Y-%m-%d') reversed_date = reversed(from_date.split("-")) separate = "-" from_date_1 = separate.join(reversed_date) to_date = jdatetime.date.fromgregorian( year=date2.year, month=date2.month, day=date2.day ).strftime('%Y-%m-%d') reversed_date = reversed(to_date.split("-")) separate = "-" to_date_1 = separate.join(reversed_date) blue_fill = PatternFill(start_color="1E487B", fill_type="solid") cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) create_header_freez(worksheet, excel_options, 1, 6, header_row=7, width=20) # for col_num, option in enumerate(excel_options, 1): # col_letter = get_column_letter(col_num) # cell = worksheet.cell(row=6, column=col_num, value=option) # cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) # cell.fill = blue_fill # cell.font = Font(size=10, bold=True, color='D9FFFFFF') # if len(option) > worksheet.column_dimensions[col_letter].width: # worksheet.column_dimensions[col_letter].width = len(option) + 3 # # # تنظیم ارتفاع سطر # # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم # worksheet.row_dimensions[6].height = 19 # worksheet.freeze_panes = worksheet['A7'] # max_col = worksheet.max_column # range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' # worksheet.auto_filter.ref = range_str l = 6 m = 1 for province_kill in province_kill_request: kill_date_1 = shamsi_date(province_kill.province_request.poultry_request.send_date) if province_kill.kill_request.slaughter_house is not None: kill_place = province_kill.kill_request.slaughter_house.name else: kill_place = province_kill.kill_request.kill_house.name total_amount = province_kill.total_wage_amount if wage_counting_type == 'carcass': list1 = [ m, str(province_kill.province_request.poultry_request.order_code), province_kill.province_request.poultry_request.poultry.unit_name, province_kill.province_request.poultry_request.poultry.user.mobile, province_kill.province_request.poultry_request.poultry.address.city.name, str(kill_date_1), kill_place, province_kill.province_request.poultry_request.hatching.chicken_breed, province_kill.total_killed_quantity, province_kill.total_killed_weight, province_kill.province_request.poultry_request.Index_weight, province_kill.total_killed_weight * 0.75, province_live_wage_amount, (province_kill.total_killed_weight * 0.75) * province_live_wage_amount, ] else: list1 = [ m, str(province_kill.province_request.poultry_request.order_code), province_kill.province_request.poultry_request.poultry.unit_name, province_kill.province_request.poultry_request.poultry.user.mobile, province_kill.province_request.poultry_request.poultry.address.city.name, str(kill_date_1), kill_place, province_kill.province_request.poultry_request.hatching.chicken_breed, province_kill.total_killed_quantity, province_kill.total_killed_weight, province_kill.province_request.poultry_request.Index_weight, province_kill.total_killed_weight, province_live_wage_amount, (province_kill.total_killed_weight) * province_live_wage_amount, ] for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') l += 1 m += 1 total_weight = \ province_kill_request.aggregate(total=Sum('total_killed_weight'))[ 'total'] or 0 total_killed_quantity = \ province_kill_request.aggregate(total=Sum('total_killed_quantity'))[ 'total'] or 0 total_wage_amount = \ province_kill_request.aggregate(total=Sum('total_wage_amount'))[ 'total'] or 0 if wage_counting_type == 'carcass': value_list = [ m - 1, total_killed_quantity, total_weight, total_weight * 0.75, (total_weight * 0.75) * province_live_wage_amount, ] else: value_list = [ m - 1, total_killed_quantity, total_weight, total_weight, (total_weight) * province_live_wage_amount, ] for item in range(len(value_list)): cell = worksheet.cell(row=4, column=item + 3, value=value_list[item]) value = value_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') if wage_counting_type == 'carcass': list2 = [ 'مجموع==>', '', '', '', '', '', '', '', total_killed_quantity, total_weight, '', total_weight * 0.75, province_live_wage_amount, (total_weight * 0.75) * province_live_wage_amount, ] else: list2 = [ 'مجموع==>', '', '', '', '', '', '', '', total_killed_quantity, total_weight, '', total_weight, province_live_wage_amount, (total_weight) * province_live_wage_amount, ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'بارهای تخلیه نشده': filtered_kill_reqs = KillHouseRequest.objects.filter(trash=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2).order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'province_request', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state').values( 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'province_request', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', ) filtered_kill_reqs_not_assigment_but_have_code1 = filtered_kill_reqs.filter( assignment_state_archive='pending') poultry_request = ( PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs_not_assigment_but_have_code1.values( 'province_request__poultry_request')) .only('quantity', 'Index_weight')).annotate( total_quantity=Sum('quantity'), total_weight=Sum(F('quantity') * F('Index_weight')) ) total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] all_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity', 0) excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'کدسفارش مرغدار', 'مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', ' محل کشتار ', 'نوع تخصیص', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', ] for col_num, option in enumerate(excel_options, 1): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=6, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = blue_fill cell.font = Font(size=10, bold=True, color='D9FFFFFF') if len(option) > worksheet.column_dimensions[col_letter].width: worksheet.column_dimensions[col_letter].width = len(option) + 3 # تنظیم ارتفاع سطر # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم worksheet.row_dimensions[6].height = 19 worksheet.freeze_panes = worksheet['A7'] max_col = worksheet.max_column range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}' worksheet.auto_filter.ref = range_str header_list = [ 'تعداد بارها', 'مجموع تعداد قطعه بارها', 'مجموع وزن بارها', 'تعداد بارهای دارای کد قرنطینه', 'تعداد بار احراز شده از قرنطینه', 'مجموع تعداد قطعه احراز شده از قرنطینه', 'تعداد تخلیه شده دامپزشک', 'مجموع تعداد تخلیه شده دامپزشک', 'مجموع وزن تخلیه شده دامپزشک', 'تعداد بارهای تکمیل شده', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', ] for col_num, option in enumerate(header_list, 9): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="0070C0", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 header_list2 = [ 'تعداد درخواست مرغداران', ' مجموع تعداد قطعه درخواست مرغداران', ' مجموع وزن درخواست مرغداران', ] for col_num, option in enumerate(header_list2, 6): cell = worksheet.cell(row=2, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") cell.font = Font(size=9, bold=True, color='D9FFFFFF') worksheet.row_dimensions[2].height = 20.8 # worksheet['B1'] = f'بارهای تخلیه نشده با کد قرنطینه' if filtered_kill_reqs.exists(): name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name'] worksheet['B2'] = f'استان {name}' worksheet['B3'] = f'از تاریخ:({shamsi_date(date1)}) تا تاریخ:({shamsi_date(date2)})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'B2:D2' merge_range = 'B3:D3' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 5 m = 1 all_quantity = 0 all_real_quantity = 0 all_net_weighte = 0 all_weighte = 0 all_vet_state_accepted = len( filtered_kill_reqs_not_assigment_but_have_code1.filter(vet_state='accepted')) bar_complete = filtered_kill_reqs_not_assigment_but_have_code1.filter(assignment_state_archive='True') accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate( total_quantity=Sum('accepted_real_quantity')).get( 'total_quantity', 0) accepted_real_wight = filtered_kill_reqs_not_assigment_but_have_code1.aggregate( total_quantity=Sum('accepted_real_weight')).get( 'total_quantity', 0) all_kill_request_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate( total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_vet_accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate( total_quantity=Sum('vet_accepted_real_quantity')).get( 'total_quantity', 0) all_vet_accepted_real_weight = filtered_kill_reqs_not_assigment_but_have_code1.aggregate( total_quantity=Sum('vet_accepted_real_weight')).get( 'total_quantity', 0) if filtered_kill_reqs_not_assigment_but_have_code1: for kill in filtered_kill_reqs_not_assigment_but_have_code1: if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' l += 1 date_of_inner_bar = '-' vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'), trash=False).select_related('vet__user').only( 'vet__user__fullname', 'vet__user__mobile').values( 'vet__user__fullname', 'vet__user__mobile').first() vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-' vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-' kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only( 'create_date').values( 'create_date').first() kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' code = kill.get('clearance_code') if kill.get('clearance_code') else '-' if kill.get('quantity'): quantity = kill.get('quantity') all_quantity += quantity else: quantity = '-' send_date = kill.get('province_request__poultry_request__send_date') date_of_poultry_request = jdatetime.date.fromgregorian( day=send_date.day, month=send_date.month, year=send_date.year ) killers = 'کشتارکن' if kill.get('killhouse_user__killer') == False: killers = 'کشتارگاه' assignment = KillHouseAssignmentInformation.objects.filter( kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight', 'real_quantity').values( 'net_weight', 'real_quantity', 'create_date').first() if assignment: net_weighte = assignment.get('net_weight') all_net_weighte += net_weighte real_quantity = assignment.get('real_quantity') all_real_quantity += real_quantity vet_check_date = assignment.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) else: net_weighte = '-' real_quantity = '-' if vet_checks: vet_check_date = vet_checks.get('create_date') date_of_inner_bar = convert_to_shamsi( datetime=vet_check_date ) if kill.get('kill_request__slaughter_house') is not None: kill_place = kill.get('kill_request__slaughter_house__name') else: kill_place = '-' vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-' vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-' weight = kill.get('quantity') * kill.get( 'province_kill_request__province_request__poultry_request__Index_weight') all_weighte += weight quarantine_quantity = '-' if kill['quarantine_quantity'] != None: quarantine_quantity = kill['quarantine_quantity'] else: if kill['quarantine_code_state'] == 'contradiction': quarantine_quantity = 'مغایرت کد رهگیری' elif kill['quarantine_code_state'] == 'noclearance': quarantine_quantity = 'فاقد کد رهگیری' elif kill['quarantine_code_state'] == 'notconfirmed': quarantine_quantity = 'عدم تایید راهداری' elif kill['quarantine_code_state'] == 'merge': quarantine_quantity = 'ادغام' sale_type = 'دولتی' if kill[ 'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد' if kill['province_kill_request__province_request__poultry_request__union'] == True: type = 'فروش آزاد' elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' else: type = 'اتحادیه' age = (kill['province_request__poultry_request__send_date'].date() - kill[ 'province_request__poultry_request__hatching__date'].date()).days + 1 list1 = [ m, str(kill.get('bar_code')), str(date_of_poultry_request), str(kill.get('province_request__poultry_request__order_code')), kill.get('province_request__poultry_request__poultry__unit_name'), str(kill.get('province_request__poultry_request__poultry__user__mobile')), kill.get('province_request__poultry_request__poultry__user__city__name'), sale_type, age, kill.get('province_request__poultry_request__amount') if kill.get( 'province_request__poultry_request__amount') else '-', kill.get('province_request__poultry_request__chicken_breed'), vet_farm_name, vet_farm_mobile, killers, kill.get('killhouse_user__name'), kill.get('killhouse_user__kill_house_operator__user__mobile'), kill.get('killhouse_user__system_address__city__name'), kill_place, type, kill_house_vet_name, kill_house_vet_mobile, kill.get('add_car__driver__driver_name'), kill.get('add_car__driver__driver_mobile'), kill.get('add_car__driver__type_car'), str(kill.get('traffic_code')), quantity, weight, code, quarantine_quantity, state, str(date_of_inner_bar), vet_quantity, vet_wight, real_quantity, net_weighte, kill['accepted_real_quantity'], kill['accepted_real_weight'], ] m += 1 for item in range(len(list1)): cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item]) value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values worksheet.row_dimensions[l + 1].height = 20 cell.alignment = Alignment(horizontal='center', vertical='center') has_code = len(filtered_kill_reqs_not_assigment_but_have_code1.filter(clearance_code__isnull=False)) all_quarantine_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate( total_quantity=Sum('quarantine_quantity')).get( 'total_quantity', 0) has_qarantine = len( filtered_kill_reqs_not_assigment_but_have_code1.filter(quarantine_quantity__isnull=False)) value_header_list = [ len(filtered_kill_reqs_not_assigment_but_have_code1), all_quantity, all_weighte, has_code, has_qarantine, all_quarantine_quantity if all_quarantine_quantity != None else 0, all_vet_state_accepted, all_vet_accepted_real_quantity, all_vet_accepted_real_weight, len(bar_complete), all_real_quantity, all_net_weighte, accepted_real_quantity if accepted_real_quantity != None else 0, accepted_real_wight if accepted_real_wight != None else 0 ] for item in range(len(value_header_list)): cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item]) value = value_header_list[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) value_header_list2 = [ len(poultry_request), total_requests_quantity, total_requests_weight ] for item in range(len(value_header_list2)): cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item]) value = value_header_list2[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_kill_request_quantity, all_weighte, '', all_quarantine_quantity if all_quarantine_quantity != None else 0, '', '', all_vet_accepted_real_quantity, all_vet_accepted_real_weight, all_real_quantity, all_net_weighte, accepted_real_quantity if accepted_real_quantity != None else 0, accepted_real_wight if accepted_real_wight != None else 0 ] for item in range(len(list2)): cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") else: filterset_class = KillHouseRequestFilterSet filterset_fields = [ 'killhouse_user__kill_house_operator__user__fullname', 'killhouse_user__kill_house_operator__user__mobile', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__order_code', 'province_request__poultry_request__order_code', 'bar_code', ] kill_house = KillHouse.objects.filter(trash=False).select_related( 'system_address__province').first() if 'date1' in request.GET and request.GET['date1']: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() filtered_kill_reqs = KillHouseRequest.objects.filter( Q(killhouse_user=kill_house) | Q(killer=kill_house), kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, ware_house_confirmation=False, trash=False, calculate_status=True).order_by( '-kill_request__recive_date').order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'province_kill_request__province_request__poultry_request__out', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'bar_document_status__title').values( 'province_request__poultry_request__poultry__user__fullname', 'province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_confirmation', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'province_kill_request__province_request__poultry_request__out', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'bar_document_status__title' ) else: filtered_kill_reqs = KillHouseRequest.objects.filter( Q(killhouse_user=kill_house) | Q(killer=kill_house), ware_house_confirmation=False, trash=False, calculate_status=True).order_by( '-kill_request__recive_date').order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'province_kill_request__province_request__poultry_request__out', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'bar_document_status__title').values( 'province_request__poultry_request__poultry__user__fullname', 'province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_confirmation', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'province_kill_request__province_request__poultry_request__out', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'bar_document_status__title' ) if 'search' in request.GET: filtered_kill_reqs = [] if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=filtered_kill_reqs ) ).filter(): ps = filterset_class(data=query, queryset=filtered_kill_reqs) filtered_kill_reqs = ps.filter() filtered_kill_reqs = [] if len(filtered_kill_reqs) == 0 else filtered_kill_reqs poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values( 'province_request__poultry_request')) .only('quantity', 'Index_weight')).annotate( total_quantity=Sum('quantity'), total_weight=Sum(F('quantity') * F('Index_weight')) ) excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'نوع کشتار', 'کدسفارش مرغدار', 'نام و نام خانوادگی مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'نام فارم', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', 'کشتارکن اختصاصی', 'تلفن کشتارکن اختصاصی', ' محل کشتار ', 'قیمت کشتارگاه(ریال)', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'وضعیت', 'وضعیت سند', 'وضعیت ورود انبار', 'تعداد لاشه', 'وزن لاشه', 'درصد افت در لحظه', 'درصد افت ورود به انبار', 'کشور مقصد', ] cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') header_list = [ 'تعداد بارهای ایجاد شده', 'تعداد بارهای دارای کشتارکن اختصاصی', 'مجموع حجم بارها', 'مجموع وزن بارها', 'میانگین وزن ', 'کمترین سن', 'بیشترین سن', 'میانگین سنی', 'تعداد بارهای دارای کد قرنطینه', 'حجم بارهای دارای کد قرنطینه', 'تعداد بار احراز شده از قرنطینه', 'مجموع تعداد قطعه احراز شده از قرنطینه', 'تعداد بار فاقد قرنطینه', 'حجم بار فاقد قرنطینه', ' تعداد بارهایی که در قرنطینه و رصدیار اختلاف دارند', 'تعداد تخلیه شده دامپزشک', 'مجموع تعداد تخلیه شده دامپزشک', 'مجموع وزن تخلیه شده دامپزشک', 'تعداد بارهای تکمیل شده', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'تعداد بار های وارد شده در انبار', 'مجموع تعداد لاشه', 'مجموع وزن لاشه', 'میانگین درصد افت لاشه ورود به انبار', ] # برای بالای هدر header_list2 = [ 'تعداد درخواست مرغداران', ' مجموع تعداد قطعه درخواست مرغداران', ' مجموع وزن درخواست مرغداران', ] create_header(worksheet, header_list2, 6, 4, height=21.8, color='green') create_header(worksheet, header_list, 9, 4, height=21.8) header_list2 = [ 'ردیف', 'نام محصول', 'وزن خریدهای دولتی داخل استان(کیلوگرم)', 'وزن خریدهای آزاد داخل استان(کیلوگرم)', 'وزن خریدهای خارج استان(کیلوگرم)', 'کل ورودی به انبار(کیلوگرم)', 'کل فروش(کیلوگرم)', 'مانده انبار(کیلوگرم)', ] create_header(worksheet, header_list2, 6, 1, height=21.8, color='FF0000') products = RolesProducts.objects.filter(kill_house=kill_house, trash=False) q = 2 w = 1 for product in products: value_header_list = [ w, product.name, product.province_governmental_carcasses_weight, product.province_free_carcasses_weight, product.free_buying_carcasses_weight, product.total_carcasses_weight, product.real_allocated_weight, product.total_remain_weight, ] create_value(worksheet, value_header_list, q, 6) q += 1 w += 1 kill_house_name = '' if filtered_kill_reqs.exists(): kill_house_name = filtered_kill_reqs.first()['killhouse_user__name'] excel_description(worksheet, 'A1', f'بارهای {kill_house_name} در انتظار ورود به انبار (کشتار داخل استان)', size=11, color='red', row2='E1') if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='C3') m = 1 create_header_freez(worksheet, excel_options, 1, 7, 8, 20) kill_keys = [kill.get('key') for kill in filtered_kill_reqs] vet_checks = VetCheckRequest.objects.filter( trash=False, kill_house_request__key__in=kill_keys ).only('create_date', 'kill_house_request__key').values( 'create_date', 'kill_house_request__key') assignments = KillHouseAssignmentInformation.objects.filter( kill_house_request__key__in=kill_keys, trash=False ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key') vet_check_mapping = {vc['kill_house_request__key']: vc['create_date'] for vc in vet_checks} assignment_mapping = { assignment.kill_house_request.key: ( int(assignment.net_weight), assignment.real_quantity, assignment.create_date) for assignment in assignments } l = 7 all_age = [] all_real_quantity = 0 all_net_weighte = 0 all_weighte = 0 poultry_ids = [req.get('province_request__poultry_request__poultry') for req in filtered_kill_reqs] vet_farms = VetFarm.objects.filter(poultry__in=poultry_ids, trash=False).select_related('vet__user') vet_farm_mapping = { vet_farm.poultry_id: (vet_farm.vet.user.fullname, vet_farm.vet.user.mobile) for vet_farm in vet_farms } if filtered_kill_reqs: for kill in filtered_kill_reqs: age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if age not in all_age: all_age.append(age) if (kill['assignment_state_archive']) == 'True' or kill[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' l += 1 vet_farm_id = kill.get('province_request__poultry_request__poultry') vet_farm_name, vet_farm_mobile = vet_farm_mapping.get(vet_farm_id, ('-', '-')) kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'), trash=False).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() code = kill.get('clearance_code') if kill.get('clearance_code') else '-' if kill.get('quantity'): quantity = kill.get('quantity') else: quantity = '-' send_date = kill.get('province_request__poultry_request__send_date') date_of_poultry_request = convert_to_shamsi(year=send_date.year, month=send_date.month, day=send_date.day, ) killers = 'کشتارکن' name_killer_exclusive = '-' mobile_killer_exclusive = '-' if kill.get('killhouse_user__killer') == False: killers = 'کشتارگاه' if kill.get('killer') != None: name_killer_exclusive = kill['killer__name'] mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile']) key = kill.get('key') kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' net_weighte, real_quantity, vet_check_date = assignment_mapping.get(key, ('-', '-', None)) all_real_quantity += real_quantity if real_quantity != '-' else 0 all_net_weighte += net_weighte if net_weighte != '-' else 0 vet_check_date = vet_check_mapping.get(key, vet_check_date) date_of_inner_bar = convert_to_shamsi(datetime=vet_check_date) if vet_check_date else '-' if kill.get('kill_request__slaughter_house') is not None: kill_place = kill.get('kill_request__slaughter_house__name') else: kill_place = '-' vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-' vet_wight = int(kill['vet_accepted_real_weight']) if kill['vet_accepted_real_weight'] else '-' weight = int(kill.get('quantity') * kill.get( 'province_kill_request__province_request__poultry_request__Index_weight')) quarantine_quantity = '-' if kill['quarantine_quantity'] != None: quarantine_quantity = kill['quarantine_quantity'] else: if kill['quarantine_code_state'] == 'contradiction': quarantine_quantity = 'مغایرت کد رهگیری' elif kill['quarantine_code_state'] == 'noclearance': quarantine_quantity = 'فاقد کد رهگیری' elif kill['quarantine_code_state'] == 'notconfirmed': quarantine_quantity = 'عدم تایید راهداری' elif kill['quarantine_code_state'] == 'merge': quarantine_quantity = 'ادغام' export_country = '-' sale_type = 'دولتی' if kill[ 'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد' if kill['province_kill_request__province_request__poultry_request__out'] == True: type = 'خارج از استان' elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' elif kill['province_request__poultry_request__freezing'] == True: type = 'انجماد' elif kill['province_request__poultry_request__export'] == True: type = 'صادرات' export_country = kill['kill_request__export_country'] else: type = 'عادی' age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if kill['message'] is not None: state_delete = 'بار حذف شده' else: state_delete = 'فعال' all_weighte += weight ware_house_accepted_real_quantity = kill['ware_house_accepted_real_quantity'] ware_house_accepted_real_weight = kill['ware_house_accepted_real_weight'] weight_loss = round(kill['weight_loss'], 2) if kill['weight_loss'] > 0 else 0 if kill['ware_house_confirmation'] == True: state_ware_house_confirmation = 'ورود به انبار' else: state_ware_house_confirmation = '-' weight_loss1 = kill['accepted_real_weight'] - kill['ware_house_accepted_real_weight'] if kill[ 'ware_house_accepted_real_weight'] > 0 else 0 if weight_loss1 < 0: weight_loss1 = weight_loss1 * -1 total_weight_loss = (weight_loss1 / kill['accepted_real_weight']) * 100 if weight_loss1 != 0 else 0 list1 = [ m, str(kill.get('bar_code')), str(date_of_poultry_request), type, str(kill.get('province_request__poultry_request__order_code')), kill.get('province_request__poultry_request__poultry__user__fullname'), str(kill.get('province_request__poultry_request__poultry__user__mobile')), kill.get('province_request__poultry_request__poultry__user__city__name'), kill.get('province_request__poultry_request__poultry__unit_name'), sale_type, age, kill.get('province_request__poultry_request__amount') if kill.get( 'province_request__poultry_request__amount') else '-', kill.get('province_request__poultry_request__chicken_breed'), vet_farm_name, vet_farm_mobile, killers, kill.get('killhouse_user__name'), kill.get('killhouse_user__kill_house_operator__user__mobile'), kill.get('killhouse_user__system_address__city__name'), name_killer_exclusive, mobile_killer_exclusive, kill_place, kill.get('province_kill_request__kill_house_price'), kill_house_vet_name, kill_house_vet_mobile, kill.get('add_car__driver__driver_name'), kill.get('add_car__driver__driver_mobile'), kill.get('add_car__driver__type_car'), str(kill.get('traffic_code')), quantity, weight, code, quarantine_quantity, state, str(date_of_inner_bar), vet_quantity, vet_wight, real_quantity, net_weighte, kill['accepted_real_quantity'], int(kill['accepted_real_weight']), state_delete, kill['bar_document_status__title'] if kill['bar_document_status'] else '-', state_ware_house_confirmation, ware_house_accepted_real_quantity, int(ware_house_accepted_real_weight), f'%{round(total_weight_loss, 2)}', f'%{weight_loss}', export_country, ] m += 1 create_value(worksheet, list1, l, 1, height=20, different_cell=40, different_value='بار حذف شده') killer_exclusive = len(filtered_kill_reqs.filter(killer__isnull=False)) all_state_ware_house_confirmation = len(filtered_kill_reqs.filter(ware_house_confirmation=True)) total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] or 0 total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0 aggregate_filtered_kill_reqs = filtered_kill_reqs.aggregate( total_accepted_real_quantity=Sum('accepted_real_quantity'), total_accepted_real_weight=Sum('accepted_real_weight'), total_quantity=Sum('quantity'), total_vet_accepted_real_quantity=Sum('vet_accepted_real_quantity'), total_vet_accepted_real_weight=Sum('vet_accepted_real_weight'), total_quarantine_quantity=Sum('quarantine_quantity'), total_ware_house_accepted_real_quantity=Sum('ware_house_accepted_real_quantity'), total_ware_house_accepted_real_weight=Sum('ware_house_accepted_real_weight'), total_weight_loss=Sum('weight_loss'), ) all_vet_state_accepted = len( filtered_kill_reqs.filter(vet_state='accepted')) bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True') accepted_real_quantity = aggregate_filtered_kill_reqs['total_accepted_real_quantity'] or 0 accepted_real_wight = aggregate_filtered_kill_reqs['total_accepted_real_weight'] or 0 all_kill_request_quantity = aggregate_filtered_kill_reqs['total_quantity'] or 0 all_quarantine_quantity = aggregate_filtered_kill_reqs['total_quarantine_quantity'] or 0 all_vet_accepted_real_quantity = aggregate_filtered_kill_reqs['total_vet_accepted_real_quantity'] or 0 all_vet_accepted_real_weight = aggregate_filtered_kill_reqs['total_vet_accepted_real_weight'] or 0 has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False)) all_ware_house_accepted_real_quantity = aggregate_filtered_kill_reqs[ 'total_ware_house_accepted_real_quantity'] or 0 all_ware_house_accepted_real_weight = aggregate_filtered_kill_reqs[ 'total_ware_house_accepted_real_weight'] or 0 all_weight_loss = aggregate_filtered_kill_reqs['total_weight_loss'] or 0 has_code1 = filtered_kill_reqs.filter(clearance_code__isnull=False).aggregate( total_quantity=Sum('quantity'), ) all_quarantine_quantity_has_code = has_code1['total_quantity'] or 0 hasnt_code1 = filtered_kill_reqs.filter(clearance_code__isnull=True) hasnt_code = hasnt_code1.aggregate( total_quantity=Sum('quantity') ) all_quarantine_quantity_hasnt_code = hasnt_code['total_quantity'] or 0 difference_bar = len(filtered_kill_reqs.filter( Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')))) all_weight_loss = round(int(all_weight_loss) / all_state_ware_house_confirmation, 2) if all_weight_loss > 0 else 0 all_age1 = sorted(all_age) has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False)) value_header_list = [ len(poultry_request), total_requests_quantity, int(total_requests_weight), len(filtered_kill_reqs), killer_exclusive, all_kill_request_quantity, int(all_weighte), round(all_weighte / all_kill_request_quantity, 1) if all_weighte > 0 and all_kill_request_quantity > 0 else 0, all_age1[0] if len(all_age1) > 0 else '-', all_age1[len(all_age1) - 1] if len(all_age1) > 0 else '-', int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-', has_code, all_quarantine_quantity_has_code, has_qarantine, all_quarantine_quantity, len(hasnt_code1), all_quarantine_quantity_hasnt_code, difference_bar, all_vet_state_accepted, all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), len(bar_complete), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, all_state_ware_house_confirmation, all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), f'%{all_weight_loss}' ] create_value(worksheet, value_header_list, 5, 6) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_kill_request_quantity, int(all_weighte), '', all_quarantine_quantity if all_quarantine_quantity != None else 0, '', '', all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, '', '', '', all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), '', '', '', ] create_value(worksheet, list2, l + 3, 1, color='green') 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 management_all_poultry_and_warehouse(request): output = BytesIO() workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date() date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date() sheet_names = ['گزارش جوجه ریزی', 'جوجه ریزی بیش از 60 روز', 'گزارش بارها', 'اطلاعات کشتار روزانه', 'عملکرد خریداران', 'گزارش سند ها', 'اطلاعات جامع انبار و توزیع', 'بارهای بدون مجوز'] from_date_1 = shamsi_date(date1) from_date_2 = shamsi_date(date2) for name in sheet_names: sheet_name = name worksheet = workbook.create_sheet(sheet_name) worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') if sheet_name == 'گزارش جوجه ریزی': date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date() date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date() filtered_poultry_hatch = PoultryHatching.objects.filter(Q(date__date__gte=date1, date__date__lte=date2) | Q(date__date__lte=date1, archive_date__isnull=True) | Q( date__date__lte=date1, archive_date__gte=date1, archive_date__isnull=False), trash=False).select_related('poultry', 'poultry__user').order_by( '-chicken_age') excel_options = [ 'ردیف', 'وضعیت', 'شماره مجوز جوجه ریزی', 'شناسه یکتا', 'مجوز بهداشتی جوجه ریزی', 'نام فارم', 'مرغدار', 'بهره برداری', 'مالکیت', 'ارتباط', 'شهر/تعاونی', 'سالن', ' دوره جوجه ریزی', 'تاریخ ثبت جوجه ریزی', 'تاریخ جوجه ریزی', 'میانگین سن کشتار', 'پیشبینی تاریخ کشتار', 'نژاد', 'سن روز', 'سن بایگانی', 'حجم جوجه ریزی', 'حجم افزایشی', 'تلفات دامپزشک(قطعه)', 'تلفات اتحادیه(قطعه)', 'تلفات کل(قطعه)', 'زنجیره/شرکت', 'دامپزشک فارم', 'تلفن دامپزشک فارم', 'کد سیستمی واحد', 'حجم کشتار شده(قطعه)', 'وزن کل کشتارشده(کیلوگرم)', 'مانده در سالن', ] from_date_1 = shamsi_date(date1) from_date_2 = shamsi_date(date2) header_list = [ 'تعداد فارم فعال', 'تعداد فارم دارای زنجیره فعال', 'مجموع جوجه ریزی', 'مجموع تلفات دامپزشک(قطعه)', 'مجموع تلفات اتحادیه(قطعه)', 'مجموع تلفات کل(قطعه)', 'مجموع قطعه کشتار شده', 'مجموع وزن کل کشتارشده', 'مانده در سالن(قطعه)', 'مانده در سالن از نود درصد(قطعه)', 'کمترین سن', 'بیشترین سن', 'مجموع وزن تعهد دولتی', ' مجموع قطعه کشتار دولتی', ' مجموع وزن کشتار دولتی', ' مجموع قطعه کشتار آزاد', ' مجموع وزن کشتار آزاد', 'مجموع تعداد کشتار خارج از استان', 'مجموع وزن کشتار خارج از استان', 'تعداد فارم های متخلف', 'تعداد بار ایجاد شده', 'حجم بار ایجاد شده', 'وزن بار ایجاد شده', 'تعداد بار کشتار شده', 'حجم بار کشتار شده', 'وزن بار کشتار شده', 'حجم زنجیره', 'وزن زنجیره', ] create_header(worksheet, header_list, 5, 2, height=20) excel_description(worksheet, 'B1', 'گزارش جوجه ریزی های فعال از تاریخ {0} تا {1}'.format(from_date_1, from_date_2), color='red', row2='C3') create_header_freez(worksheet, excel_options, 1, 6, 7, height=22) poultry_ids = filtered_poultry_hatch.values_list('poultry', flat=True).distinct() vet_farms = VetFarm.objects.filter(poultry__in=poultry_ids, trash=False).select_related('vet__user') vet_farm_mapping = { vet_farm.poultry: (vet_farm.vet.user.fullname, vet_farm.vet.user.mobile) for vet_farm in vet_farms } l = 5 m = 1 all_poultry_hatching_quantity = 0 all_poultry_hatching_killed_quantity = 0 all_poultry_hatching_left_over = 0 min_list = [] all_left_over_ninty_percent = 0 violation = 0 all_chain_company = 0 for poultry_hatching in filtered_poultry_hatch: if poultry_hatching.archive == True: archive_age = poultry_hatching.chicken_age else: archive_age = '-' vet_farm_id = poultry_hatching.poultry vet_farm_name, vet_farm_mobile = vet_farm_mapping.get(vet_farm_id, ('-', '-')) all_poultry_hatching_quantity += poultry_hatching.quantity all_poultry_hatching_killed_quantity += poultry_hatching.killed_quantity all_poultry_hatching_left_over += poultry_hatching.left_over if poultry_hatching.chicken_age not in min_list: min_list.append(poultry_hatching.chicken_age) l += 1 create_date = jdatetime.date.fromgregorian( day=poultry_hatching.create_date.day, month=poultry_hatching.create_date.month, year=poultry_hatching.create_date.year ) date = jdatetime.date.fromgregorian( day=poultry_hatching.date.day, month=poultry_hatching.date.month, year=poultry_hatching.date.year ) predicate_date = jdatetime.date.fromgregorian( day=poultry_hatching.predicate_date.day, month=poultry_hatching.predicate_date.month, year=poultry_hatching.predicate_date.year ) if poultry_hatching.predicate_date else '-' date1 = datetime.datetime.strptime(str(poultry_hatching.date), '%Y-%m-%d %H:%M:%S') age = (datetime.datetime.now() - date1).days + 1 left_over_ninty_percent = ((poultry_hatching.quantity * 90) / 100) all_left_over_ninty_percent += left_over_ninty_percent farm_state = 'عادی' if poultry_hatching.violation == True: farm_state = 'متخلف' + ' ' + '(مانده در سالن بیش از حد مجاز)' violation += 1 if poultry_hatching.chain_company: chain_company = poultry_hatching.chain_company.name all_chain_company += 1 else: chain_company = '-' list1 = [ m, farm_state, poultry_hatching.licence_number, poultry_hatching.poultry.breeding_unique_id, poultry_hatching.CertId, poultry_hatching.poultry.unit_name, f'{poultry_hatching.poultry.user.fullname} ({poultry_hatching.poultry.user.mobile})', poultry_hatching.InteractTypeName, poultry_hatching.PersonTypeName, poultry_hatching.UnionTypeName, f'{poultry_hatching.poultry.user.city.name if poultry_hatching.poultry.user.city else "-"} ' f'/ {poultry_hatching.poultry.city_operator if poultry_hatching.poultry.city_operator else "-"}', poultry_hatching.hall, poultry_hatching.period, str(create_date), str(date), poultry_hatching.poultry.killing_ave_age, str(predicate_date), poultry_hatching.chicken_breed, age, archive_age, poultry_hatching.quantity, poultry_hatching.increase_quantity, poultry_hatching.losses, poultry_hatching.direct_losses, poultry_hatching.total_losses, chain_company, vet_farm_name, vet_farm_mobile, poultry_hatching.poultry.system_code, poultry_hatching.killed_quantity, poultry_hatching.total_killed_weight, poultry_hatching.left_over, ] m += 1 create_value(worksheet, list1, l + 1, 1, border_style='thin', different_cell=1, different_value='متخلف' + ' ' + '(وجود فارم فعال دیگر)') min_list = sorted(min_list) all_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('losses')).get( 'total_quantity', 0) all_direct_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('direct_losses')).get( 'total_quantity', 0) all_total_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_losses')).get( 'total_quantity', 0) all_killed_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('killed_quantity')).get( 'total_quantity', 0) all_left_over = filtered_poultry_hatch.aggregate(total_quantity=Sum('left_over')).get( 'total_quantity', 0) all_total_commitment = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_commitment')).get( 'total_quantity', 0) all_governmental_killed_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('governmental_killed_quantity')).get( 'total_quantity', 0) all_free_killed_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('free_killed_quantity')).get( 'total_quantity', 0) all_total_killed_weight = filtered_poultry_hatch.aggregate( total_quantity=Sum('total_killed_weight')).get( 'total_quantity', 0) all_governmental_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('governmental_quantity')).get( 'total_quantity', 0) all_free_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('free_quantity')).get( 'total_quantity', 0) all_out_province_killed_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('out_province_killed_quantity')).get( 'total_quantity', 0) all_out_province_killed_weight = filtered_poultry_hatch.aggregate( total_quantity=Sum('out_province_killed_weight')).get( 'total_quantity', 0) all_increase_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('increase_quantity')).get( 'total_quantity', 0) kill_house_requests = KillHouseRequest.objects.filter(trash=False, province_request__poultry_request__hatching__in=filtered_poultry_hatch) first_quantity = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_quantity')).get( 'total_quantity') or 0 first_weight = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_weight')).get( 'total_quantity') or 0 ware_house_bars = kill_house_requests.filter(ware_house_confirmation=True) ware_house_bars_quantity = ware_house_bars.aggregate(total=Sum('ware_house_accepted_real_quantity'))[ 'total'] or 0 ware_house_bars_weight = ware_house_bars.aggregate(total=Sum('ware_house_accepted_real_weight'))[ 'total'] or 0 ware_house_bars_weight_lose = ware_house_bars.aggregate(total=Sum('weight_loss'))[ 'total'] or 0 bar_complete_with_kill_house = kill_house_requests.filter( assignment_state_archive='True') accepted_real_wight_final = bar_complete_with_kill_house.aggregate( total_quantity=Sum('accepted_real_weight')).get( 'total_quantity') or 0 accepted_real_quantity_final = bar_complete_with_kill_house.aggregate( total_quantity=Sum('accepted_real_quantity')).get( 'total_quantity', 0) or 0 chain_killed_weight_final = filtered_poultry_hatch.aggregate( total_quantity=Sum('chain_killed_weight')).get( 'total_quantity', 0) or 0 chain_killed_quantity_final = filtered_poultry_hatch.aggregate( total_quantity=Sum('chain_killed_quantity')).get( 'total_quantity', 0) or 0 extra_killed_quantity_final = filtered_poultry_hatch.aggregate( total_quantity=Sum('export_killed_quantity')).get( 'total_quantity', 0) or 0 export_killed_weight_final = filtered_poultry_hatch.aggregate( total_quantity=Sum('export_killed_weight')).get( 'total_quantity', 0) or 0 value_header_list = [ len(filtered_poultry_hatch), all_chain_company, all_poultry_hatching_quantity, all_losses, all_direct_losses, all_total_losses, all_poultry_hatching_killed_quantity, all_total_killed_weight, all_poultry_hatching_left_over, all_left_over_ninty_percent, min_list[0] if len(min_list) > 0 else '-', min_list[len(min_list) - 1] if len(min_list) > 0 else '-', all_total_commitment, all_governmental_quantity, all_governmental_killed_quantity, all_free_quantity, all_free_killed_quantity, all_out_province_killed_quantity, all_out_province_killed_weight, violation, len(kill_house_requests), first_quantity, first_weight, len(bar_complete_with_kill_house), accepted_real_quantity_final, accepted_real_wight_final, chain_killed_quantity_final, chain_killed_weight_final, ] create_value(worksheet, value_header_list, 3, 5) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_quantity, all_increase_quantity, all_losses, all_direct_losses, all_total_losses, '', '', '', '', all_killed_quantity, all_total_killed_weight, all_left_over, ] create_value(worksheet, list2, l + 3, 1, color='green') elif sheet_name == 'جوجه ریزی بیش از 60 روز': date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date() date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date() filtered_poultry_hatch = PoultryHatching.objects.filter(Q(date__date__gte=date1, date__date__lte=date2) | Q(date__date__lte=date1, archive_date__isnull=True) | Q( date__date__lte=date1, archive_date__gte=date1, archive_date__isnull=False), trash=False, chicken_age__gte=60).select_related( 'poultry', 'poultry__user').order_by( '-chicken_age') excel_options = [ 'ردیف', 'وضعیت', 'شماره مجوز جوجه ریزی', 'شناسه یکتا', 'مجوز بهداشتی جوجه ریزی', 'نام فارم', 'مرغدار', 'بهره برداری', 'مالکیت', 'ارتباط', 'شهر/تعاونی', 'سالن', ' دوره جوجه ریزی', 'تاریخ ثبت جوجه ریزی', 'تاریخ جوجه ریزی', 'میانگین سن کشتار', 'پیشبینی تاریخ کشتار', 'نژاد', 'سن روز', 'سن بایگانی', 'حجم جوجه ریزی', 'حجم افزایشی', 'تلفات دامپزشک(قطعه)', 'تلفات اتحادیه(قطعه)', 'تلفات کل(قطعه)', 'زنجیره/شرکت', 'دامپزشک فارم', 'تلفن دامپزشک فارم', 'کد سیستمی واحد', 'حجم کشتار شده(قطعه)', 'وزن کل کشتارشده(کیلوگرم)', 'مانده در سالن', ] from_date_1 = shamsi_date(date1) from_date_2 = shamsi_date(date2) header_list = [ 'تعداد فارم فعال', 'تعداد فارم دارای زنجیره فعال', 'مجموع جوجه ریزی', 'مجموع تلفات دامپزشک(قطعه)', 'مجموع تلفات اتحادیه(قطعه)', 'مجموع تلفات کل(قطعه)', 'مجموع قطعه کشتار شده', 'مجموع وزن کل کشتارشده', 'مانده در سالن(قطعه)', 'مانده در سالن از نود درصد(قطعه)', 'کمترین سن', 'بیشترین سن', 'مجموع وزن تعهد دولتی', ' مجموع قطعه کشتار دولتی', ' مجموع وزن کشتار دولتی', ' مجموع قطعه کشتار آزاد', ' مجموع وزن کشتار آزاد', 'مجموع تعداد کشتار خارج از استان', 'مجموع وزن کشتار خارج از استان', 'تعداد فارم های متخلف', 'تعداد بار ایجاد شده', 'حجم بار ایجاد شده', 'وزن بار ایجاد شده', 'تعداد بار کشتار شده', 'حجم بار کشتار شده', 'وزن بار کشتار شده', 'حجم زنجیره', 'وزن زنجیره', ] create_header(worksheet, header_list, 5, 2, height=20) excel_description(worksheet, 'B1', 'گزارش جوجه ریزی های بزرگ تر از 60 روز از تاریخ {0} تا {1}'.format(from_date_1, from_date_2), color='red', row2='C3') create_header_freez(worksheet, excel_options, 1, 6, 7, height=22) poultry_ids = filtered_poultry_hatch.values_list('poultry', flat=True).distinct() vet_farms = VetFarm.objects.filter(poultry__in=poultry_ids, trash=False).select_related('vet__user') vet_farm_mapping = { vet_farm.poultry: (vet_farm.vet.user.fullname, vet_farm.vet.user.mobile) for vet_farm in vet_farms } l = 5 m = 1 all_poultry_hatching_quantity = 0 all_poultry_hatching_killed_quantity = 0 all_poultry_hatching_left_over = 0 min_list = [] all_left_over_ninty_percent = 0 violation = 0 all_chain_company = 0 for poultry_hatching in filtered_poultry_hatch: if poultry_hatching.archive == True: archive_age = poultry_hatching.chicken_age else: archive_age = '-' vet_farm_id = poultry_hatching.poultry vet_farm_name, vet_farm_mobile = vet_farm_mapping.get(vet_farm_id, ('-', '-')) all_poultry_hatching_quantity += poultry_hatching.quantity all_poultry_hatching_killed_quantity += poultry_hatching.killed_quantity all_poultry_hatching_left_over += poultry_hatching.left_over if poultry_hatching.chicken_age not in min_list: min_list.append(poultry_hatching.chicken_age) l += 1 create_date = jdatetime.date.fromgregorian( day=poultry_hatching.create_date.day, month=poultry_hatching.create_date.month, year=poultry_hatching.create_date.year ) date = jdatetime.date.fromgregorian( day=poultry_hatching.date.day, month=poultry_hatching.date.month, year=poultry_hatching.date.year ) predicate_date = jdatetime.date.fromgregorian( day=poultry_hatching.predicate_date.day, month=poultry_hatching.predicate_date.month, year=poultry_hatching.predicate_date.year ) if poultry_hatching.predicate_date else '-' date1 = datetime.datetime.strptime(str(poultry_hatching.date), '%Y-%m-%d %H:%M:%S') age = (datetime.datetime.now() - date1).days + 1 left_over_ninty_percent = ((poultry_hatching.quantity * 90) / 100) all_left_over_ninty_percent += left_over_ninty_percent farm_state = 'عادی' if poultry_hatching.violation == True: farm_state = 'متخلف' + ' ' + '(مانده در سالن بیش از حد مجاز)' violation += 1 if poultry_hatching.chain_company: chain_company = poultry_hatching.chain_company.name all_chain_company += 1 else: chain_company = '-' list1 = [ m, farm_state, poultry_hatching.licence_number, poultry_hatching.poultry.breeding_unique_id, poultry_hatching.CertId, poultry_hatching.poultry.unit_name, f'{poultry_hatching.poultry.user.fullname} ({poultry_hatching.poultry.user.mobile})', poultry_hatching.InteractTypeName, poultry_hatching.PersonTypeName, poultry_hatching.UnionTypeName, f'{poultry_hatching.poultry.user.city.name if poultry_hatching.poultry.user.city else "-"} ' f'/ {poultry_hatching.poultry.city_operator if poultry_hatching.poultry.city_operator else "-"}', poultry_hatching.hall, poultry_hatching.period, str(create_date), str(date), poultry_hatching.poultry.killing_ave_age, str(predicate_date), poultry_hatching.chicken_breed, age, archive_age, poultry_hatching.quantity, poultry_hatching.increase_quantity, poultry_hatching.losses, poultry_hatching.direct_losses, poultry_hatching.total_losses, chain_company, vet_farm_name, vet_farm_mobile, poultry_hatching.poultry.system_code, poultry_hatching.killed_quantity, poultry_hatching.total_killed_weight, poultry_hatching.left_over, ] m += 1 create_value(worksheet, list1, l + 1, 1, border_style='thin', different_cell=1, different_value='متخلف' + ' ' + '(وجود فارم فعال دیگر)') min_list = sorted(min_list) all_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('quantity')).get( 'total_quantity', 0) all_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('losses')).get( 'total_quantity', 0) all_direct_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('direct_losses')).get( 'total_quantity', 0) all_total_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_losses')).get( 'total_quantity', 0) all_killed_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('killed_quantity')).get( 'total_quantity', 0) all_left_over = filtered_poultry_hatch.aggregate(total_quantity=Sum('left_over')).get( 'total_quantity', 0) all_total_commitment = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_commitment')).get( 'total_quantity', 0) all_governmental_killed_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('governmental_killed_quantity')).get( 'total_quantity', 0) all_free_killed_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('free_killed_quantity')).get( 'total_quantity', 0) all_total_killed_weight = filtered_poultry_hatch.aggregate( total_quantity=Sum('total_killed_weight')).get( 'total_quantity', 0) all_governmental_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('governmental_quantity')).get( 'total_quantity', 0) all_free_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('free_quantity')).get( 'total_quantity', 0) all_out_province_killed_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('out_province_killed_quantity')).get( 'total_quantity', 0) all_out_province_killed_weight = filtered_poultry_hatch.aggregate( total_quantity=Sum('out_province_killed_weight')).get( 'total_quantity', 0) all_increase_quantity = filtered_poultry_hatch.aggregate( total_quantity=Sum('increase_quantity')).get( 'total_quantity', 0) kill_house_requests = KillHouseRequest.objects.filter(trash=False, province_request__poultry_request__hatching__in=filtered_poultry_hatch) first_quantity = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_quantity')).get( 'total_quantity') or 0 first_weight = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_weight')).get( 'total_quantity') or 0 ware_house_bars = kill_house_requests.filter(ware_house_confirmation=True) ware_house_bars_quantity = ware_house_bars.aggregate(total=Sum('ware_house_accepted_real_quantity'))[ 'total'] or 0 ware_house_bars_weight = ware_house_bars.aggregate(total=Sum('ware_house_accepted_real_weight'))[ 'total'] or 0 ware_house_bars_weight_lose = ware_house_bars.aggregate(total=Sum('weight_loss'))[ 'total'] or 0 bar_complete_with_kill_house = kill_house_requests.filter( assignment_state_archive='True') accepted_real_wight_final = bar_complete_with_kill_house.aggregate( total_quantity=Sum('accepted_real_weight')).get( 'total_quantity') or 0 accepted_real_quantity_final = bar_complete_with_kill_house.aggregate( total_quantity=Sum('accepted_real_quantity')).get( 'total_quantity', 0) or 0 chain_killed_weight_final = filtered_poultry_hatch.aggregate( total_quantity=Sum('chain_killed_weight')).get( 'total_quantity', 0) or 0 chain_killed_quantity_final = filtered_poultry_hatch.aggregate( total_quantity=Sum('chain_killed_quantity')).get( 'total_quantity', 0) or 0 extra_killed_quantity_final = filtered_poultry_hatch.aggregate( total_quantity=Sum('export_killed_quantity')).get( 'total_quantity', 0) or 0 export_killed_weight_final = filtered_poultry_hatch.aggregate( total_quantity=Sum('export_killed_weight')).get( 'total_quantity', 0) or 0 value_header_list = [ len(filtered_poultry_hatch), all_chain_company, all_poultry_hatching_quantity, all_losses, all_direct_losses, all_total_losses, all_poultry_hatching_killed_quantity, all_total_killed_weight, all_poultry_hatching_left_over, all_left_over_ninty_percent, min_list[0] if len(min_list) > 0 else '-', min_list[len(min_list) - 1] if len(min_list) > 0 else '-', all_total_commitment, all_governmental_quantity, all_governmental_killed_quantity, all_free_quantity, all_free_killed_quantity, all_out_province_killed_quantity, all_out_province_killed_weight, violation, len(kill_house_requests), first_quantity, first_weight, len(bar_complete_with_kill_house), accepted_real_quantity_final, accepted_real_wight_final, chain_killed_quantity_final, chain_killed_weight_final, ] create_value(worksheet, value_header_list, 3, 5) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_quantity, all_increase_quantity, all_losses, all_direct_losses, all_total_losses, '', '', '', '', all_killed_quantity, all_total_killed_weight, all_left_over, ] create_value(worksheet, list2, l + 3, 1, color='green') elif sheet_name == 'گزارش بارها': date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date() date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date() filtered_kill_request = KillHouseRequest.objects.filter( trash=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2).order_by( '-create_date').select_related( 'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request', 'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city', 'kill_request__slaughter_house').only('province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'traffic_code', 'assignment_state_archive', 'province_request__poultry_request__hatching__chicken_age', 'killhouse_user__kill_house_operator__user__province__name', 'killhouse_user', 'killhouse_user__name', 'province_request__poultry_request__amount', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__send_date', 'province_kill_request__province_request__poultry_request__Index_weight', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'province_kill_request__province_request__poultry_request__out', 'province_kill_request__kill_house_price', 'price', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'bar_document_status__title').values( 'province_request__poultry_request__poultry__user__fullname', 'province_kill_request__kill_house_price', 'kill_request__export_country', 'province_request__poultry_request__direct_buying', 'province_request__poultry_request__export', 'province_request__poultry_request__freezing', 'document_status', 'ware_house_confirmation', 'ware_house_accepted_real_quantity', 'ware_house_accepted_real_weight', 'weight_loss', 'message', 'province_request__poultry_request__freezing', 'province_request__poultry_request', 'killhouse_user', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__system_address__city__name', 'killhouse_user__killer', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'province_request__poultry_request__poultry', 'province_request__poultry_request__order_code', 'province_request__poultry_request__chicken_breed', 'province_request__poultry_request__poultry__user__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__send_date', 'add_car__driver__driver_name', 'add_car__driver__driver_mobile', 'add_car__driver__type_car', 'add_car__driver__health_code', 'key', 'province_kill_request__province_request__poultry_request__Index_weight', 'clearance_code', 'quantity', 'bar_code', 'accepted_real_weight', 'accepted_real_quantity', 'vet_state', 'vet_accepted_real_quantity', 'vet_accepted_real_weight', 'quarantine_quantity', 'killhouse_user__kill_house_operator__user__province__name', 'province_request__poultry_request__hatching__chicken_age', 'province_request__poultry_request__amount', 'assignment_state_archive', 'traffic_code', 'province_kill_request__province_request__poultry_request__free_sale_in_province', 'province_kill_request__province_request__poultry_request__union', 'province_kill_request__province_request__poultry_request__direct_buying', 'province_kill_request__province_request__poultry_request__out', 'quarantine_code_state', 'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date', 'killer__kill_house_operator__user__mobile', 'killer__name', 'killhouse_user__type', 'killer', 'bar_document_status', 'province_kill_request__kill_house_price', 'price', 'bar_document_status__title' ) filtered_kill_reqs = filtered_kill_request poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values( 'province_request__poultry_request')) .only('quantity', 'Index_weight')).annotate( total_quantity=Sum('quantity'), total_weight=Sum(F('quantity') * F('Index_weight')) ) excel_options = [ 'ردیف', 'کد بار', ' تاریخ کشتار', 'نوع کشتار', 'کدسفارش مرغدار', 'نام و نام خانوادگی مرغدار', 'تلفن مرغدار', ' شهر مرغدار', 'نام فارم', 'فروش', 'سن مرغ', 'قیمت پیشنهادی مرغدار(ریال)', 'قیمت پیشنهادی کشتارگاه(ریال)', 'قیمت تعاونی(ریال)', ' نژاد', 'دامپزشک فارم', 'تلفن دامپزشک فارم', ' ماهیت خریدار', 'خریدار', ' تلفن خریدار', ' آدرس ', 'کشتارکن اختصاصی', 'تلفن کشتارکن اختصاصی', ' محل کشتار ', 'قیمت کشتارگاه(ریال)', 'دامپزشک کشتارگاه ', ' تلفن دامپزشک کشتارگاه ', 'راننده', 'موبایل راننده', 'نوع خودرو', 'کد بهداشتی حمل و نقل', 'تعداد قطعه بار ', 'وزن بار', 'کد رهگیری سامانه قرنطینه', 'تعداد قطعه وارد شده در قرنطینه', 'وضعیت تخلیه', 'تاریخ تخلیه (کشتارگاه)', 'تعداد تخلیه شده دامپزشک', 'وزن بار تخلیه شده(کیلوگرم)دامپزشک', 'تعداد نهایی در کشتارگاه', 'وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'وضعیت', 'وضعیت سند', 'وضعیت ورود انبار', 'تعداد لاشه', 'وزن لاشه', 'درصد افت در لحظه', 'درصد افت ورود به انبار', 'کشور مقصد', 'اختلاف مجوز', ] from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) # worksheet.sheet_view.rightToLeft = True # worksheet.insert_rows(1) # cell = worksheet.cell(row=1, column=1) header_list = [ 'تعداد بارهای ایجاد شده', 'تعداد بارهای دارای کشتارکن اختصاصی', 'حجم بارهای ایجاد شده', 'وزن بارهای ایجاد شده', 'میانگین وزن بارهای ایجاد شده', 'کمترین سن', 'بیشترین سن', 'میانگین سنی', 'تعداد بارهای دارای کد قرنطینه', 'حجم بارهای دارای کد قرنطینه', 'تعداد بار احراز شده از قرنطینه', 'مجموع تعداد قطعه احراز شده از قرنطینه', 'تعداد بار فاقد قرنطینه', 'حجم بار فاقد قرنطینه', ' تعداد بارهایی که در قرنطینه و رصدیار اختلاف دارند', 'تعداد تخلیه شده دامپزشک', 'مجموع تعداد تخلیه شده دامپزشک', 'مجموع وزن تخلیه شده دامپزشک', 'تعداد بارهای تکمیل شده', 'مجموع تعداد نهایی در کشتارگاه', 'مجموع وزن نهایی در کشتار گاه', 'ملاک قطعه کشتار شده', 'ملاک وزن کشتار شده', 'حجم بارها', 'وزن بارها', 'تعداد بار های وارد شده در انبار', 'مجموع تعداد لاشه', 'مجموع وزن لاشه', 'میانگین درصد افت لاشه ورود به انبار', ] header_list2 = [ 'تعداد درخواست مرغداران', ' مجموع تعداد قطعه درخواست مرغداران', ' مجموع وزن درخواست مرغداران', ] header_list3 = [ 'درصد بارهای دارای کد قرنطینه', 'درصد تعداد بارهای احراز شده از قرنطینه', 'درصد تعداد بارهای تکمیل شده کشتارگاه', 'درصد وزن نهایی در کشتارگاه نسبت به وزن کل', 'درصد بارهای فاقد کد قرنطینه', 'درصد بارهای اختلاف دار در قرنطینه و رصدیار', 'درصد تعداد بارهای ورودی به انبار', 'درصد وزن لاشه ها در انبار نسبت به وزن کل', 'درصد وزن لاشه در انبار نسبت به وزن نهایی در کشتارگاه', ] create_header(worksheet, header_list, 9, 2, height=21.8) create_header(worksheet, header_list2, 6, 2, height=21.8, color='green') create_header(worksheet, header_list3, 6, 5, height=43, color='orange', text_color='0D0D0D') create_header_freez(worksheet, excel_options, 1, 8, 9, height=21, len_with=True) excel_description(worksheet, 'B1', 'گزارش بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی', color='red', row2='D1') kill_keys = [kill.get('key') for kill in filtered_kill_reqs] vet_checks = VetCheckRequest.objects.filter( trash=False, kill_house_request__key__in=kill_keys ).only('create_date', 'kill_house_request__key').values( 'create_date', 'kill_house_request__key') assignments = KillHouseAssignmentInformation.objects.filter( kill_house_request__key__in=kill_keys, trash=False ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key') vet_check_mapping = {vc['kill_house_request__key']: vc['create_date'] for vc in vet_checks} assignment_mapping = { assignment.kill_house_request.key: ( int(assignment.net_weight), assignment.real_quantity, assignment.create_date) for assignment in assignments } if filtered_kill_reqs.exists(): name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name'] worksheet['B2'] = f'استان {name}' excel_description(worksheet, 'B2', f'استان {name}', color='red', row2='D2') excel_description(worksheet, 'B3', f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})', row2='D3') l = 8 m = 1 all_age = [] all_real_quantity = 0 all_net_weighte = 0 all_weighte = 0 poultry_ids = [req.get('province_request__poultry_request__poultry') for req in filtered_kill_reqs] vet_farms = VetFarm.objects.filter(poultry__in=poultry_ids, trash=False).select_related('vet__user') vet_farm_mapping = { vet_farm.poultry_id: (vet_farm.vet.user.fullname, vet_farm.vet.user.mobile) for vet_farm in vet_farms } if filtered_kill_reqs: for kill in filtered_kill_reqs: age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if age not in all_age: all_age.append(age) if (kill['assignment_state_archive']) == 'True' or kill[ 'vet_state'] == 'accepted': state = 'تخلیه شده' else: state = 'درانتظار تخلیه' l += 1 vet_farm_id = kill.get('province_request__poultry_request__poultry') vet_farm_name, vet_farm_mobile = vet_farm_mapping.get(vet_farm_id, ('-', '-')) kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'), trash=False).select_related( 'vet__user').only('vet__user__fullname', 'vet__user__mobile').values('vet__user__fullname', 'vet__user__mobile').first() code = kill.get('clearance_code') if kill.get('clearance_code') else '-' if kill.get('quantity'): quantity = kill.get('quantity') else: quantity = '-' send_date = kill.get('province_request__poultry_request__send_date') date_of_poultry_request = convert_to_shamsi(year=send_date.year, month=send_date.month, day=send_date.day, ) killers = 'کشتارکن' name_killer_exclusive = '-' mobile_killer_exclusive = '-' if kill.get('killhouse_user__killer') == False: killers = 'کشتارگاه' if kill.get('killer') != None: name_killer_exclusive = kill['killer__name'] mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile']) key = kill.get('key') kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-' kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-' if kill['assignment_state_archive'] == 'True' or kill['ware_house_confirmation'] == True: net_weighte = kill['accepted_real_weight'] real_quantity = kill['accepted_real_quantity'] else: net_weighte = 0 real_quantity = 0 net_weighte2, real_quantity2, vet_check_date = assignment_mapping.get(key, ('-', '-', None)) all_real_quantity += real_quantity if real_quantity != '-' else 0 all_net_weighte += net_weighte if net_weighte != '-' else 0 vet_check_date = vet_check_mapping.get(key, vet_check_date) date_of_inner_bar = convert_to_shamsi(datetime=vet_check_date) if vet_check_date else '-' if kill.get('kill_request__slaughter_house') is not None: kill_place = kill.get('kill_request__slaughter_house__name') else: kill_place = '-' vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-' vet_wight = int(kill['vet_accepted_real_weight']) if kill['vet_accepted_real_weight'] else '-' weight = int(kill.get('quantity') * kill.get( 'province_kill_request__province_request__poultry_request__Index_weight')) quarantine_quantity = '-' if kill['quarantine_quantity'] != None: quarantine_quantity = kill['quarantine_quantity'] else: if kill['quarantine_code_state'] == 'contradiction': quarantine_quantity = 'مغایرت کد رهگیری' elif kill['quarantine_code_state'] == 'noclearance': quarantine_quantity = 'فاقد کد رهگیری' elif kill['quarantine_code_state'] == 'notconfirmed': quarantine_quantity = 'عدم تایید راهداری' elif kill['quarantine_code_state'] == 'merge': quarantine_quantity = 'ادغام' export_country = '-' sale_type = 'دولتی' if kill[ 'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد' if kill['province_kill_request__province_request__poultry_request__out'] == True: type = 'خارج از استان' elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True: type = 'خرید مستقیم' elif kill['province_request__poultry_request__freezing'] == True: type = 'انجماد' elif kill['province_request__poultry_request__export'] == True: type = 'صادرات' export_country = kill['kill_request__export_country'] else: type = 'عادی' age = (kill.get('province_request__poultry_request__send_date').date() - kill.get('province_request__poultry_request__hatching__date').date()).days + 1 if kill['message'] is not None: state_delete = 'بار حذف شده' else: state_delete = 'فعال' all_weighte += weight ware_house_accepted_real_quantity = kill['ware_house_accepted_real_quantity'] ware_house_accepted_real_weight = kill['ware_house_accepted_real_weight'] weight_loss = round(kill['weight_loss'], 2) if kill['weight_loss'] > 0 else 0 if kill['ware_house_confirmation'] == True: state_ware_house_confirmation = 'ورود به انبار' else: state_ware_house_confirmation = '-' weight_loss1 = kill['accepted_real_weight'] - kill['ware_house_accepted_real_weight'] if kill[ 'ware_house_accepted_real_weight'] > 0 else 0 if weight_loss1 < 0: weight_loss1 = weight_loss1 * -1 total_weight_loss = int((weight_loss1 / kill['accepted_real_weight']) * 100) if kill[ 'accepted_real_weight'] > 0 else 0 defreent_quarantine = kill['accepted_real_quantity'] - quarantine_quantity if kill[ 'quarantine_quantity'] != None else 0 list1 = [ m, str(kill.get('bar_code')), str(date_of_poultry_request), type, str(kill.get('province_request__poultry_request__order_code')), kill.get('province_request__poultry_request__poultry__user__fullname'), str(kill.get('province_request__poultry_request__poultry__user__mobile')), kill.get('province_request__poultry_request__poultry__user__city__name'), kill.get('province_request__poultry_request__poultry__unit_name'), sale_type, age, kill.get('province_request__poultry_request__amount') if kill.get( 'province_request__poultry_request__amount') else '-', kill.get('province_kill_request__kill_house_price') if kill.get( 'province_kill_request__kill_house_price') else '-', kill.get('price') if kill.get( 'price') else '-', kill.get('province_request__poultry_request__chicken_breed'), vet_farm_name, vet_farm_mobile, killers, kill.get('killhouse_user__name'), kill.get('killhouse_user__kill_house_operator__user__mobile'), kill.get('killhouse_user__system_address__city__name'), name_killer_exclusive, mobile_killer_exclusive, kill_place, kill.get('province_kill_request__kill_house_price'), kill_house_vet_name, kill_house_vet_mobile, kill.get('add_car__driver__driver_name'), kill.get('add_car__driver__driver_mobile'), kill.get('add_car__driver__type_car'), str(kill.get('traffic_code')), quantity, weight, code, quarantine_quantity, state, str(date_of_inner_bar), vet_quantity, vet_wight, real_quantity, net_weighte, kill['accepted_real_quantity'], round(kill['accepted_real_weight'], 1), state_delete, kill['bar_document_status__title'] if kill['bar_document_status'] else '-', state_ware_house_confirmation, ware_house_accepted_real_quantity, int(ware_house_accepted_real_weight), f'%{round(total_weight_loss, 2)}', f'%{weight_loss}', export_country, kill['accepted_real_quantity'] - quarantine_quantity if kill[ 'quarantine_quantity'] != None else quarantine_quantity ] if defreent_quarantine < 0: different_cell = 51 different_value = 'اختلاف مجوز' else: different_cell = None different_value = None m += 1 create_value(worksheet, list1, l, 1, height=20, different_cell=different_cell, different_value=different_value) killer_exclusive = len(filtered_kill_reqs.filter(killer__isnull=False)) all_state_ware_house_confirmation = len(filtered_kill_reqs.filter(ware_house_confirmation=True)) total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] or 0 total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0 aggregate_filtered_kill_reqs = filtered_kill_reqs.aggregate( total_accepted_real_quantity=Sum('accepted_real_quantity'), total_accepted_real_weight=Sum('accepted_real_weight'), total_quantity=Sum('quantity'), total_vet_accepted_real_quantity=Sum('vet_accepted_real_quantity'), total_vet_accepted_real_weight=Sum('vet_accepted_real_weight'), total_quarantine_quantity=Sum('quarantine_quantity'), total_ware_house_accepted_real_quantity=Sum('ware_house_accepted_real_quantity'), total_ware_house_accepted_real_weight=Sum('ware_house_accepted_real_weight'), total_weight_loss=Sum('weight_loss'), ) all_vet_state_accepted = len( filtered_kill_reqs.filter(vet_state='accepted')) bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True') accepted_real_quantity = aggregate_filtered_kill_reqs['total_accepted_real_quantity'] or 0 accepted_real_wight = aggregate_filtered_kill_reqs['total_accepted_real_weight'] or 0 all_kill_request_quantity = aggregate_filtered_kill_reqs['total_quantity'] or 0 all_quarantine_quantity = aggregate_filtered_kill_reqs['total_quarantine_quantity'] or 0 all_vet_accepted_real_quantity = aggregate_filtered_kill_reqs['total_vet_accepted_real_quantity'] or 0 all_vet_accepted_real_weight = aggregate_filtered_kill_reqs['total_vet_accepted_real_weight'] or 0 has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False)) all_ware_house_accepted_real_quantity = aggregate_filtered_kill_reqs[ 'total_ware_house_accepted_real_quantity'] or 0 all_ware_house_accepted_real_weight = aggregate_filtered_kill_reqs[ 'total_ware_house_accepted_real_weight'] or 0 all_weight_loss = aggregate_filtered_kill_reqs['total_weight_loss'] or 0 has_code1 = filtered_kill_reqs.filter(clearance_code__isnull=False).aggregate( total_quantity=Sum('quantity'), ) all_quarantine_quantity_has_code = has_code1['total_quantity'] or 0 hasnt_code1 = filtered_kill_reqs.filter(clearance_code__isnull=True) hasnt_code = hasnt_code1.aggregate( total_quantity=Sum('quantity') ) all_quarantine_quantity_hasnt_code = hasnt_code['total_quantity'] or 0 difference_bar = len(filtered_kill_reqs.filter( Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')))) all_weight_loss = round(int(all_weight_loss) / all_state_ware_house_confirmation, 2) if all_weight_loss > 0 else 0 all_age1 = sorted(all_age) has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False)) province_kill_request = ProvinceKillRequest.objects.filter( pk__in=filtered_kill_reqs.values( 'province_kill_request')).aggregate( total_quantity_melak=Sum('total_killed_quantity'), total_weight_melak=Sum('total_killed_weight'), ) accepted_real_quantity_melak = province_kill_request['total_quantity_melak'] or 0 accepted_real_wight_melak = province_kill_request['total_weight_melak'] or 0 value_header_list = [ len(poultry_request), total_requests_quantity, int(total_requests_weight), len(filtered_kill_reqs), killer_exclusive, all_kill_request_quantity, int(all_weighte), round(all_weighte / all_kill_request_quantity, 1) if all_weighte > 0 and all_kill_request_quantity > 0 else 0, all_age1[0] if len(all_age1) > 0 else '-', all_age1[len(all_age1) - 1] if len(all_age1) > 0 else '-', int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-', has_code, all_quarantine_quantity_has_code, has_qarantine, all_quarantine_quantity, len(hasnt_code1), all_quarantine_quantity_hasnt_code, difference_bar, all_vet_state_accepted, all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), len(bar_complete), all_real_quantity, int(all_net_weighte), accepted_real_quantity_melak, accepted_real_wight_melak, accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, all_state_ware_house_confirmation, all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), f'%{all_weight_loss}' ] create_value(worksheet, value_header_list, 3, 6) value_header_list2 = [ f'%{round((has_code * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((has_qarantine * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((len(bar_complete) * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((int(all_net_weighte) * 100) / int(all_weighte), 2) if int(all_weighte) > 0 else 0}', f'%{round((len(hasnt_code1) * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((difference_bar * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((all_state_ware_house_confirmation * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}', f'%{round((int(all_ware_house_accepted_real_weight) * 100) / int(all_weighte), 2) if int(all_weighte) > 0 else 0}', f'%{round((int(all_ware_house_accepted_real_weight) * 100) / int(all_net_weighte), 2) if int(all_net_weighte) > 0 else 0}' ] create_value(worksheet, value_header_list2, 6, 6) list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', all_kill_request_quantity, int(all_weighte), '', all_quarantine_quantity if all_quarantine_quantity != None else 0, '', '', all_vet_accepted_real_quantity, int(all_vet_accepted_real_weight), all_real_quantity, int(all_net_weighte), accepted_real_quantity if accepted_real_quantity != None else 0, int(accepted_real_wight) if accepted_real_wight != None else 0, '', '', '', all_ware_house_accepted_real_quantity, int(all_ware_house_accepted_real_weight), '', '', '', '', ] create_value(worksheet, list2, l + 3, 1, color='green') elif sheet_name == 'اطلاعات کشتار روزانه': date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date() date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date() header_list = [ 'ردیف', 'تاریخ', 'حجم درخواست کشتار مرغدار', 'وزن درخواست کشتار مرغدار', 'حجم خرید های مستقیم', 'وزن خرید های مستقیم', 'حجم خرید های خارج از استان (زنده)', 'وزن خرید های خارج از استان (زنده)', 'وزن خرید های خارج از استان (لاشه)', 'حجم کل تخصیصات (خرید مستقیم/ مرغدار)', 'وزن کل تخصیصات (خرید مستقیم/ مرغدار)', 'حجم فروش به خارج استان', 'وزن فروش به خارج استان', 'حجم بارها', 'وزن بارها', 'لاشه تولیدی امروز با احتساب 25درصد افت کشتار' ] create_header(worksheet, header_list, 1, 3, height=25, width=25, border_style='thin', color='C00000') excel_description(worksheet, 'A1', 'گزارش کشتار روزانه استان از تاریخ {0} تا {1}'.format(from_date_1, from_date_2), color='red', row2='E1') m = 1 l = 4 current_date = date1 for day in range((date2 - date1).days + 1): kill_house_free_bar = KillHouseFreeBarInformation.objects.filter( trash=False, archive_wage=False, date__date=current_date ).only( 'quantity', 'live_weight', 'number_of_carcasses', 'weight_of_carcasses', 'send_date', 'type', 'out' ) kill_house_free_bar_aggregates = kill_house_free_bar.aggregate( total_quantity_live=Sum('quantity', filter=Q(create_date__date=current_date, buy_type='live')), total_weight_live=Sum('live_weight', filter=Q(create_date__date=current_date, buy_type='live')), total_quantity_carcass=Sum('number_of_carcasses', filter=Q(date__date=current_date, buy_type='carcass')), total_weight_carcass=Sum('weight_of_carcasses', filter=Q(date__date=current_date, buy_type='carcass')), warehouse_total_weight_carcass=Sum('weight_of_carcasses', filter=Q(date__date=current_date)), ) poultry_request = PoultryRequest.objects.filter( trash=False, state_process__in=('pending', 'accepted'), province_state__in=('pending', 'accepted'), out_province_request_cancel=False, temporary_trash=False, temporary_deleted=False, send_date__date=current_date ).only( 'quantity', 'Index_weight', 'send_date' ) poultry_request_aggregates = poultry_request.aggregate( total_quantity=Sum('quantity', filter=Q(send_date__date=current_date, direct_buying=False, out=False)), total_weight=Sum(F('quantity') * F('Index_weight'), filter=Q(send_date__date=current_date, direct_buying=False, out=False)), total_direct_buying_quantity=Sum('quantity', filter=Q(send_date__date=current_date, direct_buying=True)), total_direct_buying_weight=Sum(F('quantity') * F('Index_weight'), filter=Q(send_date__date=current_date, direct_buying=True)), poultry_out_province_quantity=Sum('quantity', filter=Q(out=True, send_date__date=current_date)), poultry_out_province_weight=Sum(F('quantity') * F('Index_weight'), filter=Q(out=True, send_date__date=current_date)), total_killing_ave_weight=Avg('Index_weight', filter=Q(send_date__date=current_date)), # yesterday total_killing_ave_weight_yesterday=Avg('Index_weight', filter=Q(send_date__date=current_date)) ) province_kill_request = ProvinceKillRequest.objects.filter( trash=False, archive_wage=False, return_to_province=False, state__in=('pending', 'accepted'), kill_request__recive_date__date=current_date ).only( 'total_killed_quantity', 'total_killed_weight', 'kill_request__recive_date' ) province_kill_request_aggregates = province_kill_request.aggregate( total_quantity=Sum('total_killed_quantity', filter=Q(kill_request__recive_date__date=current_date)), total_weight_carcass=Sum('total_killed_weight', filter=Q(kill_request__recive_date__date=current_date)) * 0.75, province_kill_request_total_weight=Sum('total_killed_weight', filter=Q(kill_request__recive_date__date=current_date)), ) kill_house_request = KillHouseRequest.objects.filter( trash=False, kill_request__recive_date__date=current_date, temporary_trash=False, temporary_deleted=False ).select_related('kill_request').only( 'ware_house_accepted_real_weight', 'weight_loss', 'ware_house_confirmation', 'kill_request__recive_date' ) kill_house_request_aggregates = kill_house_request.aggregate( total_quantity=Sum( 'accepted_real_quantity', filter=Q(kill_request__recive_date__date=current_date) ), total_weight=Sum( 'accepted_real_weight', filter=Q(kill_request__recive_date__date=current_date) ) ) province_kill_request_weight = province_kill_request_aggregates[ 'province_kill_request_total_weight'] or 0 bars_live_weight = kill_house_free_bar_aggregates['total_weight_live'] or 0 bars_carcasses_weight = kill_house_free_bar_aggregates['total_weight_carcass'] or 0 total_loss_weight = int( ((province_kill_request_weight + bars_live_weight) * 0.75) + bars_carcasses_weight) list1 = [ m, str(shamsi_date(current_date, in_value=True)), poultry_request_aggregates.get('total_quantity') or 0, poultry_request_aggregates.get('total_weight') or 0, poultry_request_aggregates.get('total_direct_buying_quantity') or 0, poultry_request_aggregates.get('total_direct_buying_weight') or 0, kill_house_free_bar_aggregates.get('total_quantity_live') or 0, kill_house_free_bar_aggregates.get('total_weight_live') or 0, kill_house_free_bar_aggregates.get('total_weight_carcass') or 0, province_kill_request_aggregates.get('total_quantity') or 0, int(province_kill_request_aggregates.get('province_kill_request_total_weight') or 0), poultry_request_aggregates.get('poultry_out_province_quantity') or 0, poultry_request_aggregates.get('poultry_out_province_weight') or 0, kill_house_request_aggregates.get('total_quantity') or 0, kill_house_request_aggregates.get('total_weight') or 0, int(total_loss_weight or 0) ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 current_date += datetime.timedelta(days=1) city_operators = CityOperator.objects.filter(trash=False) all_admin_all_violation = 0 city_operator_name = city_operators.values_list('user__fullname', flat=True).distinct() city_operator_all_violation_all = PoultryHatching.objects.filter(trash=False, violation_reporter__isnull=False, violation_reporter__in=city_operator_name).count() row_list = l + 7 row_city = l + 5 len_poultry = 0 len_all_hatching = 0 all_hathcing_quantitya_all = 0 all_province_requests_quantity = 0 all_province_requests_weight = 0 len_hatching = 0 all_hatching_quantity = 0 all_hatching_lest_over = 0 all_out_poultry_request_quantity = 0 all_out_poultry_request_weight = 0 city_operator_poultry_request_quantity_all = 0 city_operator_poultry_request_weight_all = 0 direct_bying_poultry_request_quantity_all = 0 direct_bying_poultry_request_weight_all = 0 province_operaor_poultry_request_quantity_all = 0 province_operaor_poultry_request_weight_all = 0 row_list2 = l + 2 worksheet[f'D{row_list2}'] = f'اطلاعات کشتار به تفکیک تعاونی ها از تاریخ {from_date_1} تا {from_date_2}' worksheet[f'D{row_list2}'].font = Font(color="C00000", bold=True, size=12) worksheet[f'D{row_list2}'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = f'D{row_list2}:J{row_list2 + 1}' worksheet.merge_cells(merge_range1) for city_operator in city_operators: poultry_request = PoultryRequest.objects.filter(trash=False, out_province_request_cancel=False, province_state='accepted', poultry__city_operator=city_operator.unit_name) poultry = Poultry.objects.filter(trash=False, city_operator=city_operator.unit_name) out_poultry_request = poultry_request.filter(out=True) city_operator_poultry_request = poultry_request.filter(direct_buying=False, registrar__role='CityOperator') province_operaor_poultry_request = poultry_request.filter(~Q(registrar__role='CityOperator'), direct_buying=False) direct_bying_poultry_request = poultry_request.filter(direct_buying=True) province_requests = ProvinceKillRequest.objects.filter(trash=False, province_request__poultry_request__poultry__city_operator=city_operator.unit_name , return_to_province=False, state__in=('accepted', 'pending')) province_requests_quantity = \ province_requests.aggregate( total=Sum('total_killed_quantity'))[ 'total'] or 0 province_requests_weight = \ province_requests.aggregate( total=Sum('total_killed_weight'))[ 'total'] or 0 kill_requests = KillHouseRequest.objects.filter(trash=False, province_kill_request__in=province_requests) all_hatching = PoultryHatching.objects.filter(trash=False, poultry__in=poultry) all_violation = all_hatching.filter(violation_reporter__isnull=False) city_operator_all_violation = all_violation.filter( violation_reporter=city_operator.user.fullname).count() admin_all_violation = all_violation.filter(~Q(violation_reporter=city_operator.user.fullname)).count() hathcing_quantity_all = \ all_hatching.aggregate( total=Sum(F('quantity')))[ 'total'] or 0 out_poultry_request_quantity_all = \ out_poultry_request.aggregate( total=Sum(F('quantity')))[ 'total'] or 0 out_poultry_request_weight_all = \ out_poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 hatching = all_hatching.filter(archive=False, allow_hatching='pending') hatching_quantity = \ hatching.aggregate( total=Sum('quantity'))[ 'total'] or 0 hatching_lest_over = \ hatching.aggregate( total=Sum('left_over'))[ 'total'] or 0 city_operator_poultry_request_quantity = \ city_operator_poultry_request.aggregate( total=Sum('quantity'))[ 'total'] or 0 city_operator_poultry_request_weight = \ city_operator_poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 direct_bying_poultry_request_quantity = \ direct_bying_poultry_request.aggregate( total=Sum('quantity'))[ 'total'] or 0 direct_bying_poultry_request_weight = \ direct_bying_poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 province_operaor_poultry_request_quantity = \ province_operaor_poultry_request.aggregate( total=Sum('quantity'))[ 'total'] or 0 province_operaor_poultry_request_weight = \ province_operaor_poultry_request.aggregate( total=Sum(F('quantity') * F('Index_weight')))[ 'total'] or 0 all_admin_all_violation += admin_all_violation len_poultry += len(poultry) len_all_hatching += len(all_hatching) all_hathcing_quantitya_all += hathcing_quantity_all all_province_requests_quantity += province_requests_quantity all_province_requests_weight += province_requests_weight len_hatching += len(hatching) all_hatching_quantity += hatching_quantity all_hatching_lest_over += hatching_lest_over all_out_poultry_request_quantity += out_poultry_request_quantity_all all_out_poultry_request_weight += out_poultry_request_weight_all province_requests_date = province_requests.filter( province_request__poultry_request__send_date__date__gte=date1 , province_request__poultry_request__send_date__date__lte=date2, province_request__poultry_request__poultry__city_operator=city_operator.unit_name ) city_operator_poultry_request_quantity_all += city_operator_poultry_request_quantity city_operator_poultry_request_weight_all += city_operator_poultry_request_weight direct_bying_poultry_request_quantity_all += direct_bying_poultry_request_quantity direct_bying_poultry_request_weight_all += direct_bying_poultry_request_weight province_operaor_poultry_request_quantity_all += province_operaor_poultry_request_quantity province_operaor_poultry_request_weight_all += province_operaor_poultry_request_weight list2 = [ 'ردیف', 'ماهیت', 'خریدار', 'نام و نام خانوادگی مالک', 'تلفن مالک', 'شهر', 'تعداد سفارش', 'حجم سفارش', 'تعداد بار ', 'حجم بار', 'وزن بار', 'وزن لاشه', ] for col_num, option in enumerate(list2, 2): col_letter = get_column_letter(col_num) cell = worksheet.cell(row=row_list, column=col_num, value=option) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.fill = PatternFill(start_color="31869B", fill_type="solid") cell.font = Font(size=10, bold=True, color='FFFFFF') if option in ['تعداد سفارش', 'حجم سفارش', 'تعداد بار ', 'حجم بار', 'وزن بار', 'وزن لاشه']: cell.fill = PatternFill(start_color="FF0000", fill_type="solid") # worksheet.row_dimensions[row_list].height = 35 worksheet.column_dimensions[col_letter].width = 17 cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) m = 1 kill_houses1 = province_requests_date.values_list('killhouse_user', flat=True).distinct() kill_houses = KillHouse.objects.filter(id__in=kill_houses1) len_province_requests_kill = 0 all_province_quantity = 0 len_kill_requests_date = 0 all_accepted_assignment_real_quantity = 0 all_accepted_assignment_real_weight = 0 all_ware_house_accepted_real_weight = 0 for kill_house in kill_houses: province_requests_kill = province_requests_date.filter(killhouse_user=kill_house) province_quantity = \ province_requests_kill.aggregate( total=Sum('main_quantity'))[ 'total'] or 0 kill_requests_date = kill_requests.filter(kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, killhouse_user=kill_house, province_kill_request__in=province_requests_kill) accepted_assignment_real_quantity = \ kill_requests_date.aggregate( total=Sum('accepted_real_quantity'))[ 'total'] or 0 accepted_assignment_real_weight = \ kill_requests_date.aggregate( total=Sum('accepted_real_weight'))[ 'total'] or 0 len_province_requests_kill += len(province_requests_kill) all_province_quantity += province_quantity len_kill_requests_date += len(kill_requests_date) all_accepted_assignment_real_quantity += accepted_assignment_real_quantity all_accepted_assignment_real_weight += int(accepted_assignment_real_weight) all_ware_house_accepted_real_weight += int(accepted_assignment_real_weight) * 0.75 # killer='کشتارگاه' if kill_house.killer == False else 'کشتارکن' if kill_house.killer == True and kill_house.type == 'exclusive': parent = KillHousePercentage.objects.get(kill_house=kill_house, trash=False) killer_type = f'کشتارکن اختصاصی {parent.kill_house_for_killer.name}' elif kill_house.killer == True and kill_house.type == 'public': killer_type = 'کشتارکن عمومی' else: killer_type = 'کشتارگاه' list1 = [ m, killer_type, kill_house.name, kill_house.kill_house_operator.user.fullname, kill_house.kill_house_operator.user.mobile, kill_house.kill_house_operator.user.city.name, len(province_requests_kill), province_quantity, len(kill_requests_date), accepted_assignment_real_quantity, int(accepted_assignment_real_weight), int(accepted_assignment_real_weight) * 0.75, ] for item in range(len(list1)): cell = worksheet.cell(row=row_list + 1, column=item + 2, value=list1[item]) cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) cell.font = Font(size=10, bold=True) cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid") value = list1[item] # Check if the value is a number before formatting if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.border = openpyxl.styles.Border( left=openpyxl.styles.Side(style='thin'), right=openpyxl.styles.Side(style='thin'), top=openpyxl.styles.Side(style='thin'), bottom=openpyxl.styles.Side(style='thin') ) row_list += 1 m += 1 else: row_list += 5 worksheet[f'F{row_city}'] = f'{city_operator.unit_name}' worksheet[f'F{row_city}'].font = Font(color="C00000", bold=True, size=12) worksheet[f'F{row_city}'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) merge_range1 = f'F{row_city}:H{row_city + 1}' worksheet.merge_cells(merge_range1) row_city += len(kill_houses) + 5 list2 = [ 'مجموع==>', '', '', '', '', '', len_province_requests_kill, all_province_quantity, len_kill_requests_date or 0, all_accepted_assignment_real_quantity or 0, all_accepted_assignment_real_weight or 0, all_ware_house_accepted_real_weight or 0, ] for item in range(len(list2)): cell = worksheet.cell(row=row_city - 2, column=item + 2, value=list2[item]) value = list2[item] cell.font = Font(size=10, bold=True, color='FFFFFF') if isinstance(value, (int, float)): cell.number_format = '#,###' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'عملکرد خریداران': kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list( 'kill_house', flat=True) kill_houses = KillHouse.objects.filter(out_province=False, active=True, trash=False).exclude( id__in=kill_house_ids).order_by( 'id') serializer = KillHouseForPerformanceDashboardSerializer(kill_houses, many=True, context={'date1': date1, 'date2': date2, }).data excel_options = [ 'ردیف', 'ماهیت', 'کشتارگاه / کشتارکن', 'مالک', 'شهر', 'تعداد بارهای داخل استان', 'حجم بارهای داخل استان', 'وزن بارهای داخل استان', 'تعداد بارهای خارج استان', 'حجم بارهای خارج استان', 'وزن بارهای خارج استان', 'حجم تخصیصات بدون بار', 'حجم کل بارها', 'وزن کل بارها', 'میانگین وزن', 'حجم وارد شده به انبار', 'وزن وارد شده به انبار', 'حجم وارد نشده به انبار', 'وزن وارد نشده به انبار' ] from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) create_header(worksheet, excel_options, 1, 2, height=25, width=25, border_style='thin', color='C00000') worksheet['B1'] = f'اطلاعات کشتار زنده کشتارگاه' worksheet['E1'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = 'B1:D1' merge_range2 = 'E1:H1' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range2) worksheet['B1'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") l = 2 m = 1 if serializer: for data in serializer: list1 = [ m, # ردیف 'کشتارگاه' if data['killer'] else 'کشتارکن', # ماهیت data['name'], # کشتارگاه / کشتارکن data['kill_house_operator']['user']['fullname'], # مالک data['kill_house_operator']['user']['city'], # شهر data['killing_info']['kill_house_requests_count'], # تعداد بارهای داخل استان data['killing_info']['kill_house_requests_quantity'], # حجم بارهای داخل استان data['killing_info']['kill_house_requests_weight'], # وزن بارهای داخل استان data['killing_info']['kill_house_free_bar_count'], # تعداد بارهای خارج استان data['killing_info']['kill_house_free_bar_quantity'], # حجم بارهای خارج استان data['killing_info']['kill_house_free_bar_weight'], # وزن بارهای خارج استان data['killing_info']['province_kill_requests_quantity'], # حجم تخصیصات بدون بار data['killing_info']['total_quantity'], # حجم کل بارها data['killing_info']['total_weight'], # وزن کل بارها data['killing_info']['total_avg_weight'], # میانگین وزن data['killing_info']['kill_house_requests_ware_house_true_quantity'], # حجم وارد شده به انبار data['killing_info']['kill_house_requests_ware_house_true_weight'], # وزن وارد شده به انبار data['killing_info']['kill_house_requests_ware_house_false_quantity'], # حجم وارد نشده به انبار data['killing_info']['kill_house_requests_ware_house_false_weight'] # وزن وارد نشده به انبار ] m += 1 create_value(worksheet, list1, l + 1, 1) l += 1 total_province_kill_requests_count = sum( data['killing_info']['kill_house_requests_count'] for data in serializer) total_province_kill_requests_quantity = sum( data['killing_info']['kill_house_requests_quantity'] for data in serializer) total_province_kill_requests_weight = sum( data['killing_info']['kill_house_requests_weight'] for data in serializer) total_kill_house_requests_count = sum( data['killing_info']['kill_house_free_bar_count'] for data in serializer) total_kill_house_requests_quantity = sum( data['killing_info']['kill_house_free_bar_quantity'] for data in serializer) total_kill_house_requests_weight = sum( data['killing_info']['kill_house_free_bar_weight'] for data in serializer) total_quantity = sum(data['killing_info']['province_kill_requests_quantity'] for data in serializer) total_kill_house_free_bar_quantity = sum( data['killing_info']['total_quantity'] for data in serializer) total_kill_house_free_bar_weight = sum( data['killing_info']['total_weight'] for data in serializer) total_avg_weight = sum(data['killing_info']['total_avg_weight'] for data in serializer) / len( serializer) if serializer else 0 total_ware_house_true_quantity = sum( data['killing_info']['kill_house_requests_ware_house_true_quantity'] for data in serializer) total_ware_house_true_weight = sum( data['killing_info']['kill_house_requests_ware_house_true_weight'] for data in serializer) total_ware_house_false_quantity = sum( data['killing_info']['kill_house_requests_ware_house_false_quantity'] for data in serializer) total_ware_house_false_weight = sum( data['killing_info']['kill_house_requests_ware_house_false_weight'] for data in serializer) # لیست مجموع مقادیر list2 = [ 'مجموع==>', '', '', '', '', total_province_kill_requests_count, total_province_kill_requests_quantity, total_province_kill_requests_weight, total_kill_house_requests_count, total_kill_house_requests_quantity, total_kill_house_requests_weight, total_quantity, total_kill_house_free_bar_quantity, total_kill_house_free_bar_weight, total_avg_weight, total_ware_house_true_quantity, total_ware_house_true_weight, total_ware_house_false_quantity, total_ware_house_false_weight ] for item in range(len(list2)): cell = worksheet.cell(row=l + 2, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list( 'kill_house', flat=True) kill_houses = KillHouse.objects.filter(out_province=False, active=True, trash=False).exclude( id__in=kill_house_ids).order_by( 'id') kill_houses = kill_houses.annotate( allocation_count=Count( 'kill_house_steward_allocation', filter=Q(kill_house_steward_allocation__receiver_state__in=['pending', 'accepted']) ) ).order_by( '-allocation_count' ) new_serializer = KillHouseForProvinceWareHouseDashboardSerializer(kill_houses, many=True, context={'request': request}).data excel_options = [ 'ردیف', 'خریدار', 'ماهیت', 'شهر', 'مانده انبار فعلی', 'وزن کل فروش (لاشه)', 'وزن فروش داخل استان (لاشه)', 'وزن فروش خارج استان (لاشه)' ] from_date_1 = shamsi_date(date1) to_date_1 = shamsi_date(date2) cell = worksheet.cell(row=1, column=1) cell.alignment = Alignment(horizontal='center', vertical='center') red_font = Font(color="C00000", bold=True) new_l = l + 6 create_header(worksheet, excel_options, 1, new_l, height=25, width=25, border_style='thin', color='C00000') new_m = 1 worksheet[f'B{new_l - 1}'] = f'اطلاعات توزیع گوشت مرغ کشتارگاه' worksheet[f'E{new_l - 1}'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})' worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center') worksheet[f'B{new_l - 1}'].alignment = Alignment(horizontal='center', vertical='center') worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center') merge_range1 = f'B{new_l - 1}:D{new_l - 1}' merge_range2 = f'E{new_l - 1}:H{new_l - 1}' worksheet.merge_cells(merge_range1) worksheet.merge_cells(merge_range2) worksheet[f'B{new_l - 1}'].font = red_font worksheet['B3'].font = Font(size=11) worksheet['B2'].font = Font(size=10, bold=True, color="C00000") if new_serializer: for data in new_serializer: list1 = [ new_m, # ردیف data['name'], # خریدار 'کشتارگاه' if data['killer'] else 'کشتارکن', # ماهیت data['kill_house_operator']['user']['city']['name'], # شهر data['ware_house_info']['product_remain_weight'], # مانده انبار فعلی data['ware_house_info']['total_sell'], # وزن کل فروش (لاشه) data['ware_house_info']['total_kill_house_allocations_weight'], # وزن فروش داخل استان (لاشه) data['ware_house_info']['total_kill_house_free_sale__bar_carcasses_weight'] # وزن فروش خارج استان (لاشه) ] new_m += 1 create_value(worksheet, list1, new_l + 1, 1) new_l += 1 total_inventory = sum(data['ware_house_info']['product_remain_weight'] for data in new_serializer) total_sales = sum(data['ware_house_info']['total_sell'] for data in new_serializer) total_in_province = sum( data['ware_house_info']['total_kill_house_allocations_weight'] for data in new_serializer) total_out_province = sum( data['ware_house_info']['total_kill_house_free_sale__bar_carcasses_weight'] for data in new_serializer) list2 = [ 'مجموع ==>', '', '', '', total_inventory, total_sales, total_in_province, total_out_province ] for item in range(len(list2)): cell = worksheet.cell(row=new_l + 2, column=item + 1, value=list2[item]) value = list2[item] if isinstance(value, (int, float)): if value != 0: cell.number_format = '#,##0' # Apply general number format else: cell.value = value # Keep as text for other values cell.alignment = Alignment(horizontal='center') cell.font = Font(size=10, bold=True) cell.font = Font(bold=True) cell.fill = PatternFill(start_color="00B050", fill_type="solid") elif sheet_name == 'گزارش سند ها': date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() kill_houses = KillHouse.objects.filter(trash=False, out_province=False).order_by('id') kill_house_request = KillHouseRequest.objects.filter(trash=False, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, temporary_trash=False, temporary_deleted=False) bar_duc = BarDocumentStatus.objects.filter(trash=False).order_by('id').values_list('title', flat=True) excel_options = [ 'ردیف', 'نام گشتارگاه', 'تلفن', 'شهر', 'تعداد کل بار', 'بارهای دارای سند', 'بارهای فاقد سند', *bar_duc ] from_date_1 = shamsi_date(date1) from_date_2 = shamsi_date(date2) excel_description(worksheet, 'B1', 'گزارش سند ها از تاریخ {0} تا {1}'.format(from_date_1, from_date_2), color='red', row2='C3') create_header_freez(worksheet, excel_options, 1, 6, 7, height=22) l = 5 m = 1 total_counts = {title: 0 for title in bar_duc} for kill_house in kill_houses: kill_house_request1 = kill_house_request.filter( trash=False, killhouse_user=kill_house, kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, temporary_trash=False, temporary_deleted=False ) # محاسبه تعداد کل بارها bar_count = kill_house_request1.count() # محاسبه تعداد بارهای دارای سند و فاقد سند bar_assigment_true_count = kill_house_request1.filter(assignment_state_archive='True').count() bar_assigment_pending_count = kill_house_request1.filter(assignment_state_archive='pending').count() # محاسبه تعداد هر وضعیت سند status_counts = {} for title in bar_duc: count = kill_house_request1.filter(bar_document_status__title=title).count() status_counts[title] = count total_counts[title] += count list1 = [ m, kill_house.name, kill_house.kill_house_operator.user.mobile, kill_house.kill_house_operator.user.city.name, bar_count, bar_assigment_true_count, bar_assigment_pending_count, *[status_counts.get(title, 0) for title in bar_duc] ] m += 1 l += 1 create_value(worksheet, list1, l + 1, 1, border_style='thin') bar_count = kill_house_request.count() bar_assigment_true_count = kill_house_request.filter(assignment_state_archive='True').count() bar_assigment_pending_count = kill_house_request.filter(assignment_state_archive='pending').count() list2 = [ 'مجموع', '', '', '', bar_count, bar_assigment_true_count, bar_assigment_pending_count, *[total_counts[title] for title in bar_duc] ] create_value(worksheet, list2, l + 3, 1, color='green') elif sheet_name == 'اطلاعات جامع انبار و توزیع': kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id').annotate( allocation_count=Count( 'kill_house_steward_allocation', filter=Q(kill_house_steward_allocation__receiver_state__in=['pending', 'accepted']) ) ).order_by( '-allocation_count' ) date1 = request.GET.get('date1') date2 = request.GET.get('date2') worksheet.sheet_view.rightToLeft = True worksheet.insert_rows(1) serializer = KillHouseForProvinceWareHouseDashboardSerializer(kill_houses, many=True, context={'request': request}).data header_list2 = [ 'ردیف', 'خریدار', 'تلفن خریدار', 'ماهیت', 'شهر', 'مانده انبار فعلی', 'کل وزن ورودی به انبار', 'کل وزن فروش رفته', 'حجم تخصیصات بدون ماشین', 'تعداد بار درون استان', 'حجم بار درون استان', 'وزن بار درون استان', 'تعداد بار زنده خارج استان', 'حجم بار زنده خارج استان', 'وزن بار زنده خارج استان', 'تعداد بار لاشه خارج استان', 'حجم بار لاشه خارج استان', 'وزن بار لاشه خارج استان', 'تعداد کل بارها', 'حجم کل بارها', 'وزن کل بارها', 'تعداد بار وارد شده به انبار', 'تعداد بار وارد نشده به انبار', 'حجم بار وارد نشده به انبار', 'وزن بار وارد نشده به انبار', 'وزن فروش داخل استان', 'وزن فروش خارج استان', ] create_header(worksheet, header_list2, 1, 6, height=21.8, width=20, border_style='thin') l = 7 if serializer: m = 1 for data in serializer: list1 = [ m, data.get('name', ''), data.get('kill_house_operator', {}).get('user', {}).get('mobile', ''), 'کشتارگاه' if not data.get('killer', False) else 'کشتارکن', data.get('kill_house_operator', {}).get('user', {}).get('city', {}).get('name', ''), data.get('ware_house_info', {}).get('product_remain_weight', 0), data.get('ware_house_info', {}).get('warehouse_total_entered_carcasses_weight', 0), data.get('ware_house_info', {}).get('total_sell', 0), data.get('ware_house_info', {}).get('province_kill_requests_quantity', 0), data.get('ware_house_info', {}).get('total_province_bars', 0), data.get('ware_house_info', {}).get('total_province_bars_quantity', 0), data.get('ware_house_info', {}).get('total_province_bars_weight', 0), data.get('ware_house_info', {}).get('total_kill_house_free_bar', 0), data.get('ware_house_info', {}).get('total_kill_house_free_live_bar_quantity', 0), data.get('ware_house_info', {}).get('total_kill_house_free_live_bar_weight', 0), data.get('ware_house_info', {}).get('total_kill_house_free_carcasses_bar', 0), data.get('ware_house_info', {}).get('total_kill_house_free_bar_carcasses', 0), data.get('ware_house_info', {}).get('total_kill_house_free_bar_carcasses_weight', 0), data.get('ware_house_info', {}).get('total_bars', 0), data.get('ware_house_info', {}).get('warehouse_total_quantity', 0), data.get('ware_house_info', {}).get('warehouse_total_weight', 0), int(data.get('ware_house_info', {}).get('warehouse_total_entered_bars', 0)), data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars', 0), data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_quantity', 0), data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_weight', 0), data.get('ware_house_info', {}).get('total_kill_house_allocations_weight', 0), data.get('ware_house_info', {}).get('total_kill_house_free_sale__bar_carcasses_weight', 0), ] create_value(worksheet, list1, l, 1, border_style='thin', m=m) m += 1 l += 1 header_list2 = [ 'حجم کل بارها', 'وزن کل بارها', 'وزن وارد شده به انبار', 'وزن توزیع شده داخل استان', 'وزن توزیع شده خارج استان', 'مانده انبار', ] create_header(worksheet, header_list2, 3, 3, height=21.8, width=20, color='C00000', border_style='thin') products = RolesProducts.objects.filter(kill_house__in=kill_houses, trash=False) product_remain_weight = products.aggregate(total=Sum('total_remain_weight'))[ 'total'] or 0 if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() shamsi_date1 = shamsi_date(date1) shamsi_date2 = shamsi_date(date2) excel_description(worksheet, 'A2', f' اطلاعات جامع انبار و توزیع کشتارگاه{shamsi_date1} تا تاریخ {shamsi_date2}', size=11, color='red', row2='B4') else: excel_description(worksheet, 'A2', f'اطلاعات جامع انبار', size=11, color='red', row2='B4') if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() kill_house_requests = KillHouseRequest.objects.filter( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses), kill_request__recive_date__date__gte=date1, kill_request__recive_date__date__lte=date2, temporary_trash=False, temporary_deleted=False, trash=False, calculate_status=True) kill_house_free_bar_informations = KillHouseFreeBarInformation.objects.filter( Q(date__date__gte=date1, date__date__lte=date2, buy_type='carcass') | Q( create_date__date__gte=date1, create_date__date__lte=date2, buy_type='live'), kill_house__in=kill_houses, trash=False, temporary_trash=False, temporary_deleted=False, calculate_status=True) kill_house_free_Sale_bar_informations = KillHouseFreeSaleBarInformation.objects.filter( kill_house__in=kill_houses, date__date__gte=date1, date__date__lte=date2, trash=False, temporary_trash=False, temporary_deleted=False, calculate_status=True) kill_house_allocations = StewardAllocation.objects.filter(kill_house__in=kill_houses, trash=False, receiver_state__in=( 'pending', 'accepted'), date__date__gte=date1, date__date__lte=date2, temporary_trash=False, temporary_deleted=False, to_cold_house__isnull=True, calculate_status=True) else: kill_house_requests = KillHouseRequest.objects.filter( Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses), temporary_trash=False, temporary_deleted=False, trash=False, calculate_status=True) kill_house_free_bar_informations = KillHouseFreeBarInformation.objects.filter( kill_house__in=kill_houses, trash=False, temporary_trash=False, temporary_deleted=False, calculate_status=True) kill_house_free_Sale_bar_informations = KillHouseFreeSaleBarInformation.objects.filter( kill_house__in=kill_houses, trash=False, temporary_trash=False, temporary_deleted=False, calculate_status=True) kill_house_allocations = StewardAllocation.objects.filter(kill_house__in=kill_houses, trash=False, receiver_state__in=( 'pending', 'accepted'), temporary_trash=False, temporary_deleted=False, to_cold_house__isnull=True, calculate_status=True) total_kill_house_requests_quantity = \ kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))[ 'total'] or 0 total_kill_house_requests_weight = kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[ 'total'] or 0 total_entered_kill_house_requests_carcasses_weight = \ kill_house_requests.filter(ware_house_confirmation=True).aggregate( total=Sum('ware_house_accepted_real_weight'))[ 'total'] or 0 kill_house_free_bar_informations_live = kill_house_free_bar_informations.filter(buy_type='live') kill_house_free_bar_informations_carcasses = kill_house_free_bar_informations.filter( buy_type='carcass') total_kill_house_free_bar_quantity = \ kill_house_free_bar_informations_live.aggregate(total=Sum('quantity'))['total'] or 0 total_kill_house_free_bar_weight = \ kill_house_free_bar_informations_live.aggregate(total=Sum('live_weight'))['total'] or 0 total_kill_house_free_bar_carcasses = \ kill_house_free_bar_informations_carcasses.aggregate(total=Sum('number_of_carcasses'))[ 'total'] or 0 total_kill_house_free_bar_carcasses_weight = \ kill_house_free_bar_informations_carcasses.aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 total_entered_kill_house_free_bar_carcasses_weight = \ kill_house_free_bar_informations.aggregate(total=Sum('weight_of_carcasses'))[ 'total'] or 0 total_kill_house_free_sale__bar_carcasses_weight = \ kill_house_free_Sale_bar_informations.aggregate(total=Sum('real_weight_of_carcasses'))[ 'total'] or 0 total_kill_house_allocations_weight = \ kill_house_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[ 'total'] or 0 warehouse_total_weight = total_kill_house_requests_weight + total_kill_house_free_bar_weight + total_kill_house_free_bar_carcasses_weight warehouse_total_entered_carcasses_weight = total_entered_kill_house_requests_carcasses_weight + total_entered_kill_house_free_bar_carcasses_weight result = { "product_remain_weight": int(warehouse_total_entered_carcasses_weight - ( total_kill_house_allocations_weight + total_kill_house_free_sale__bar_carcasses_weight)), "warehouse_total_quantity": int( total_kill_house_requests_quantity + total_kill_house_free_bar_quantity + total_kill_house_free_bar_carcasses), "warehouse_total_weight": int(warehouse_total_weight), "warehouse_total_entered_carcasses_weight": int(warehouse_total_entered_carcasses_weight), "total_kill_house_allocations_weight": int(total_kill_house_allocations_weight), "total_kill_house_free_sale_bar_carcasses_weight": int( total_kill_house_free_sale__bar_carcasses_weight), } value_header_list = [ result['warehouse_total_quantity'], # حجم کل بارها result['warehouse_total_weight'], # وزن کل بارها result['warehouse_total_entered_carcasses_weight'], # وزن وارد شده به انبار result['total_kill_house_allocations_weight'], # وزن توزیع شده داخل استان result['total_kill_house_free_sale_bar_carcasses_weight'], result['product_remain_weight'] # مانده انبار ] create_value(worksheet, value_header_list, 4, 3, border_style='thin') # محاسبه مجموع هر یک از فیلدها sum_product_remain_weight = sum( data.get('ware_house_info', {}).get('product_remain_weight', 0) for data in serializer) sum_previous_product_remain_weight = sum( data.get('ware_house_info', {}).get('previous_product_remain_weight', 0) for data in serializer) sum_province_kill_requests_quantity = sum( data.get('ware_house_info', {}).get('province_kill_requests_quantity', 0) for data in serializer) sum_total_province_bars = sum( data.get('ware_house_info', {}).get('total_province_bars', 0) for data in serializer) sum_total_province_bars_quantity = sum( data.get('ware_house_info', {}).get('total_province_bars_quantity', 0) for data in serializer) sum_total_province_bars_weight = sum( data.get('ware_house_info', {}).get('total_province_bars_weight', 0) for data in serializer) sum_total_kill_house_free_bar = sum( data.get('ware_house_info', {}).get('total_kill_house_free_bar', 0) for data in serializer) sum_total_kill_house_free_live_bar_quantity = sum( data.get('ware_house_info', {}).get('total_kill_house_free_live_bar_quantity', 0) for data in serializer) sum_total_kill_house_free_live_bar_weight = sum( data.get('ware_house_info', {}).get('total_kill_house_free_live_bar_weight', 0) for data in serializer) sum_total_kill_house_free_carcasses_bar = sum( data.get('ware_house_info', {}).get('total_kill_house_free_carcasses_bar', 0) for data in serializer) sum_total_kill_house_free_bar_carcasses = sum( data.get('ware_house_info', {}).get('total_kill_house_free_bar_carcasses', 0) for data in serializer) sum_total_kill_house_free_bar_carcasses_weight = sum( data.get('ware_house_info', {}).get('total_kill_house_free_bar_carcasses_weight', 0) for data in serializer) sum_total_bars = sum(data.get('ware_house_info', {}).get('total_bars', 0) for data in serializer) sum_warehouse_total_quantity = sum( data.get('ware_house_info', {}).get('warehouse_total_quantity', 0) for data in serializer) sum_warehouse_total_weight = sum( data.get('ware_house_info', {}).get('warehouse_total_weight', 0) for data in serializer) sum_warehouse_total_entered_bars = sum( int(data.get('ware_house_info', {}).get('warehouse_total_entered_bars', 0)) for data in serializer) sum_warehouse_total_entered_carcasses_weight = sum( data.get('ware_house_info', {}).get('warehouse_total_entered_carcasses_weight', 0) for data in serializer) sum_warehouse_total_not_entered_bars = sum( data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars', 0) for data in serializer) sum_warehouse_total_not_entered_bars_quantity = sum( data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_quantity', 0) for data in serializer) sum_warehouse_total_not_entered_bars_weight = sum( data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_weight', 0) for data in serializer) sum_total_kill_house_allocations_weight = sum( data.get('ware_house_info', {}).get('total_kill_house_allocations_weight', 0) for data in serializer) sum_total_kill_house_free_sale__bar_carcasses_weight = sum( data.get('ware_house_info', {}).get('total_kill_house_free_sale__bar_carcasses_weight', 0) for data in serializer) sum_total_sell = sum( data.get('ware_house_info', {}).get('total_sell', 0) for data in serializer) sum_warehouse_total_entered_bars = sum( data.get('ware_house_info', {}).get('warehouse_total_entered_bars', 0) for data in serializer) summary_list = [ 'جمع کل==>', '', '', '', '', sum_product_remain_weight, sum_warehouse_total_entered_bars, sum_total_sell, sum_province_kill_requests_quantity, sum_total_province_bars, sum_total_province_bars_quantity, sum_total_province_bars_weight, sum_total_kill_house_free_bar, sum_total_kill_house_free_live_bar_quantity, sum_total_kill_house_free_live_bar_weight, sum_total_kill_house_free_carcasses_bar, sum_total_kill_house_free_bar_carcasses, sum_total_kill_house_free_bar_carcasses_weight, sum_total_bars, sum_warehouse_total_quantity, sum_warehouse_total_weight, sum_warehouse_total_entered_bars, sum_warehouse_total_not_entered_bars, sum_warehouse_total_not_entered_bars_quantity, sum_warehouse_total_not_entered_bars_weight, sum_total_kill_house_allocations_weight, sum_total_kill_house_free_sale__bar_carcasses_weight ] create_value(worksheet, summary_list, l + 1, 1, color='green') new_l = l + 7 date1 = request.GET.get('date1') date2 = request.GET.get('date2') stewards = Guilds.objects.filter(trash=False, steward=True).select_related('user').only('user', 'guilds_name', 'steward').order_by( 'id') if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() allocation_stewards = stewards.annotate( allocation_count=Count( 'allocation_to_steward', filter=Q(allocation_to_steward__receiver_state__in=['pending', 'accepted'], allocation_to_steward__date__date__gte=date1, allocation_to_steward__date__date__lte=date2) ) ).filter(allocation_count__gt=0).order_by('-allocation_count') free_bar_stewards = stewards.annotate( free_bar_count=Count( 'free_bar_info_steward' ) ).filter(free_bar_count__gt=0).order_by('-free_bar_count') stewards1 = list(set(chain(allocation_stewards, free_bar_stewards))) else: allocation_stewards = stewards.annotate( allocation_count=Count( 'allocation_to_steward', filter=Q(allocation_to_steward__receiver_state__in=['pending', 'accepted']) ) ).filter(allocation_count__gt=0).order_by('-allocation_count') free_bar_stewards = stewards.annotate( free_bar_count=Count( 'free_bar_info_steward' ) ).filter(free_bar_count__gt=0).order_by('-free_bar_count') stewards1 = list(set(chain(allocation_stewards, free_bar_stewards))) serializer = RealGuildsForDashboardSerializer(stewards1, many=True, context={'request': request}).data if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() allocation_stewards = stewards.annotate( allocation_count=Count( 'allocation_to_steward', filter=Q(allocation_to_steward__receiver_state__in=['pending', 'accepted'], allocation_to_steward__date__date__gte=date1, allocation_to_steward__date__date__lte=date2) ) ).filter(allocation_count__gt=0).order_by('-allocation_count') free_bar_stewards = stewards.annotate( free_bar_count=Count( 'free_bar_info_steward' ) ).filter(free_bar_count__gt=0).order_by('-free_bar_count') stewards = (list(chain(allocation_stewards, free_bar_stewards))) allocations = StewardAllocation.objects.filter( Q(steward__in=stewards) | Q(to_steward__in=stewards), trash=False, calculate_status=True, to_cold_house__isnull=True, date__date__gte=date1, date__date__lte=date2) free_bars = StewardFreeBarInformation.objects.filter(steward__in=stewards, trash=False, date__date__gte=date1, date__date__lte=date2) free_sale_bars = StewardFreeSaleBarInformation.objects.filter(steward__in=stewards, trash=False, date__date__gte=date1, date__date__lte=date2) else: allocation_stewards = stewards.annotate( allocation_count=Count( 'allocation_to_steward', filter=Q(allocation_to_steward__receiver_state__in=['pending', 'accepted']) ) ).filter(allocation_count__gt=0).order_by('-allocation_count').values_list('id', flat=True) free_bar_stewards = stewards.annotate( free_bar_count=Count( 'free_bar_info_steward' ) ).filter(free_bar_count__gt=0).order_by('-free_bar_count').values_list('id', flat=True) stewards = (list(chain(allocation_stewards, free_bar_stewards))) allocations = StewardAllocation.objects.filter( Q(steward__in=stewards) | Q(to_steward__in=stewards), trash=False, calculate_status=True, to_cold_house__isnull=True) free_bars = StewardFreeBarInformation.objects.filter(steward__in=stewards, trash=False) free_sale_bars = StewardFreeSaleBarInformation.objects.filter(steward__in=stewards, trash=False) header_list2 = [ 'ردیف', 'خریدار', 'تلفن خریدار', 'ماهیت', 'شهر', 'مانده انبار فعلی', 'تعداد کل بارها', 'وزن کل بارها', 'تعداد بار وارد شده به انبار', 'کل وزن ورودی به انبار', 'تعداد فروش رفته', 'کل وزن فروش رفته', 'تعداد بار درون استان', 'وزن بار درون استان', 'تعداد بار لاشه خارج استان', 'وزن بار لاشه خارج استان', 'وزن فروش داخل استان', 'وزن فروش خارج استان', ] create_header(worksheet, header_list2, 1, new_l, height=21.8, width=20, border_style='thin') allocations_aggregates = allocations.aggregate( total_input_bars_count=Count('id', filter=Q(to_steward__isnull=False)), total_input_bars_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False)), total_output_bars_weight=Sum('real_weight_of_carcasses', filter=Q(steward__isnull=False, receiver_state__in=('pending', 'accepted'))), total_input_entered_bars_weight=Sum('real_weight_of_carcasses', filter=Q(to_steward__isnull=False, receiver_state='accepted')) ) free_bars_aggregates = free_bars.aggregate( total_count=Count('id'), total_weight=Sum('weight_of_carcasses') ) free_sale_bars_aggregates = free_sale_bars.aggregate( total_count=Count('id'), total_weight=Sum('weight_of_carcasses'), ) input_allocations_weight = allocations_aggregates['total_input_bars_weight'] or 0 input_entered_allocations_weight = allocations_aggregates['total_input_entered_bars_weight'] or 0 output_allocations_weight = allocations_aggregates['total_output_bars_weight'] or 0 free_bars_weight = free_bars_aggregates['total_weight'] or 0 free_sale_bars_weight = free_sale_bars_aggregates['total_weight'] or 0 remain_weight = int( (input_entered_allocations_weight + free_bars_weight) - ( free_sale_bars_weight + output_allocations_weight)) if date1: date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date() shamsi_date1 = shamsi_date(date1) shamsi_date2 = shamsi_date(date2) excel_description(worksheet, f'A{new_l - 2}', f' اطلاعات جامع انبار و توزیع مباشرین از تاریخ {shamsi_date1} تا تاریخ {shamsi_date2}', size=11, color='red', row2=f'B{new_l - 1}') sum_remain_weight = sum(data.get('ware_house_info', {}).get('remain_weight', 0) for data in serializer) sum_total_bars_count = sum( data.get('ware_house_info', {}).get('total_bars_count', 0) for data in serializer) sum_total_bars_weight = sum( data.get('ware_house_info', {}).get('total_bars_weight', 0) for data in serializer) sum_total_entered_bars_count = sum( data.get('ware_house_info', {}).get('total_entered_bars_count', 0) for data in serializer) sum_total_entered_bars_weight = sum( data.get('ware_house_info', {}).get('total_entered_bars_weight', 0) for data in serializer) sum_total_in_out_province_bars_count = sum( data.get('ware_house_info', {}).get('total_in_out_province_bars_count', 0) for data in serializer) sum_total_in_out_province_bars_weight = sum( data.get('ware_house_info', {}).get('total_in_out_province_bars_weight', 0) for data in serializer) sum_input_bars_count = sum( data.get('ware_house_info', {}).get('input_bars_count', 0) for data in serializer) sum_input_bars_weight = sum( data.get('ware_house_info', {}).get('input_bars_weight', 0) for data in serializer) sum_free_bars_count = sum(data.get('ware_house_info', {}).get('free_bars_count', 0) for data in serializer) sum_free_bars_weight = sum( data.get('ware_house_info', {}).get('free_bars_weight', 0) for data in serializer) sum_in_province_bars_weight = sum( data.get('ware_house_info', {}).get('in_province_bars_weight', 0) for data in serializer) sum_out_province_bars_weight = sum( data.get('ware_house_info', {}).get('out_province_bars_weight', 0) for data in serializer) sum_warehouse_total_entered_bars = sum( data.get('ware_house_info', {}).get('warehouse_total_entered_bars', 0) for data in serializer) result = { "total_bars_weight": int(input_allocations_weight + free_bars_weight), "total_entered_bars_weight": int(input_entered_allocations_weight + free_bars_weight), "in_province_bars_weight": int(output_allocations_weight), "out_province_bars_weight": int(free_sale_bars_weight), "remain_weight": remain_weight, } value_header_list = [ result['total_bars_weight'], result['total_entered_bars_weight'], result['in_province_bars_weight'], result['out_province_bars_weight'], result['remain_weight'], ] create_value(worksheet, value_header_list, new_l - 1, 3, border_style='thin') header_list2 = [ 'وزن کل بارها', 'وزن وارد شده به انبار', 'وزن توزیع شده داخل استان', 'وزن توزیع شده خارج استان', 'مانده انبار', ] create_header(worksheet, header_list2, 3, new_l - 2, height=21.8, width=20, color='C00000', border_style='thin') if serializer: m = 1 for data in serializer: steward_type = 'مباشر' if data.get('steward') == True else 'صنف' list1 = [ m, data.get('user', {}).get('fullname', ''), data.get('user', {}).get('mobile', ''), f'{steward_type}({data.get("guilds_name", "")})', data.get('user', {}).get('city_name', {}), data.get('ware_house_info', {}).get('remain_weight', 0), data.get('ware_house_info', {}).get('total_bars_count', 0), data.get('ware_house_info', {}).get('total_bars_weight', 0), data.get('ware_house_info', {}).get('total_entered_bars_count', 0), data.get('ware_house_info', {}).get('total_entered_bars_weight', 0), data.get('ware_house_info', {}).get('total_in_out_province_bars_count', 0), data.get('ware_house_info', {}).get('total_in_out_province_bars_weight', 0), data.get('ware_house_info', {}).get('input_bars_count', 0), data.get('ware_house_info', {}).get('input_bars_weight', 0), data.get('ware_house_info', {}).get('free_bars_count', 0), data.get('ware_house_info', {}).get('free_bars_weight', 0), data.get('ware_house_info', {}).get('in_province_bars_weight', 0), data.get('ware_house_info', {}).get('out_province_bars_weight', 0), ] create_value(worksheet, list1, new_l + 1, 1, border_style='thin', m=m) m += 1 new_l += 1 date1 = request.GET.get('date1') date2 = request.GET.get('date2') summary_list = [ 'جمع کل==>', '', '', '', '', sum_remain_weight, sum_total_bars_count, sum_total_bars_weight, sum_total_entered_bars_count, sum_total_entered_bars_weight, sum_total_in_out_province_bars_count, sum_total_in_out_province_bars_weight, sum_input_bars_count, sum_input_bars_weight, sum_free_bars_count, sum_free_bars_weight, sum_in_province_bars_weight, sum_out_province_bars_weight, ] create_value(worksheet, summary_list, new_l + 1, 1, color='green') else: date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date() date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date() kill_house_request = KillHouseRequest.objects.filter( trash=False, temporary_trash=False, temporary_deleted=False, clearance_code__isnull=False ).values_list('clearance_code', flat=True).distinct() kill_house_free_sale = PoultryRequest.objects.filter(trash=False, quarantine_code__isnull=False, out=True) \ .values_list('quarantine_code', flat=True).distinct() result = list(kill_house_request) + list(kill_house_free_sale) response = requests.post( f'https://rsibackend.rasadyar.com/app/send_different_bar/?province={base_url_for_sms_report}' f'&date1={date1}&date2={date2}', json=result, headers={'Content-Type': 'application/json'} ) header_list = [ 'تعداد مرغداران', 'تعداد کشتارگاه ها', 'حجم کشتار', ] create_header(worksheet, header_list, 4, 2, height=25, width=25, border_style='thin', color='C00000') excel_options = [ 'ردیف', 'نوع بار', 'تاریخ کشتار', 'مرغدار', 'شناسه یکتا مرغدار', 'شماره مجوز جوجه ریزی', 'شماره موبایل مرغدار', 'شهر مرغدار', 'دامپزشک فارم', 'تلفن دامپزشک فارم', 'کد قرنطینه', 'وضعیت بار', 'کشتارگاه', 'شناسه یکتا کشتارگاه', 'استان', 'شهر', 'حجم کشتار', 'سن کشتار', ] m = 1 create_header_freez(worksheet, excel_options, 1, 6, 7, 20) l = 7 unique_poultry_out_false = set() unique_slaughterhouses_out_false = set() total_slaughter_out_false = 0 excel_description(worksheet, 'A1', f'بارهای دارای مغایرت', color='red', row2='B1') if 'date1' in request.GET: date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() from_date1 = shamsi_date(date1) from_date2 = shamsi_date(date2) excel_description(worksheet, 'A3', f'از تاریخ {from_date1} تا {from_date2}', color='red', row2='C3') for data in response.json(): if data['Out'] == False: state = 'داخل استان' else: state = 'خارج استان' vet_farm_mobile = '' vet_farm_name = '' vet_farm = VetFarm.objects.filter(trash=False, poultry__breeding_unique_id=data['hatching']['poultry'][ 'PartIdCode']).first() if vet_farm: vet_farm_mobile = vet_farm.vet.user.mobile vet_farm_name = vet_farm.vet.user.fullname unique_poultry_out_false.add(data['hatching']['poultry']['UnitName']) unique_slaughterhouses_out_false.add(data['DesUnitName']) total_slaughter_out_false += data['GoodAmount'] date_str = str(data['Date']).split('T')[0] # جدا کردن بخش تاریخ date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date() list1 = [ m, state, str(shamsi_date(date, in_value=True)), data['hatching']['poultry']['UnitName'], data['hatching']['poultry']['PartIdCode'], data['hatching']['RequestCode'], data['hatching']['poultry']['Mobile'], data['hatching']['poultry']['City'], vet_farm_name, vet_farm_mobile, data['TrackingCode'], data['TrackingStatusDescription'], data['DesUnitName'], data['DesPartIdCode'], data['Province'], data['City'], data['GoodAmount'], data['Age'], ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=35) l += 1 m += 1 value_header_list = [ len(unique_poultry_out_false), len(unique_slaughterhouses_out_false), total_slaughter_out_false ] create_value(worksheet, value_header_list, 3, 4, border_style='thin') quantity = sum( data['GoodAmount'] for data in response.json() if data['Out'] == False) or 0 list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', quantity, '', ] create_value(worksheet, list2, l + 1, 1, color='green') workbook.save(output) output.seek(0) response1 = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response1[ 'Content-Disposition'] = f'attachment; filename="پایش کلی اطلاعات.xlsx"'.encode( 'utf-8') response1.write(output.getvalue()) return response1 def market_requests_excel(request): filterset_class = KillRequestFilterSet filterset_fields = [ 'kill_house__kill_house_operator__user__mobile', 'kill_house__kill_house_operator__user__fullname', 'kill_house__kill_house_operator__user__first_name', 'kill_house__kill_house_operator__user__last_name', 'poultry_request__chicken_breed', 'poultry_request__order_code', 'poultry_request__poultry__address__city__name', 'poultry_request__poultry__user__mobile', 'poultry_request__poultry__user__fullname', ] user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) now = datetime.datetime.now().date() role = request.GET.get('role') filter = { 'trash': False, 'market': True, 'recive_date__date': now, } excel_name = 'سفارشات دریافتی' excel_options = [ "ردیف", "فارم", "مرغدار", "تلفن مرغدار", "شهر", "ماهیت خریدار", "خریدار", "تلفن خریدار", "آدرس خریدار", "نژاد", "سن (روز)", "تعداد قطعه", "تاریخ کشتار", "میانگین وزنی (کیلوگرم)", "وزن تقریبی (کیلوگرم)", "مبلغ هر کیلو (ریال)", "حداکثر مهلت تسویه", "وضعیت", ] if role == 'KillHouse': kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first() filter['kill_house'] = kill_house excel_name = 'خریدهای ثبت شده' excel_options = [ "ردیف", "فارم", "مرغدار", "تلفن مرغدار", "شهر", "نژاد", "سن (روز)", "تعداد قطعه", "تاریخ کشتار", "میانگین وزنی (کیلوگرم)", "وزن تقریبی (کیلوگرم)", "مبلغ هر کیلو (ریال)", "حداکثر مهلت تسویه", "وضعیت", ] elif role in ('CityJahad', 'CityOperator', 'CityCommerce', 'CityVet', 'CitySupervisor', 'CityPoultry'): filter['poultry__address__city'] = user.city state_type = request.GET.get('type') if state_type and state_type != 'all': filter['market_state'] = state_type kill_requests = KillRequest.objects.filter(**filter).select_related('poultry_hatching', 'poultry').only( 'poultry_hatching', 'poultry').order_by( Case( When(market_state='pending', then=Value(0)), default=Value(1) ), '-create_date' ) if 'search' in request.GET: kill_requests_list = [] if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=kill_requests ) ).filter(): ps = filterset_class(data=query, queryset=kill_requests) kill_requests_list = ps.filter() kill_requests = [] if len( kill_requests_list) == 0 else kill_requests_list 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') header_list = [ 'تعداد قطعه', "وزن تقریبی (کیلوگرم)", ] create_header(worksheet, header_list, 5, 2, height=20) excel_description(worksheet, 'B1', excel_name, color='red', row2='C3') create_header_freez(worksheet, excel_options, 1, 6, 7, height=22) l = 5 m = 1 all_wight = 0 serializer = KillRequestForDirectBuyingSerializer(kill_requests, many=True).data if serializer: for data in serializer: all_wight += int(data['Index_weight'] * data['kill_capacity']) state = '-' if data['market_state'] == "pending" and data['market_code_status'] == True and data[ 'market_final_accept'] == True \ and data.get('input_market_code'): state = 'در انتظار ورود کد احراز' elif data['market_final_accept'] == False: state = 'در انتظار تایید خریدار' elif data['market_state'] == "pending": state = 'در انتظار تایید استان' elif data['market_state'] == "accepted": state = 'تایید شده' elif data['market_state'] == "rejected": state = 'رد شده' elif data['market_state'] == "deleted": state = 'حذف شده' if type(data['recive_date']) is str: try: # فرمت با کسری ثانیه str_date = datetime.datetime.strptime(str(data['recive_date']), "%Y-%m-%dT%H:%M:%S.%f").date() except: try: # فرمت بدون کسری ثانیه str_date = datetime.datetime.strptime(str(data['recive_date']), "%Y-%m-%dT%H:%M:%S").date() except: try: # فقط تاریخ str_date = datetime.datetime.strptime(str(data['recive_date']), '%Y-%m-%d').date() except: # اگر هیچکدام کار نکرد، مقدار پیشفرض قرار دهید str_date = None date = shamsi_date(str_date, in_value=True) if str_date else '-' elif data['recive_date'] is None: date = '-' else: date = shamsi_date(data['recive_date'], in_value=True) if type(data['payment_deadline_date']) is str: try: # فرمت با کسری ثانیه str_date = datetime.datetime.strptime(str(data['payment_deadline_date']), "%Y-%m-%dT%H:%M:%S.%f").date() except: try: # فرمت بدون کسری ثانیه str_date = datetime.datetime.strptime(str(data['payment_deadline_date']), "%Y-%m-%dT%H:%M:%S").date() except: try: # فقط تاریخ str_date = datetime.datetime.strptime(str(data['payment_deadline_date']), '%Y-%m-%d').date() except: # اگر هیچکدام کار نکرد، مقدار پیشفرض قرار دهید str_date = None payment_deadline_date = shamsi_date(str_date, in_value=True) if str_date else '-' elif data['payment_deadline_date'] is None: payment_deadline_date = '-' else: payment_deadline_date = shamsi_date(data['payment_deadline_date'], in_value=True) if role == 'KillHouse': list1 = [ m, str(data['poultry']['unit_name']), data['poultry']['fullname'], data['poultry']['mobile'], data['poultry']['city'], data['chicken_breed'], data['poultry_request']['killing_age'], data['kill_capacity'], str(date), str(data['Index_weight']), int(data['Index_weight'] * data['kill_capacity']), data['amount'], str(payment_deadline_date), state ] else: killer = 'کشتارکن' if data['kill_house']['killer'] == True else 'کشتارگاه' list1 = [ m, data['poultry']['unit_name'], data['poultry']['fullname'], data['poultry']['mobile'], data['poultry']['city'], data['chicken_breed'], killer, data['kill_house']['name'], data['kill_house']['mobile'], data['kill_house']['city'], data['poultry_request']['killing_age'], data['kill_capacity'], str(date), str(data['Index_weight']), int(data['Index_weight'] * data['kill_capacity']), data['amount'], str(payment_deadline_date), state ] m += 1 l += 1 create_value(worksheet, list1, l + 1, 1, border_style='thin') kill_capacity = sum( item['kill_capacity'] for item in serializer) value_header_list = [ kill_capacity, all_wight, ] create_value(worksheet, value_header_list, 3, 5) if role == 'KillHouse': list2 = [ 'مجموع==>', '', '', '', '', '', '', kill_capacity, '', '', all_wight, '', '', '', ] else: list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', kill_capacity, '', '', all_wight, '', '', '', ] create_value(worksheet, list2, l + 3, 1, color='green') workbook.save(output) output.seek(0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response[ 'Content-Disposition'] = f'attachment; filename="{excel_name}.xlsx"'.encode( 'utf-8') response.write(output.getvalue()) return response def get_more_than_one_role(request): users = SystemUserProfile.objects.filter(trash=False).annotate(role_count=Count('role')) \ .filter(role_count__gt=1) 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) m = 1 create_header_freez(worksheet, excel_options, 1, 1, 2, 20, width=30) l = 2 for user in users: role_list = [role.name for role in user.role.all()] list1 = [ m, user.fullname, user.mobile, str(role_list), user.city.name if user.city else '-' ] create_value(worksheet, list1, l, 1, m=m, border_style='thin') m += 1 l += 1 province = users.first().province.name workbook.save(output) output.seek(0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response[ 'Content-Disposition'] = f'attachment; filename="کاربران چند نقشی استان {province} .xlsx"'.encode( 'utf-8') response.write(output.getvalue()) return response def return_province_request_excel(request): serializer_class = ReturnProvinceKillRequestSerializer filterset_class = ReturnProvinceKillRequestFilterSet filterset_fields = [ 'province_request__poultry_request__order_code', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__fullname', 'killhouse_user__kill_house_operator__user__mobile', 'killhouse_user__kill_house_operator__address__city__name', 'province_request__poultry_request__poultry__unit_name', 'province_request__poultry_request__poultry__user__fullname', 'province_request__poultry_request__poultry__user__mobile', 'province_request__poultry_request__poultry__address__city__name', ] 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') date1 = request.GET.get('date1') date2 = request.GET.get('date2') role = request.GET.get('role') user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False) filters = { 'archive_wage': False, 'state__in': ('pending', 'accepted'), 'first_car_allocated_quantity': 0 } if role == 'KillHouse': filters['killhouse_user__kill_house_operator__user'] = user if date1: filters['kill_request__recive_date__date__gte'] = date1 filters['kill_request__recive_date__date__lte'] = date2 return_province_kill_requests = ProvinceKillRequest.objects.filter( Q(trash=False, return_to_province=True) | Q(trash=True, return_trash=True), **filters).order_by('id') if 'search' in request.GET: return_province_kill_requests_list = [] if request.GET['search'] == 'filter': if request.GET['value'] != "" and request.GET['value'] != 'undefined': for item in filterset_fields: query = QueryDict('{0}__contains={1}'.format(item, request.GET['value'])) if (filterset_class( data=query, queryset=return_province_kill_requests ) ).filter(): ps = filterset_class(data=query, queryset=return_province_kill_requests) return_province_kill_requests_list = ps.filter() return_province_kill_requests = [] if len( return_province_kill_requests_list) == 0 else return_province_kill_requests_list serializer = serializer_class(return_province_kill_requests, many=True).data header_list2 = [ 'ردیف', 'کدسفارش', 'نوع درخواست', 'نام فارم', 'نام مرغدار', 'شهر مرغدار', 'تاریخ کشتار', 'تعداد درخواست', 'تاریخ ثبت تخصیص', 'نام کشتارگاه', 'شهر کشتارگاه', 'قیمت مرغدار', 'قیمت کشتارگاه', 'تعداد تخصیص', 'وضعیت تایید', 'وضعیت تخصیص ماشین', 'مانده قابل تخصیص', 'برگشت دهنده', ] create_header(worksheet, header_list2, 1, 12, height=21.8, width=20, border_style='thin') excel_description(worksheet, 'A2', f'تخصیصات برگشت داده شده', size=11, color='red', row2='B4') if serializer: l = 13 m = 1 for item in serializer: state = "" if item.get('state') == "pending": state = "در انتظار تایید" elif item.get('state') == "accepted": state = "تایید شده" elif item.get('state') == "rejected": state = "رد شده" request_type = "" if item.get('market'): request_type = "پنل معاملات" elif item.get('direct_buying'): request_type = "خرید مستقیم" elif item.get('warehouse'): request_type = "انبار" else: request_type = "اتحادیه" poultry_info = "" if item.get('poultry_fullname') and item.get('poultry_mobile'): poultry_info = f"{item.get('poultry_fullname')} ({item.get('poultry_mobile')})" else: poultry_info = item.get('poultry_fullname', '-') returner_info = "" if item.get('returner'): returner_fullname = item.get('returner', {}).get('fullname', '') returner_mobile = item.get('returner', {}).get('mobile', '') modify_date = str(shamsi_date((convert_str_to_date(item.get('modify_date'))), in_value=True)) returner_info = f"{returner_fullname} ({returner_mobile}) {modify_date}" else: returner_info = "سیستم" list1 = [ m, item.get('order_code') or "-", request_type, item.get('poultry_unit_name') or "-", poultry_info, item.get('poultry_city') or "-", str(shamsi_date(convert_str_to_date(item.get('killing_date')), in_value=True)), item.get('poultry_request_quantity'), str(shamsi_date(convert_str_to_date(item.get('create_date')), in_value=True)), item.get('killhouse_user', {}).get('name') or "-", item.get('killhouse_user', {}).get('city') or "-", int(float(item.get('poultry_amount') or 0)), item.get('kill_house_price'), item.get('quantity'), state, "دارد" if item.get('first_car_allocated_quantity', 0) > 0 else "ندارد", (item.get('quantity', 0) - item.get('total_killed_quantity', 0)), returner_info ] create_value(worksheet, list1, l, 1, border_style='thin', m=m) m += 1 l += 1 header_list2 = [ "تعداد کل تخصیصات", "تعداد تخصیصات بازگشتی کاربر", "تعداد تخصیصات بازگشتی سیستم", "حجم کل تخصیصات", "حجم تخصیصات بازگشتی کاربر", "حجم تخصیصات بازگشتی سیستم", "وزن کل تخصیصات", "وزن بازگشتی کاربر", "وزن بازگشتی سیستم", "تعداد کل بارها", "تعداد بارهای عدم وصول", "تعداد بارهای بازگشتی سیستمی", "حجم کل بارها", "حجم بارهای عدم وصول", "حجم بارهای بازگشتی سیستمی", "وزن کل بارها", "وزن بارهای عدم وصول", "وزن بارهای بازگشتی سیستمی", "وزن خریدهای بازگشتی با کارمزد", "کارمزد خریدهای بازگشتی" ] create_header(worksheet, header_list2, 3, 3, height=21.8, width=20, color='C00000', border_style='thin') total_wage_type = WageType.objects.filter(trash=False) province_live_wage_type = total_wage_type.filter(en_name='province-kill-request', trash=False).first() province_live_wage_type_amount = province_live_wage_type.amount if province_live_wage_type.status == True else 0 province_kill_request_filters = { 'archive_wage': False, 'state__in': ('pending', 'accepted'), 'first_car_allocated_quantity': 0 } kill_house_request_filters = {} if date1: province_kill_request_filters['kill_request__recive_date__date__gte'] = date1 province_kill_request_filters['kill_request__recive_date__date__lte'] = date2 kill_house_request_filters['kill_request__recive_date__date__gte'] = date1 kill_house_request_filters['kill_request__recive_date__date__lte'] = date2 if role == 'KillHouse': kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first() province_kill_request_filters['killhouse_user'] = kill_house return_kill_house_requests = KillHouseRequest.objects.filter( Q(killhouse_user=kill_house) | Q(killer=kill_house), Q(non_receipt=True, main_non_receipt=True, non_receipt_state__in=('pending', 'accepted')) | Q( trash=True, return_trash=True), **kill_house_request_filters) else: return_kill_house_requests = KillHouseRequest.objects.filter( Q(non_receipt=True, main_non_receipt=True, non_receipt_state__in=('pending', 'accepted')) | Q( trash=True, return_trash=True), **kill_house_request_filters) return_province_kill_requests = ProvinceKillRequest.objects.filter( Q(trash=False, return_to_province=True) | Q(trash=True, return_trash=True), **province_kill_request_filters).order_by('id') return_province_kill_requests_aggregates = return_province_kill_requests.aggregate( total_count=Count('id'), total_operator_return_count=Count('id', filter=Q(trash=False, return_to_province=True)), total_system_return_count=Count('id', filter=Q(trash=True, return_trash=True)), total_quantity=Sum('total_killed_quantity'), total_operator_return_quantity=Sum('main_quantity', filter=Q(trash=False, return_to_province=True)), total_system_return_quantity=Sum('total_killed_quantity', filter=Q(trash=True, return_trash=True)), total_weight=Sum('total_killed_weight'), total_operator_return_weight=Sum(F('main_quantity') * F('province_request__poultry_request__Index_weight'), filter=Q(trash=False, return_to_province=True)), total_system_return_weight=Sum('total_killed_weight', filter=Q(trash=True, return_trash=True)), ) return_kill_house_requests_aggregates = return_kill_house_requests.aggregate( total_count=Count('id'), total_non_receipt_count=Count('id', filter=Q(non_receipt=True, main_non_receipt=True)), total_system_return_count=Count('id', filter=Q(trash=True, return_trash=True)), total_quantity=Sum('accepted_real_quantity'), total_non_receipt_quantity=Sum('accepted_real_quantity', filter=Q(non_receipt=True, main_non_receipt=True)), total_system_return_quantity=Sum('accepted_real_quantity', filter=Q(trash=True, return_trash=True)), total_weight=Sum('accepted_real_weight'), total_non_receipt_weight=Sum('accepted_real_weight', filter=Q(non_receipt=True, main_non_receipt=True)), total_system_return_weight=Sum('accepted_real_weight', filter=Q(trash=True, return_trash=True)), ) province_kill_request_total_operator_return_quantity = return_province_kill_requests_aggregates[ 'total_operator_return_quantity'] or 0 province_kill_request_total_system_return_quantity = return_province_kill_requests_aggregates[ 'total_system_return_quantity'] or 0 province_kill_request_total_quantity = province_kill_request_total_operator_return_quantity + province_kill_request_total_system_return_quantity province_kill_request_total_operator_return_weight = return_province_kill_requests_aggregates[ 'total_operator_return_weight'] or 0 province_kill_request_total_system_return_weight = return_province_kill_requests_aggregates[ 'total_system_return_weight'] or 0 province_kill_request_total_weight = province_kill_request_total_operator_return_weight + province_kill_request_total_system_return_weight kill_house_request_total_system_return_weight = return_kill_house_requests_aggregates[ 'total_system_return_weight'] or 0 total_return_weight_with_wage = province_kill_request_total_system_return_weight + kill_house_request_total_system_return_weight result = { "province_kill_request_total_count": return_province_kill_requests_aggregates['total_count'] or 0, "province_kill_request_total_operator_return_count": return_province_kill_requests_aggregates[ 'total_operator_return_count'] or 0, "province_kill_request_total_system_return_count": return_province_kill_requests_aggregates[ 'total_system_return_count'] or 0, "province_kill_request_total_quantity": province_kill_request_total_quantity, "province_kill_request_total_operator_return_quantity": province_kill_request_total_operator_return_quantity, "province_kill_request_total_system_return_quantity": province_kill_request_total_system_return_quantity, "province_kill_request_total_weight": province_kill_request_total_weight, "province_kill_request_total_operator_return_weight": province_kill_request_total_operator_return_weight, "province_kill_request_total_system_return_weight": province_kill_request_total_system_return_weight, "kill_house_request_total_count": return_kill_house_requests_aggregates['total_count'] or 0, "kill_house_request_total_non_receipt_count": return_kill_house_requests_aggregates[ 'total_non_receipt_count'] or 0, "kill_house_request_total_system_return_count": return_kill_house_requests_aggregates[ 'total_system_return_count'] or 0, "kill_house_request_total_quantity": return_kill_house_requests_aggregates['total_quantity'] or 0, "kill_house_request_total_non_receipt_quantity": return_kill_house_requests_aggregates[ 'total_non_receipt_quantity'] or 0, "kill_house_request_total_system_return_quantity": return_kill_house_requests_aggregates[ 'total_system_return_quantity'] or 0, "kill_house_request_total_weight": return_kill_house_requests_aggregates['total_weight'] or 0, "kill_house_request_total_non_receipt_weight": return_kill_house_requests_aggregates[ 'total_non_receipt_weight'] or 0, "kill_house_request_total_system_return_weight": kill_house_request_total_system_return_weight, "total_return_weight_with_wage": total_return_weight_with_wage, "total_return_wage": total_return_weight_with_wage * province_live_wage_type_amount, } value_header_list = [ result.get('province_kill_request_total_count') or 0, result.get('province_kill_request_total_operator_return_count') or 0, result.get('province_kill_request_total_system_return_count') or 0, result.get('province_kill_request_total_quantity') or 0, result.get('province_kill_request_total_operator_return_quantity') or 0, result.get('province_kill_request_total_system_return_quantity') or 0, result.get('province_kill_request_total_weight') or 0, result.get('province_kill_request_total_operator_return_weight') or 0, result.get('province_kill_request_total_system_return_weight') or 0, result.get('kill_house_request_total_count') or 0, result.get('kill_house_request_total_non_receipt_count') or 0, result.get('kill_house_request_total_system_return_count') or 0, result.get('kill_house_request_total_quantity') or 0, result.get('kill_house_request_total_non_receipt_quantity') or 0, result.get('kill_house_request_total_system_return_quantity') or 0, result.get('kill_house_request_total_weight') or 0, result.get('kill_house_request_total_non_receipt_weight') or 0, result.get('kill_house_request_total_system_return_weight') or 0, result.get('total_return_weight_with_wage') or 0, result.get('total_return_wage') or 0, ] create_value(worksheet, value_header_list, 4, 3, border_style='thin') summary_list = [ 'جمع کل==>', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ] create_value(worksheet, summary_list, l + 1, 1, color='green') 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 guilds_without_allocation_excel(request): guilds = Guilds.objects.filter(trash=False, active=True).order_by('id') guilds_with_allocation = StewardAllocation.objects.filter( trash=False ).values_list('to_steward_id', 'to_guilds_id') allocated_guild_ids = set() for to_steward_id, to_guilds_id in guilds_with_allocation: if to_steward_id: allocated_guild_ids.add(to_steward_id) if to_guilds_id: allocated_guild_ids.add(to_guilds_id) pos_machines_with_paid_transactions = POSTransactions.objects.filter( trash=False, paid=True, pos_machine__isnull=False ).values_list('pos_machine_id', flat=True).distinct() guilds_with_paid_pos = POSMachine.objects.filter( id__in=pos_machines_with_paid_transactions, guild__isnull=False ).values_list('guild_id', flat=True).distinct() guilds_to_keep = allocated_guild_ids.union(set(guilds_with_paid_pos)) guilds_without_allocation = guilds.exclude(id__in=guilds_to_keep) total_guilds_count = guilds.count() guilds_without_allocation_count = guilds_without_allocation.count() guilds_with_allocation_count = total_guilds_count - guilds_without_allocation_count 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_CELL header_list = [ 'تعداد کل صنف‌ها', 'تعداد صنف‌های دارای توزیع', 'تعداد صنف‌های بدون توزیع', ] create_header(worksheet, header_list, 4, 2, 21, 22) excel_description(worksheet, 'A1', f'گزارش صنف‌های بدون توزیع', size=12, color='red', row2='C1') value_header_list = [ total_guilds_count, guilds_with_allocation_count, guilds_without_allocation_count, ] create_value(worksheet, value_header_list, 3, 4, border_style='thin') excel_options = [ 'ردیف', 'نام صنف', 'کد صنف', 'شماره مجوز', 'نام مالک', 'موبایل', 'شهر', 'استان', 'نوع فعالیت', 'حوزه فعالیت', 'مباشر', 'وضعیت پز', 'وضعیت فعال', 'تاریخ ثبت', ] create_header_freez(worksheet, excel_options, 1, 6, 7, 22, width=22) l = 7 m = 1 for guild in guilds_without_allocation: steward_status = '✅' if guild.steward else '❌' has_pos_status = '✅' if guild.has_pos else '❌' active_status = 'فعال' if guild.active else 'غیرفعال' if guild.create_date: create_date_shamsi = str(shamsi_date(guild.create_date.date(), in_value=True)) else: create_date_shamsi = '-' list1 = [ m, guild.guilds_name if guild.guilds_name else '-', guild.guilds_id if guild.guilds_id else '-', guild.license_number if guild.license_number else '-', guild.user.fullname if guild.user else '-', guild.user.mobile if guild.user else '-', guild.user.city.name if guild.user.city else '-', guild.user.province.name if guild.user.province else '-', guild.type_activity if guild.type_activity else '-', guild.area_activity if guild.area_activity else '-', steward_status, has_pos_status, active_status, create_date_shamsi, ] create_value(worksheet, list1, l, 1, m=m, border_style='thin', height=22) m += 1 l += 1 list2 = [ 'مجموع==>', '', '', '', '', '', '', '', '', '', '', '', '', '', ] create_value(worksheet, list2, l + 3, 1, color='green') 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