279 lines
11 KiB
Python
279 lines
11 KiB
Python
from datetime import datetime
|
||
import os
|
||
from openpyxl import load_workbook
|
||
import openpyxl
|
||
from rest_framework.response import Response
|
||
from datetime import date
|
||
from .serializers import *
|
||
from .models import *
|
||
import pandas as pd
|
||
from rest_framework.views import APIView
|
||
from userauth.models import *
|
||
from django.shortcuts import render
|
||
from pandas.io.excel import ExcelWriter
|
||
import openpyxl as oxl
|
||
from openpyxl import Workbook
|
||
from openpyxl.styles import Font, Alignment, Side, Border, PatternFill
|
||
from openpyxl.worksheet.formula import ArrayFormula
|
||
from pandas.api.types import CategoricalDtype
|
||
import urllib.request
|
||
|
||
class GeneralVacationAPIView(APIView):
|
||
def get(self, request):
|
||
general = GeneralVacation.objects.all()
|
||
plan = PlanCalendar.objects.all()
|
||
|
||
# Сериализуем извлечённый набор записей
|
||
serializer_for_basecrit = GeneralVacationSerializer(
|
||
instance=general, # Передаём набор записей
|
||
many=True # Указываем, что на вход подаётся именно набор записей
|
||
)
|
||
|
||
serializer_for_plan = PlanCalendarSerializer(
|
||
instance=plan, # Передаём набор записей
|
||
many=True # Указываем, что на вход подаётся именно набор записей
|
||
)
|
||
return Response({"Отпуск": serializer_for_basecrit.data, "План-график": serializer_for_plan.data})
|
||
|
||
class DailyRoundUpAPIView(APIView):
|
||
|
||
def convert_width(self, width):
|
||
"""
|
||
Конвертируем ширину столбца Excel в ширину столбца openpyxl
|
||
"""
|
||
PIXELS_PER_CHAR = 7
|
||
return (width) / PIXELS_PER_CHAR
|
||
|
||
|
||
|
||
def get(self, request):
|
||
user = DictEmployee.objects.using('user_directory').filter(deleted=0).values('login', 'department', 'familyname', 'name', 'parentname')
|
||
df = pd.DataFrame.from_records(user)
|
||
df['tabel'] = df['login'].str.split('-', expand = True)[1]+df['login'].str.split('-', expand = True)[2]
|
||
file_path = 'media/DailyRoundUp.xlsx'
|
||
|
||
thins = Side(border_style="thin")
|
||
# l = pd.DataFrame(df[(df.department=='Руководство')][['tabel', 'familyname', 'name', 'parentname']])
|
||
# l.to_excel(file_path, sheet_name="Список", index= False, header= False, startcol=2, startrow=8)
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
filters = ws.auto_filter
|
||
filters.ref = "A6:L15"
|
||
ws.title = "Список"
|
||
ws['B2'] = 'Список сотрудников'
|
||
ws['B3'] = 'МИ ФНС России по ЦОД № 2'
|
||
ws['B4'] = 'по подразделениям'
|
||
|
||
ws['B6'] = 'Таб.'
|
||
ws['C6'] = 'Фамилия'
|
||
ws['D6'] = 'Имя'
|
||
ws['E6'] = 'Очество'
|
||
|
||
for col in ws.iter_cols(min_row=6, max_row=6, min_col=2, max_col=5):
|
||
for cell in col:
|
||
cell.font = Font(name='Times New Roman', size=11, bold=True)
|
||
cell.border = Border(top=thins, bottom=thins, left=thins, right=thins)
|
||
|
||
ws['G6'] = 'Отпуск'
|
||
ws['I6'] = 'Болен'
|
||
ws['K6'] = 'Удаленка'
|
||
|
||
# ws['F99']= ArrayFormula("A1:A90", "=SUM(C2:C11*D2:D11)")
|
||
|
||
|
||
|
||
heads =['G6', 'I6', 'K6']
|
||
for x in heads:
|
||
|
||
ws[x].fill = PatternFill(fgColor="00FFFF00", fill_type = "solid")
|
||
ws[x].font = Font(name='Times New Roman', size=10, bold=True)
|
||
ws[x].border = Border(top=thins, bottom=thins, left=thins, right=thins)
|
||
ws[x].alignment = Alignment(horizontal='center')
|
||
# for col in ws.iter_cols(min_row=6, max_row=6, min_col=2, max_col=5):
|
||
# for cell in col:
|
||
# cell.font = Font(name='Times New Roman', size=11, bold=True)
|
||
# cell.border = Border(top=thins, bottom=thins, left=thins, right=thins)
|
||
|
||
|
||
ws['I1'] = 'На '+ date.today().strftime("%d.%m.%Y")
|
||
|
||
numb = 1
|
||
|
||
column_widths = [29, 53, 96, 96, 112, 28, 222, 29, 148, 28, 145, 33]
|
||
for i, width in enumerate(column_widths):
|
||
column_letter = openpyxl.utils.get_column_letter(i+1)
|
||
ws.column_dimensions[column_letter].width = self.convert_width(width)
|
||
|
||
|
||
|
||
for col in ws.iter_cols(min_row=2, max_row=5, min_col=2, max_col=5):
|
||
for cell in col:
|
||
cell.font = Font(name='Times New Roman', size=12, bold=True)
|
||
cell.alignment = Alignment(horizontal='center')
|
||
|
||
ws['I1'].font = Font(name='Times New Roman', size=14, bold=True)
|
||
ws['I1'].alignment = Alignment(horizontal='left')
|
||
|
||
|
||
for x in range(3):
|
||
ws.merge_cells(start_row=2+x, start_column=2, end_row=2+x, end_column=6)
|
||
|
||
|
||
k=7
|
||
|
||
|
||
for i in sorted(df['department'].unique(), reverse=True):
|
||
|
||
ws.cell(row = k, column = 2).value = i
|
||
|
||
ws.cell(row = k, column = 2).font = Font(name='Times New Roman', size=10, bold=True)
|
||
ws.merge_cells(start_row=k, start_column=2, end_row=k, end_column=12)
|
||
|
||
l = pd.DataFrame(df[(df.department==i)][['tabel', 'familyname', 'name', 'parentname']])
|
||
|
||
zap = [7, 9, 11]
|
||
for x in range(len(l)):
|
||
k=k+1
|
||
|
||
ws.cell(row = k, column = 1).value = numb
|
||
ws.cell(row = k, column = 1).font = Font(name='Times New Roman', size=10, bold=True)
|
||
|
||
ws.cell(row = k, column = 2).value = l.iloc[x]['tabel']
|
||
ws.cell(row = k, column = 3).value = l.iloc[x]['familyname']
|
||
ws.cell(row = k, column = 4).value = l.iloc[x]['name']
|
||
ws.cell(row = k, column = 5).value = l.iloc[x]['parentname']
|
||
|
||
for h in zap:
|
||
ws.cell(row = k, column = h).border = Border(top=thins, bottom=thins, left=thins, right=thins)
|
||
ws.cell(row = k, column = h).font = Font(name='Times New Roman', size=10)
|
||
ws.cell(row = k, column = h).alignment = Alignment(horizontal='center')
|
||
|
||
|
||
for v in range(4):
|
||
ws.cell(row = k, column = 2+v).font = Font(name='Times New Roman', size=10)
|
||
ws.cell(row = k, column = 2+v).border = Border(top=thins, bottom=thins, left=thins, right=thins)
|
||
|
||
|
||
numb=numb+1
|
||
|
||
k=k+1
|
||
|
||
ws.cell(row = k+1, column=6).value = "=SUM(F6:F"+str(k-1)+")"
|
||
ws.cell(row = k+1, column=6).fill = PatternFill(fgColor="00FFFF00", fill_type = "solid")
|
||
ws.cell(row = k+1, column=6).font = Font(name='Times New Roman', size=13, bold=True)
|
||
|
||
ws.cell(row = k+1, column=7).value = "ВСЕГО отпуск="
|
||
ws.cell(row = k+1, column=7).fill = PatternFill(fgColor="00FFFF00", fill_type = "solid")
|
||
ws.cell(row = k+1, column=7).font = Font(name='Times New Roman', size=10, bold=True)
|
||
|
||
ws.cell(row = k+1, column=8).value = "=SUM(H6:H"+str(k-1)+")"
|
||
ws.cell(row = k+1, column=8).fill = PatternFill(fgColor="00FFFF00", fill_type = "solid")
|
||
ws.cell(row = k+1, column=8).font = Font(name='Times New Roman', size=10, bold=True)
|
||
|
||
ws.cell(row = k+1, column=9).value = "Всего больных="
|
||
ws.cell(row = k+1, column=9).fill = PatternFill(fgColor="8EA9DB", fill_type = "solid")
|
||
ws.cell(row = k+1, column=9).font = Font(name='Times New Roman', size=10, bold=True)
|
||
|
||
ws.cell(row = k+1, column=10).value = "=SUM(J6:J"+str(k-1)+")"
|
||
ws.cell(row = k+1, column=10).fill = PatternFill(fgColor="8EA9DB", fill_type = "solid")
|
||
ws.cell(row = k+1, column=10).font = Font(name='Times New Roman', size=10, bold=True)
|
||
|
||
ws.cell(row = k+1, column=11).value = "Всего удаленка="
|
||
ws.cell(row = k+1, column=11).fill = PatternFill(fgColor="8EA9DB", fill_type = "solid")
|
||
ws.cell(row = k+1, column=11).font = Font(name='Times New Roman', size=10, bold=True)
|
||
|
||
ws.cell(row = k+1, column=12).value = "=SUM(L6:L"+str(k-1)+")"
|
||
ws.cell(row = k+1, column=12).fill = PatternFill(fgColor="8EA9DB", fill_type = "solid")
|
||
ws.cell(row = k+1, column=12).font = Font(name='Times New Roman', size=10, bold=True)
|
||
|
||
ws.cell(row = k+3, column=5).value = "ИТОГО"
|
||
ws.cell(row = k+3, column=5).font = Font(name='Times New Roman', size=14, bold=True)
|
||
|
||
ws.cell(row = k+3, column=7).value = "факт работающих"
|
||
ws.cell(row = k+3, column=7).font = Font(name='Times New Roman', size=14, bold=True)
|
||
|
||
|
||
ws.cell(row = k+3, column=8).value = f"=F{k+1}-H{k+1}-J{k+1}-L{k+1}"
|
||
ws.cell(row = k+3, column=8).font = Font(name='Times New Roman', size=14, bold=True)
|
||
|
||
|
||
|
||
wb.save(file_path)
|
||
|
||
|
||
|
||
|
||
return Response(file_path)
|
||
|
||
|
||
|
||
def post(self, request):
|
||
user = DictEmployee.objects.using('user_directory').filter(deleted=0).values('login', 'id')
|
||
dfuser = pd.DataFrame.from_records(user)
|
||
# print(dfuser)
|
||
file = request.data['dailyfiles']
|
||
ed = pd.read_excel(file)
|
||
df = pd.DataFrame(ed)
|
||
|
||
datas = df.columns[8].split(" ")[1]
|
||
|
||
|
||
|
||
# DailyRoundUp.objects.update_or_create(todaysDate=datetime.datetime.strptime(datas, '%d.%m.%Y').strftime('%Y-%m-%d'), defaults={'user':self.request.user, 'position':base})
|
||
df.columns = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
|
||
df=df.iloc[6:]
|
||
df= df[df.b.notna()]
|
||
df= df[df.a.notna()]
|
||
df['b']=df['b'].str[-3:]
|
||
df=df[['b', 'f', 'h', 'j','l']]
|
||
|
||
df['b'] = df['b'].astype(int)
|
||
|
||
types = ['f', 'h', 'j','l']
|
||
for n in types:
|
||
df[n] = df[n].fillna(0)
|
||
df[n] = df[n].astype(int)
|
||
|
||
df3 = pd.merge(df, dfuser, left_on= 'b', right_on="id")
|
||
df3=df3[['login', 'f', 'h', 'j','l']]
|
||
|
||
|
||
|
||
for ind in df3.index:
|
||
keys = ''
|
||
if df3['h'][ind] == 1:
|
||
keys = 4 # В отпуске
|
||
elif df3['j'][ind] == 1:
|
||
keys = 5 # Болен
|
||
elif df3['l'][ind] == 1:
|
||
keys = 2 # Удаленка
|
||
else:
|
||
keys = 6
|
||
base=BasePosition.objects.get(pk=keys)
|
||
DailyRoundUp.objects.update_or_create(todaysDate=datetime.strptime(datas, '%d.%m.%Y').strftime('%Y-%m-%d'),
|
||
user=df3['login'][ind], defaults={'position':base})
|
||
|
||
|
||
|
||
# serializer_for_daily = DailyRoundUpSerializer(
|
||
# instance=daily, # Передаём набор записей
|
||
# many=True # Указываем, что на вход подаётся именно набор записей
|
||
# )
|
||
|
||
|
||
|
||
return Response("")
|
||
|
||
|
||
class DailyloadAPIView(APIView):
|
||
def get(self, request):
|
||
daily = DailyRoundUp.objects.filter(todaysDate=datetime.now())
|
||
print(daily, '-----------------------------')
|
||
|
||
#
|
||
# serializer_for_daily = DailyRoundUpSerializer(
|
||
# instance=daily, # Передаём набор записей
|
||
# many=True # Указываем, что на вход подаётся именно набор записей
|
||
# )
|
||
return Response('kkkk')
|
||
# return Response({"Обход":serializer_for_daily}) |