XH_Digital_Management/application/org_mgnt/views.py

558 lines
23 KiB
Python
Raw Normal View History

2024-06-14 16:47:56 +08:00
import json
import os
2024-06-14 16:47:56 +08:00
from django.apps import apps
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
2024-06-14 16:47:56 +08:00
from django.http import JsonResponse, Http404
2024-06-14 16:47:43 +08:00
from django.shortcuts import render, get_object_or_404
2024-06-07 03:47:15 +08:00
from django.template.loader import render_to_string
2024-05-31 20:17:40 +08:00
from django.urls import reverse
2024-06-14 16:47:56 +08:00
from django.views.decorators.csrf import csrf_protect
from openpyxl import load_workbook
from rest_framework import status
2024-06-06 15:08:38 +08:00
from rest_framework.decorators import api_view, permission_classes
from rest_framework.pagination import PageNumberPagination
2024-06-06 15:08:38 +08:00
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.serializers import ModelSerializer
2024-05-30 13:39:36 +08:00
from application.org_mgnt.forms import (
CompanyEntityForm,
PrimaryDepartmentForm,
SecondaryDepartmentForm
)
from application.org_mgnt.models import (
PrimaryDepartment,
SecondaryDepartment,
CompanyEntity,
CompanyBankAccount
)
from application.org_mgnt.serializers import (
EntityChangeRecordSerializer,
CompanyBankAccountSerializer
)
2024-06-14 16:47:43 +08:00
from common.auth import custom_permission_required
2024-05-31 20:17:40 +08:00
from common.utils.page_helper import paginate_query_and_assign_numbers
class StandardResultsSetPagination(PageNumberPagination):
page_size = 5
page_size_query_param = 'page_size'
max_page_size = 100
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.view_companyentity')
2024-05-31 20:17:40 +08:00
def eir_list_view(request):
# 声明查询集
query_set = CompanyEntity.objects.filter().order_by('-entity_id')
# 获取查询参数
company_name = request.GET.get('company_name', '')
2024-06-04 16:50:30 +08:00
business_status = request.GET.get('business_status', '')
taxpayer_identification_number = request.GET.get('taxpayer_identification_number', '')
2024-05-31 20:17:40 +08:00
# 根据提供的参数进行筛选
2024-06-06 20:56:06 +08:00
if company_name:
2024-06-07 03:47:15 +08:00
query_set = query_set.filter(company_name__icontains=company_name)
2024-06-06 20:56:06 +08:00
if business_status:
query_set = query_set.filter(business_status=business_status)
if taxpayer_identification_number:
2024-06-07 03:47:15 +08:00
query_set = query_set.filter(taxpayer_identification_number__icontains=taxpayer_identification_number)
2024-05-31 20:17:40 +08:00
# 对查询结果进行分页每页10条记录
items = paginate_query_and_assign_numbers(
request=request,
queryset=query_set,
per_page=10
)
# 构建上下文查询参数字符串
2024-06-06 20:56:06 +08:00
query_params = '&company_name={}&business_status={}&taxpayer_identification_number={}'.format(
company_name, business_status, taxpayer_identification_number
)
# Excel上传模板
2024-06-09 17:14:10 +08:00
template_name = "组织管理-公司主体信息登记-Excel上传模板.xlsx"
2024-06-04 16:50:30 +08:00
# 构建上下文
2024-05-31 20:17:40 +08:00
context = {
2024-06-06 20:56:06 +08:00
"model_config": 'org_mgnt.CompanyEntity',
2024-06-04 16:50:30 +08:00
"items": items,
2024-06-06 20:56:06 +08:00
"breadcrumb_list": [
{"title": "首页", "name": "index"},
{"title": "组织管理", "name": "index"},
{"title": "公司主体信息登记表", "name": "eir_list"}
],
2024-06-06 15:08:38 +08:00
"filters": [
{"type": "text", "id": "company_name", "name": "company_name", "label": "公司名称",
"placeholder": "请输入公司名称"},
{"type": "select", "id": "business_status", "name": "business_status", "label": "公司经营状态",
"options": [{"value": "存续", "display": "存续"}, {"value": "注销", "display": "注销"}]},
{"type": "text", "id": "taxpayer_identification_number", "name": "taxpayer_identification_number",
"label": "纳税人识别号", "placeholder": "请输入纳税人识别号"}
2024-06-04 16:50:30 +08:00
],
2024-06-07 03:47:15 +08:00
"table_exclude_field_name": ['entity_id'],
2024-06-06 20:56:06 +08:00
"excel_upload_config": {
2024-06-17 19:38:02 +08:00
"template_url": reverse("dl_excel_tpl", kwargs={'template_name': template_name}),
2024-06-06 20:56:06 +08:00
"parse_url": reverse("common_excel_parse"),
"save_url": reverse("save_excel_table_data"),
"fields_preview_config": {
"company_type": {"type": "text", "width": "180px"},
"company_name": {"type": "text", "width": "180px"},
"registration_address": {"type": "text", "width": "180px"},
"registered_capital": {"type": "text", "width": "180px"},
"capital_paid_time": {"type": "date", "width": "180px"},
"capital_paid": {"type": "text", "width": "180px"},
"establishment_time": {"type": "date", "width": "180px"},
"operation_period": {"type": "text", "width": "180px"},
"taxpayer_identification_number": {"type": "text", "width": "180px"},
"business_status": {"type": "select", "width": "180px", "options": ["存续", "注销"]},
"scope_of_business": {"type": "text", "width": "180px"},
"purpose_of_company": {"type": "text", "width": "180px"},
"shareholders_and_stakes": {"type": "text", "width": "180px"},
"chairman": {"type": "text", "width": "180px"},
"directors": {"type": "text", "width": "180px"},
"supervisor_chairman": {"type": "text", "width": "180px"},
"employee_supervisor": {"type": "text", "width": "180px"},
"supervisors": {"type": "text", "width": "180px"},
"general_manager": {"type": "text", "width": "180px"},
2024-06-14 16:47:56 +08:00
"financial_officer": {"type": "text", "width": "180px"}
2024-06-06 20:56:06 +08:00
}
},
"query_params": query_params,
"form_action_url": 'eir_list',
"modify_url": reverse("eir_list_modify"),
"add_url": reverse("eir_list_add"),
"delete_url": reverse("eir_list_delete"),
2024-05-30 13:39:36 +08:00
}
return render(request, 'ce_list.html', context)
2024-06-04 16:50:30 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.add_companyentity')
2024-06-04 16:50:30 +08:00
def eir_list_add(request):
if request.method == 'POST':
2024-06-07 03:47:15 +08:00
form = CompanyEntityForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"message": "添加成功"})
else:
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html, "errors": form.errors}, status=400)
elif request.method == 'GET':
form = CompanyEntityForm()
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html})
else:
return JsonResponse({"message": "无效的请求方法"}, status=405)
2024-06-04 16:50:30 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.change_companyentity')
2024-06-04 16:50:30 +08:00
def eir_list_modify(request):
if request.method == 'POST':
2024-06-07 03:47:15 +08:00
if 'id' in request.POST:
instance = CompanyEntity.objects.get(entity_id=request.POST['id'])
form = CompanyEntityForm(request.POST, instance=instance)
else:
form = CompanyEntityForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"message": "保存成功"})
else:
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html, "errors": form.errors}, status=400)
elif request.method == 'GET':
if 'id' in request.GET:
try:
instance = CompanyEntity.objects.get(entity_id=request.GET['id'])
form = CompanyEntityForm(instance=instance)
except CompanyEntity.DoesNotExist:
raise Http404("对象不存在")
else:
form = CompanyEntityForm()
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html})
else:
return JsonResponse({"message": "无效的请求方法"}, status=405)
2024-06-04 16:50:30 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.delete_companyentity')
2024-06-04 16:50:30 +08:00
def eir_list_delete(request):
if request.method == 'GET':
2024-06-06 15:08:38 +08:00
target_id = request.GET.get('target_id')
CompanyEntity.objects.filter(entity_id=target_id).delete()
return JsonResponse({"message": "删除成功"})
return JsonResponse({"message": "无效的请求方法"}, status=405)
@api_view(['GET'])
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.view_entitychangerecord')
def change_record_list(request, entity_id):
entity = get_object_or_404(CompanyEntity, pk=entity_id)
change_records = entity.change_records.all().order_by('record_id')
2024-06-06 15:08:38 +08:00
paginator = StandardResultsSetPagination()
paginated_change_records = paginator.paginate_queryset(change_records, request)
2024-06-06 15:08:38 +08:00
serializer = EntityChangeRecordSerializer(paginated_change_records, many=True)
return paginator.get_paginated_response(serializer.data)
2024-06-06 15:08:38 +08:00
@api_view(['GET'])
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.view_companybankaccount')
def bank_account_list(request, entity_id):
entity = get_object_or_404(CompanyEntity, pk=entity_id)
bank_accounts = entity.bank_accounts.all().order_by('account_id')
paginator = StandardResultsSetPagination()
paginated_bank_accounts = paginator.paginate_queryset(bank_accounts, request)
serializer = CompanyBankAccountSerializer(paginated_bank_accounts, many=True)
response = paginator.get_paginated_response(serializer.data)
response_data = response.data
response_data['next_page'] = paginator.page.next_page_number() if paginator.page.has_next() else None
response_data['previous_page'] = paginator.page.previous_page_number() if paginator.page.has_previous() else None
2024-06-06 15:08:38 +08:00
return Response(response_data)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_bank_account_details(request, account_id):
bank_account = get_object_or_404(CompanyBankAccount, pk=account_id)
serializer = CompanyBankAccountSerializer(bank_account)
return Response(serializer.data)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_bank_account(request, entity_id):
entity = get_object_or_404(CompanyEntity, pk=entity_id)
serializer = CompanyBankAccountSerializer(data=request.data)
if serializer.is_valid():
serializer.save(company_entity=entity)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def update_bank_account(request, account_id):
bank_account = get_object_or_404(CompanyBankAccount, pk=account_id)
serializer = CompanyBankAccountSerializer(bank_account, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_bank_account(request, account_id):
bank_account = get_object_or_404(CompanyBankAccount, pk=account_id)
bank_account.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.view_primarydepartment')
2024-06-06 15:08:38 +08:00
def pd_list_view(request):
# 声明查询集
query_set = PrimaryDepartment.objects.filter().order_by('-primary_department_id')
# 获取查询参数
department_name = request.GET.get('department_name', '')
# 根据提供的参数进行筛选
if department_name:
query_set = query_set.filter(department_name__icontains=department_name)
# 对查询结果进行分页每页10条记录
items = paginate_query_and_assign_numbers(
request=request,
queryset=query_set,
per_page=10
)
# 构建上下文查询参数字符串
query_params = '&department_name={}'.format(department_name)
2024-06-06 20:56:06 +08:00
# Excel上传模板
2024-06-09 17:14:10 +08:00
template_name = "组织管理-一级部门-Excel上传模板.xlsx"
2024-06-06 15:08:38 +08:00
# 构建上下文
context = {
2024-06-06 20:56:06 +08:00
"model_config": 'org_mgnt.PrimaryDepartment',
2024-06-06 15:08:38 +08:00
"items": items,
2024-06-06 20:56:06 +08:00
"breadcrumb_list": [
{"title": "首页", "name": "index"},
{"title": "组织管理", "name": "index"},
{"title": "一级部门表", "name": "pd_list"}
],
2024-06-06 15:08:38 +08:00
"filters": [
{"type": "text", "id": "department_name", "name": "department_name", "label": "一级部门名称",
"placeholder": "请输入一级部门名称"}
],
2024-06-07 03:47:15 +08:00
"table_exclude_field_name": ['primary_department_id'],
2024-06-06 20:56:06 +08:00
"excel_upload_config": {
2024-06-17 19:38:02 +08:00
"template_url": reverse("dl_excel_tpl", kwargs={'template_name': template_name}),
2024-06-06 20:56:06 +08:00
"parse_url": reverse("common_excel_parse"),
"save_url": reverse("save_excel_table_data"),
"fields_preview_config": {
"department_name": {"type": "text", "width": "180px"},
"description": {"type": "text", "width": "180px"},
}
},
"query_params": query_params,
"form_action_url": 'pd_list',
"modify_url": reverse("pd_list_modify"),
"add_url": reverse("pd_list_add"),
"delete_url": reverse("pd_list_delete"),
"add_button": True
2024-06-06 15:08:38 +08:00
}
2024-06-07 03:47:15 +08:00
return render(request, 'items_list.html', context)
2024-06-06 15:08:38 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.add_primarydepartment')
2024-06-06 15:08:38 +08:00
def pd_list_add(request):
if request.method == 'POST':
2024-06-07 03:47:15 +08:00
form = PrimaryDepartmentForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"message": "添加成功"})
else:
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html, "errors": form.errors}, status=400)
elif request.method == 'GET':
form = PrimaryDepartmentForm()
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html})
else:
return JsonResponse({"message": "无效的请求方法"}, status=405)
2024-06-06 15:08:38 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.change_primarydepartment')
2024-06-06 15:08:38 +08:00
def pd_list_modify(request):
if request.method == 'POST':
2024-06-07 03:47:15 +08:00
if 'id' in request.POST:
instance = PrimaryDepartment.objects.get(primary_department_id=request.POST['id'])
form = PrimaryDepartmentForm(request.POST, instance=instance)
else:
form = PrimaryDepartmentForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"message": "保存成功"})
else:
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html, "errors": form.errors}, status=400)
elif request.method == 'GET':
if 'id' in request.GET:
try:
instance = PrimaryDepartment.objects.get(primary_department_id=request.GET['id'])
form = PrimaryDepartmentForm(instance=instance)
except PrimaryDepartment.DoesNotExist:
raise Http404("对象不存在")
else:
form = PrimaryDepartmentForm()
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html})
else:
return JsonResponse({"message": "无效的请求方法"}, status=405)
2024-06-06 15:08:38 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.delete_primarydepartment')
2024-06-06 15:08:38 +08:00
def pd_list_delete(request):
if request.method == 'GET':
id = request.GET.get('id')
PrimaryDepartment.objects.filter(primary_department_id=id).delete()
2024-06-06 15:08:38 +08:00
return JsonResponse({"message": "删除成功"})
return JsonResponse({"message": "无效的请求方法"}, status=405)
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.view_secondarydepartment')
2024-06-06 15:08:38 +08:00
def sd_list_view(request):
# 声明查询集
query_set = SecondaryDepartment.objects.filter().order_by('-secondary_department_id')
# 获取查询参数
secondary_department_name = request.GET.get('secondary_department_name', '')
# 根据提供的参数进行筛选
if secondary_department_name:
query_set = query_set.filter(secondary_department_name__icontains=secondary_department_name)
# 对查询结果进行分页每页10条记录
items = paginate_query_and_assign_numbers(
request=request,
queryset=query_set,
per_page=10
)
# 构建上下文查询参数字符串
query_params = '&secondary_department_name={}'.format(secondary_department_name)
2024-06-06 20:56:06 +08:00
# Excel上传模板
2024-06-09 17:14:10 +08:00
template_name = "组织管理-二级部门-Excel上传模板.xlsx"
2024-06-06 15:08:38 +08:00
# 构建上下文
context = {
2024-06-06 20:56:06 +08:00
"model_config": 'org_mgnt.SecondaryDepartment',
2024-06-06 15:08:38 +08:00
"items": items,
2024-06-06 20:56:06 +08:00
"breadcrumb_list": [
{"title": "首页", "name": "index"},
{"title": "组织管理", "name": "index"},
{"title": "二级部门表", "name": "sd_list"}
],
2024-06-06 15:08:38 +08:00
"filters": [
{"type": "text", "id": "secondary_department_name", "name": "secondary_department_name",
2024-06-06 20:56:06 +08:00
"label": "二级部门名称", "placeholder": "请输入二级部门名称"}
2024-06-06 15:08:38 +08:00
],
2024-06-07 03:47:15 +08:00
"table_exclude_field_name": ['secondary_department_id'],
2024-06-06 20:56:06 +08:00
"excel_upload_config": {
2024-06-17 19:38:02 +08:00
"template_url": reverse("dl_excel_tpl", kwargs={'template_name': template_name}),
2024-06-17 10:23:24 +08:00
"parse_url": reverse("common_excel_parse"),
"save_url": reverse("save_excel_table_data"),
2024-06-06 20:56:06 +08:00
"fields_preview_config": {
2024-06-14 16:47:56 +08:00
"primary_department": {"type": "text", "width": "180px"},
2024-06-06 20:56:06 +08:00
"secondary_department_name": {"type": "text", "width": "180px"},
"description": {"type": "text", "width": "180px"},
}
},
"query_params": query_params,
"form_action_url": 'sd_list',
"modify_url": reverse("sd_list_modify"),
"add_url": reverse("sd_list_add"),
"delete_url": reverse("sd_list_delete"),
"add_button": True
2024-06-06 15:08:38 +08:00
}
2024-06-07 03:47:15 +08:00
return render(request, 'items_list.html', context)
2024-06-06 15:08:38 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.add_secondarydepartment')
2024-06-06 15:08:38 +08:00
def sd_list_add(request):
if request.method == 'POST':
2024-06-07 03:47:15 +08:00
form = SecondaryDepartmentForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"message": "添加成功"})
else:
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html, "errors": form.errors}, status=400)
elif request.method == 'GET':
form = SecondaryDepartmentForm()
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html})
else:
return JsonResponse({"message": "无效的请求方法"}, status=405)
2024-06-06 15:08:38 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.change_secondarydepartment')
2024-06-06 15:08:38 +08:00
def sd_list_modify(request):
if request.method == 'POST':
2024-06-07 03:47:15 +08:00
if 'id' in request.POST:
instance = SecondaryDepartment.objects.get(secondary_department_id=request.POST['id'])
form = SecondaryDepartmentForm(request.POST, instance=instance)
else:
form = SecondaryDepartmentForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"message": "保存成功"})
else:
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html, "errors": form.errors}, status=400)
elif request.method == 'GET':
if 'id' in request.GET:
try:
instance = SecondaryDepartment.objects.get(secondary_department_id=request.GET['id'])
form = SecondaryDepartmentForm(instance=instance)
except SecondaryDepartment.DoesNotExist:
raise Http404("对象不存在")
else:
form = SecondaryDepartmentForm()
form_html = render_to_string('form_partial.html', {'form': form}, request)
return JsonResponse({"form_html": form_html})
else:
return JsonResponse({"message": "无效的请求方法"}, status=405)
2024-06-06 15:08:38 +08:00
2024-06-14 16:47:43 +08:00
@custom_permission_required('org_mgnt.delete_secondarydepartment')
2024-06-06 15:08:38 +08:00
def sd_list_delete(request):
if request.method == 'GET':
2024-06-07 03:47:15 +08:00
secondary_department_id = request.GET.get('secondary_department_id')
SecondaryDepartment.objects.filter(secondary_department_id=secondary_department_id).delete()
2024-06-04 16:50:30 +08:00
return JsonResponse({"message": "删除成功"})
return JsonResponse({"message": "无效的请求方法"}, status=405)
2024-06-14 16:47:56 +08:00
@csrf_protect
@login_required
def save_excel_table_data(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
model_config = data.get('model_config')
table_data = data.get('table_data')
if not model_config or not table_data:
return JsonResponse({'error': '缺少必要的参数'}, status=400)
# 分割 model_config 以获取 app_label 和 model_name
try:
app_label, model_name = model_config.split('.')
Model = apps.get_model(app_label, model_name)
except (ValueError, LookupError):
return JsonResponse({'error': '无效的 model_config'}, status=400)
# 获取模型中配置的不需要的字段
exclude_fields = getattr(Model, 'excluded_fields', [])
# 创建模型实例列表
instances = []
for row_data in table_data:
# 处理primary_department字段假设模型中有primary_department字段并且table_data中包含一级部门名称
primary_department_name = row_data.get('primary_department')
if primary_department_name:
try:
primary_department_instance = PrimaryDepartment.objects.get(
department_name=primary_department_name)
row_data['primary_department'] = primary_department_instance
except PrimaryDepartment.DoesNotExist:
return JsonResponse({'error': f'找不到名称为 {primary_department_name} 的一级部门信息。'},
status=400)
try:
# 排除不需要的字段
instance_data = {key: value for key, value in row_data.items() if key not in exclude_fields}
instance = Model(**instance_data)
instance.full_clean() # 验证数据
instances.append(instance)
except ValidationError as e:
return JsonResponse({'error': f'数据校验错误: {e.message_dict}'}, status=400)
except Exception as e:
return JsonResponse({'error': f'创建实例时出错: {str(e)}'}, status=500)
# 批量创建模型实例
try:
Model.objects.bulk_create(instances)
except Exception as e:
return JsonResponse({'error': f'批量保存数据时出错: {str(e)}'}, status=500)
return JsonResponse({'message': '表格数据保存成功'}, status=200)
except json.JSONDecodeError:
return JsonResponse({'error': '无效的JSON格式'}, status=400)
except Exception as e:
return JsonResponse({'error': f'服务器内部错误: {str(e)}'}, status=500)
return JsonResponse({'error': '无效的请求方法'}, status=400)