add excel

This commit is contained in:
2026-01-26 15:25:19 +03:30
parent 5fde0a680f
commit 2c2e060f6a
80 changed files with 285 additions and 5 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -14,11 +14,12 @@ from rest_framework.permissions import AllowAny
from app.filtersets import TransportingDetailFilterSet, KillHouseFilterSet, HatchingsFilterSet, GuildsFilterSet, \
TransportCarcassDetailFilterSet, AllProductsTransportFilterSet
from app.helper_excel import create_header, create_header_freez, shamsi_date, excel_description, create_value
from app.helper_excel import create_header, create_header_freez, shamsi_date, excel_description, create_value, \
convert_str_to_date
from app.models import TransportingDetail, KillHouse, Hatching, TransportCarcassDetail, Guilds, AllProductsTransport
from app.serializers import TransportingDetailSerializer, HatchingDetailSerializer, \
StewardForTransportCarcassSerializer, KillHouseForTransportCarcassSerializer, TransportCarcassDetailSerializer, \
GuildsForTransportCarcassSerializer, AllProductsTransportSerializer
GuildsForTransportCarcassSerializer, AllProductsTransportSerializer, AllProductsTransportCustomSerializer
from helpers import build_query
from app.helper import get_hatching_permit_code
@@ -2571,4 +2572,228 @@ def import_transporting_detail(request):
new_obj.save()
created_count += 1
return HttpResponse(f"{created_count} رکورد جدید اضافه شد ✅")
return HttpResponse(f"{created_count} رکورد جدید اضافه شد ✅")
def all_products_transport_excel(request):
filterset_class = AllProductsTransportFilterSet
transports = AllProductsTransport.objects.filter(trash=False)
product_type = request.GET.get('product_type')
destination_province = request.GET.get('destination_province')
date1 = request.GET.get('date1')
date2 = request.GET.get('date2')
search = request.GET.get('search')
if product_type and product_type != 'undefined':
transports = transports.filter(product=product_type)
if destination_province and destination_province != 'undefined':
transports = transports.filter(destination_province=destination_province)
if date1 and date2 and date1 != 'undefined' and date2 != 'undefined':
try:
start_date = datetime.datetime.strptime(str(date1), '%Y-%m-%d')
end_date = datetime.datetime.strptime(str(date2), '%Y-%m-%d')
transports = transports.filter(date__gte=start_date, date__lte=end_date)
except ValueError:
pass
if search:
if search != 'undefined' and search.strip():
transports = transports.filter(
build_query(filterset_class.Meta.fields, search)
)
serializer = AllProductsTransportCustomSerializer(transports.order_by('-date', '-create_date'), 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')
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['A3'] = f'از تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'
excel_description(worksheet, 'A5', f'اطلاعات بار کل کشور', color='red', row2='C5')
if destination_province and destination_province != 'undefined':
excel_description(worksheet, 'A4', f'استان {destination_province}', row2='C4')
if product_type and product_type != 'undefined':
excel_description(worksheet, 'A1', f'محصول {product_type}', row2='C1')
# header_list2 = [
# 'تعداد کشتارگاه ها',
# 'تعداد بار',
# 'حجم بار',
# 'تعداد بار داخل استان',
# 'حجم بار داخل استان',
# 'درصد بار داخل استان',
# 'تعداد بار خارج استان',
# 'حجم بار خارج استان',
# 'درصد بار خارج استان',
#
# ]
# create_header(worksheet, header_list2, 5, 2, height=20.8, border_style='thin')
create_header_freez(worksheet, excel_options, 1, 6, 7, 20)
l = 5
m = 1
if serializer:
for data in serializer:
list1 = [
m, # ردیف
data.get("tracking"),
data.get("product"),
data.get("items") if data.get("items") else '-',
data.get("quantity"),
data.get("unit"),
str(shamsi_date(convert_str_to_date(data.get("date")),in_value=True)) if data.get('date') else '-',
data.get("destination"),
data.get("jihadi_destination"),
data.get("destination_province"),
data.get("destination_city"),
data.get("origin"),
data.get("jihadi_origin"),
data.get("origin_province"),
data.get("origin_city"),
"داخل استان" if data.get("origin_province") == data.get("destination_province") else "خارج استان",
data.get("destination_prev") if data.get("destination_prev") else '-',
data.get("destination_changed") if data.get("destination_changed") else '-',
data.get("car_tracking_code"),
str(shamsi_date(convert_str_to_date(data.get("unloading_date")), in_value=True)) if data.get("unloading_date") else '-',
data.get("unloading") if data.get("unloading") else '-',
]
m += 1
l += 1
create_value(worksheet, list1, l + 1, 1)
total_quantity = sum(
item['quantity'] for item in serializer)
# aggregation1_bars = all_bars.aggregate(
# total=Sum('GoodAmount'),
# input_total=Sum('GoodAmount', filter=Q(Out=False)),
# output_total=Sum('GoodAmount', filter=Q(Out=True)),
# input_count=Count('id', filter=Q(Out=False)),
# output_count=Count('id', filter=Q(Out=True)),
# total_count=Count('id')
# )
#
# aggregation1_all_products = all_products_transport.aggregate(
# total=Sum('quantity'),
# input_total=Sum('quantity', filter=Q(out=False)),
# output_total=Sum('quantity', filter=Q(out=True)),
# input_count=Count('id', filter=Q(out=False)),
# output_count=Count('id', filter=Q(out=True)),
# total_count=Count('id')
# )
#
# total_count = (aggregation1_bars['total_count'] or 0) + (aggregation1_all_products['total_count'] or 0)
# total_bars_quantity = (aggregation1_bars['total'] or 0) + (aggregation1_all_products['total'] or 0)
# total_input_bars_quantity = (aggregation1_bars['input_total'] or 0) + (
# aggregation1_all_products['input_total'] or 0)
# total_output_bars_quantity = (aggregation1_bars['output_total'] or 0) + (
# aggregation1_all_products['output_total'] or 0)
# input_bars_count = (aggregation1_bars['input_count'] or 0) + (aggregation1_all_products['input_count'] or 0)
# output_bars_count = (aggregation1_bars['output_count'] or 0) + (aggregation1_all_products['output_count'] or 0)
#
# if total_count > 0:
# total_input_bars_percent = round((input_bars_count / total_count) * 100, 1)
# total_output_bars_percent = round((output_bars_count / total_count) * 100, 1)
# else:
# total_input_bars_percent = 0
# total_output_bars_percent = 0
# value_header_list2 = [
# kill_houses.count(),
# total_count,
# total_bars_quantity,
# input_bars_count,
# total_input_bars_quantity,
# total_input_bars_percent,
# output_bars_count,
# total_output_bars_quantity,
# total_output_bars_percent,
#
# ]
#
# create_value(worksheet, value_header_list2, 3, 5, border_style='thin')
list2 = [
'مجموع==>',
'',
'',
'',
total_quantity,
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
# total_count,
# total_bars_quantity,
# input_bars_count,
# total_input_bars_quantity,
# total_input_bars_percent,
# output_bars_count,
# total_output_bars_quantity,
# total_output_bars_percent,
]
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

View File

@@ -1,3 +1,4 @@
from datetime import datetime
from io import BytesIO
import jdatetime
@@ -324,4 +325,56 @@ def add_chart(
# chart_title="نمودار تغییرات وزن در سردخانه‌ها",
# x_axis_title="سردخانه‌ها",
# y_axis_title="وزن (کیلوگرم)"
# )
# )
def convert_str_to_date(string, with_datetime=None):
"""
Convert a string to a datetime.date object.
This function tries multiple common date formats, including ISO 8601 with or
without milliseconds, and plain 'YYYY-MM-DD'. If the string cannot be parsed,
it returns None.
Parameters:
-----------
string : str
The date string to convert.
Returns:
--------
datetime.date or None
A datetime.date object if conversion succeeds, otherwise None.
Supported formats:
------------------
- 'YYYY-MM-DDTHH:MM:SS.sssZ' (ISO 8601 with milliseconds)
- 'YYYY-MM-DDTHH:MM:SSZ' (ISO 8601 without milliseconds)
- 'YYYY-MM-DD' (Simple date)
"""
string = str(string).strip()
# فرمت‌های مختلف تاریخ
date_formats = [
'%Y-%m-%dT%H:%M:%S.%fZ',
'%Y-%m-%dT%H:%M:%SZ',
'%Y-%m-%dT%H:%M:%S.%f%z', # ✅ با میلی‌ثانیه و تایم‌زون
'%Y-%m-%dT%H:%M:%S%z', # ✅ مثل: 2025-02-26T03:30:00+03:30
'%Y-%m-%dT%H:%M:%S.%f',
'%Y-%m-%dT%H:%M:%S',
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d'
]
for fmt in date_formats:
try:
if with_datetime:
date = datetime.strptime(string, fmt)
else:
date = datetime.strptime(string, fmt).date()
return date
except ValueError:
continue
return None

View File

@@ -2,7 +2,8 @@ from django.urls import include, path
from rest_framework.routers import DefaultRouter
from app import views as app_views
from app.excel_processing import transporting_detail_excel, total_killhouse_excel, hatching_excel, all_hatching_excel, \
all_send_different_bar_excel, transport_carcass_detail_excel, guilds_transport_carcass_detail_excel
all_send_different_bar_excel, transport_carcass_detail_excel, guilds_transport_carcass_detail_excel, \
all_products_transport_excel
from app.helper import get_bar_info, test_city, api_get_hatching_permit_code
from app.scripts import update_poultry_city_province
from app.views import get_transport_to_kill, add_kill_house, update_hatching, get_breeds, dashboard_total_kill_house, \
@@ -234,6 +235,7 @@ urlpatterns = [
path('get-all-products-transport-dashboard-by-code/', get_all_products_transport_dashboard_by_code),
path('get-all-products-transport-products-by-code/', get_all_products_transport_products_by_code),
path('get-all-products-transport-provinces-by-code/', get_all_products_transport_provinces_by_code),
path('all_products_transport_excel/', all_products_transport_excel),
]