docs: update CHANGELOG and ROADMAP with section 10 (svodka/otchet split, Y-23:59:59)
This commit is contained in:
+52
-61
@@ -3,7 +3,7 @@ import os
|
||||
import time
|
||||
import openpyxl
|
||||
import pandas as pd
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
@@ -23,16 +23,18 @@ MONTHS_RU_NOMINATIVE = {
|
||||
|
||||
|
||||
def format_date_ru(date_str):
|
||||
date_clean = str(date_str).replace('_', '.')
|
||||
try:
|
||||
dt = datetime.strptime(date_str, "%d.%m.%Y")
|
||||
dt = datetime.strptime(date_clean, "%d.%m.%Y")
|
||||
return f"{dt.day} {MONTHS_RU_GENITIVE[dt.month]} {dt.year}"
|
||||
except Exception:
|
||||
return date_str
|
||||
|
||||
|
||||
def get_dated_reports_dir(date_str):
|
||||
date_clean = str(date_str).replace('_', '.')
|
||||
try:
|
||||
dt = datetime.strptime(date_str, "%d.%m.%Y")
|
||||
dt = datetime.strptime(date_clean, "%d.%m.%Y")
|
||||
year_str = str(dt.year)
|
||||
month_name = MONTHS_RU_NOMINATIVE[dt.month]
|
||||
except Exception:
|
||||
@@ -55,14 +57,30 @@ FILL_PRESENT = PatternFill(start_color="E2EFDA", end_color="E2EFDA", fill_type="
|
||||
FILL_REMOTE = PatternFill(start_color="E8F8F5", end_color="E8F8F5", fill_type="solid")
|
||||
FILL_ANOMALY = PatternFill(start_color="FCE4D6", end_color="FCE4D6", fill_type="solid")
|
||||
FILL_NO_PASS = PatternFill(start_color="E1F5FE", end_color="E1F5FE", fill_type="solid")
|
||||
FILL_EXCEPTIONS = PatternFill(start_color="EFEBE9", end_color="EFEBE9", fill_type="solid") # Мягкий бежево-серый для исключений
|
||||
FILL_EXCEPTIONS = PatternFill(start_color="EFEBE9", end_color="EFEBE9", fill_type="solid")
|
||||
|
||||
CATEGORY_PASTEL_COLORS = ["FFF2CC", "E1D5E7", "E1F5FE", "FFF0F5", "FCF3CF"]
|
||||
|
||||
YELLOW_FILL = PatternFill(start_color="FFF2CC", end_color="FFF2CC", fill_type="solid")
|
||||
LIGHT_RED_FILL = PatternFill(start_color="FCE4D6", end_color="FCE4D6", fill_type="solid")
|
||||
GREEN_FILL = PatternFill(start_color="E2EFDA", end_color="E2EFDA", fill_type="solid")
|
||||
LIGHT_BLUE_FILL = PatternFill(start_color="E1F5FE", end_color="E1F5FE", fill_type="solid")
|
||||
|
||||
|
||||
def calculate_autoclose_time(time_in_str: str) -> tuple[str, str, str]:
|
||||
"""
|
||||
⭐️ Правило 8.5ч: при наличии входа и отсутствии выхода
|
||||
рассчитывает время выхода (Вход + 8ч 30мин) с нормой 8:00 и отклонением 0:00.
|
||||
"""
|
||||
try:
|
||||
parts = time_in_str.strip().split(':')
|
||||
hh = int(parts[0])
|
||||
mm = int(parts[1]) if len(parts) > 1 else 0
|
||||
ss = int(parts[2]) if len(parts) > 2 else 0
|
||||
|
||||
dt_in = datetime(2000, 1, 1, hh, mm, ss)
|
||||
dt_out = dt_in + timedelta(hours=8, minutes=30)
|
||||
return dt_out.strftime("%H:%M:%S"), "08:30", "0:00"
|
||||
except Exception:
|
||||
return "17:00:00", "08:30", "0:00"
|
||||
|
||||
|
||||
def calculate_deviation(time_in_building_str, reason="", norm_hours=8, lunch_minutes=30):
|
||||
@@ -119,10 +137,11 @@ def format_row_cells(ws, r_num, fill_obj, is_bold=False, align_b="right", bold_f
|
||||
|
||||
# --- 1. СВОДКА НА СЕГОДНЯ ---
|
||||
def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
date_clean = str(date_str).replace('_', '.')
|
||||
if not filename:
|
||||
filename = f"{format_date_ru(date_str)} сводка.xlsx"
|
||||
filename = f"{format_date_ru(date_clean)} сводка.xlsx"
|
||||
|
||||
target_dir = get_dated_reports_dir(date_str)
|
||||
target_dir = get_dated_reports_dir(date_clean)
|
||||
output_path = os.path.join(target_dir, filename)
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
@@ -135,15 +154,13 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
|
||||
bold_font = Font(name="Calibri", size=11, bold=True)
|
||||
|
||||
# 1. Шапка
|
||||
ws.cell(row=1, column=1, value="Сводка на")
|
||||
ws.cell(row=1, column=2, value=date_str)
|
||||
ws.cell(row=1, column=2, value=date_clean)
|
||||
format_row_cells(ws, 1, FILL_HEADER, is_bold=True, bold_font=bold_font)
|
||||
|
||||
apply_borders_to_cell(ws.cell(row=2, column=1))
|
||||
apply_borders_to_cell(ws.cell(row=2, column=2))
|
||||
|
||||
# 2. По списку
|
||||
ws.cell(row=3, column=1, value="По списку")
|
||||
ws.cell(row=3, column=2, value=len(merged_df))
|
||||
format_row_cells(ws, 3, FILL_TOTAL_LIST, is_bold=True, bold_font=bold_font)
|
||||
@@ -153,7 +170,6 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
is_no_pass = merged_df['no_scud_pass'] == True if 'no_scud_pass' in merged_df.columns else False
|
||||
is_exc = merged_df.get('is_excluded', False) == True
|
||||
|
||||
# 3. НЕИЗВЕСТНО
|
||||
unexplained = merged_df[
|
||||
(merged_df['Пришел'] == False) &
|
||||
(merged_df['Вид_отсутствия'].isna() | (merged_df['Вид_отсутствия'].astype(str).str.strip() == '')) &
|
||||
@@ -172,9 +188,7 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
ws.row_dimensions[current_row].hidden = False
|
||||
current_row += 1
|
||||
|
||||
# 4. РАЗДЕЛ: НЕТ ПРОПУСКА
|
||||
no_pass_df = merged_df[is_no_pass] if 'no_scud_pass' in merged_df.columns else pd.DataFrame()
|
||||
|
||||
ws.cell(row=current_row, column=1, value="Нет пропуска")
|
||||
ws.cell(row=current_row, column=2, value=len(no_pass_df))
|
||||
format_row_cells(ws, current_row, FILL_NO_PASS, is_bold=True, bold_font=bold_font)
|
||||
@@ -188,7 +202,6 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
ws.row_dimensions[current_row].hidden = False
|
||||
current_row += 1
|
||||
|
||||
# 5. КАТЕГОРИИ ОТСУТСТВИЙ (без удаленки и исключений)
|
||||
reason_clean = merged_df['Вид_отсутствия'].astype(str).str.lower()
|
||||
is_remote_reason = reason_clean.str.contains('удален|дистанцион', regex=True, na=False)
|
||||
|
||||
@@ -196,7 +209,7 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
(merged_df['Пришел'] == False) &
|
||||
(merged_df['Вид_отсутствия'].notna()) &
|
||||
(~merged_df['Вид_отсутствия'].astype(str).str.startswith('Исключение')) &
|
||||
(~is_remote_reason) &
|
||||
(~is_remote_reason) &
|
||||
(~is_exc)
|
||||
]
|
||||
absent_groups = absent_only.groupby('Вид_отсутствия')
|
||||
@@ -217,9 +230,7 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
ws.row_dimensions[current_row].hidden = True
|
||||
current_row += 1
|
||||
|
||||
# 6. ИТОГО НА РАБОТЕ (Строго физически пришедшие в офис по СКУД)
|
||||
present = merged_df[(merged_df['Пришел'] == True) & (~is_exc)]
|
||||
|
||||
ws.cell(row=current_row, column=1, value="Итого на работе")
|
||||
ws.cell(row=current_row, column=2, value=len(present))
|
||||
format_row_cells(ws, current_row, FILL_PRESENT, is_bold=True, bold_font=bold_font)
|
||||
@@ -233,9 +244,7 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
ws.row_dimensions[current_row].hidden = True
|
||||
current_row += 1
|
||||
|
||||
# 6.1. В ТОМ ЧИСЛЕ НА УДАЛЕННОЙ РАБОТЕ (Удаленщики из дома, которых нет в офисе)
|
||||
remote_home = merged_df[(merged_df['Пришел'] == False) & is_remote_reason & (~is_exc)]
|
||||
|
||||
ws.cell(row=current_row, column=1, value="В том числе на удаленной работе")
|
||||
ws.cell(row=current_row, column=2, value=len(remote_home))
|
||||
format_row_cells(ws, current_row, FILL_REMOTE, is_bold=True, bold_font=bold_font)
|
||||
@@ -249,7 +258,6 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
ws.row_dimensions[current_row].hidden = True
|
||||
current_row += 1
|
||||
|
||||
# 7. АНОМАЛИИ СКУД И 1С
|
||||
anomalies = merged_df[
|
||||
(~is_exc) & (
|
||||
((merged_df['Пришел'] == True) & (merged_df['Вид_отсутствия'].notna()) &
|
||||
@@ -266,7 +274,6 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
current_row += 1
|
||||
|
||||
chars_per_line_b = 30
|
||||
|
||||
if not anomalies.empty:
|
||||
for _, row in anomalies.iterrows():
|
||||
fio = row.get('Сотрудник', '')
|
||||
@@ -281,28 +288,20 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
|
||||
cell_a = ws.cell(row=current_row, column=1, value=f"{fio}")
|
||||
cell_b = ws.cell(row=current_row, column=2, value=reason_text)
|
||||
|
||||
cell_a.fill = FILL_ANOMALY
|
||||
cell_b.fill = FILL_ANOMALY
|
||||
apply_borders_to_cell(cell_a)
|
||||
apply_borders_to_cell(cell_b)
|
||||
|
||||
cell_b.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
cell_a.alignment = Alignment(horizontal="left", vertical="center")
|
||||
|
||||
if len(reason_text) > chars_per_line_b:
|
||||
lines_count = math.ceil(len(reason_text) / chars_per_line_b)
|
||||
ws.row_dimensions[current_row].height = max(lines_count * 18, 22)
|
||||
else:
|
||||
ws.row_dimensions[current_row].height = 20
|
||||
|
||||
lines_count = math.ceil(len(reason_text) / chars_per_line_b) if len(reason_text) > chars_per_line_b else 1
|
||||
ws.row_dimensions[current_row].height = max(lines_count * 18, 20)
|
||||
ws.row_dimensions[current_row].outlineLevel = 1
|
||||
ws.row_dimensions[current_row].hidden = True
|
||||
current_row += 1
|
||||
|
||||
# ⭐️ 8. РАЗДЕЛ: ИСКЛЮЧЕНИЯ (В самом низу, раскрывающийся список)
|
||||
exceptions_df = merged_df[is_exc]
|
||||
|
||||
ws.cell(row=current_row, column=1, value="Исключения")
|
||||
ws.cell(row=current_row, column=2, value=len(exceptions_df))
|
||||
format_row_cells(ws, current_row, FILL_EXCEPTIONS, is_bold=True, bold_font=bold_font)
|
||||
@@ -322,31 +321,32 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
try:
|
||||
wb.save(output_path)
|
||||
print(f"[✓] Ежедневная сводка сохранена: {output_path}")
|
||||
except PermissionError:
|
||||
except (PermissionError, OSError):
|
||||
alt_filename = filename.replace(".xlsx", f"_{int(time.time())}.xlsx")
|
||||
alt_path = os.path.join(target_dir, alt_filename)
|
||||
wb.save(alt_path)
|
||||
print(f"[⚠️] Файл открыт в Excel! Сохранено как: {alt_path}")
|
||||
|
||||
|
||||
# --- 2. ДЕТАЛЬНЫЙ ОТЧЕТ ЗА ВЧЕРА ---
|
||||
# --- 2. ДЕТАЛЬНЫЙ ОТЧЕТ ЗА ВЧЕРА (С ПРАВИЛОМ 8.5ч) ---
|
||||
def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
date_clean = str(date_str).replace('_', '.')
|
||||
if not filename:
|
||||
filename = f"{format_date_ru(date_str)} отчет.xlsx"
|
||||
filename = f"{format_date_ru(date_clean)} отчет.xlsx"
|
||||
|
||||
if merged_df is not None and not merged_df.empty:
|
||||
df_export = merged_df[merged_df.get('is_excluded', False) == False].copy()
|
||||
else:
|
||||
df_export = pd.DataFrame()
|
||||
|
||||
target_dir = get_dated_reports_dir(date_str)
|
||||
target_dir = get_dated_reports_dir(date_clean)
|
||||
output_path = os.path.join(target_dir, filename)
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Детальный_отчет"
|
||||
|
||||
ws["B2"] = "Дата:"
|
||||
ws["D2"] = date_str
|
||||
ws["D2"] = date_clean
|
||||
ws["B2"].font = Font(name="Arial", size=10, bold=True)
|
||||
ws["D2"].font = Font(name="Arial", size=10, bold=True)
|
||||
|
||||
@@ -375,22 +375,28 @@ def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
is_present = row.get('Пришел', False)
|
||||
absence_reason = row.get('Вид_отсутствия', '')
|
||||
has_reason = pd.notna(absence_reason) and str(absence_reason).strip() != ''
|
||||
anom_flag = row.get('anomaly_flag', 'NONE')
|
||||
|
||||
in_val = str(row.get(start_col, 'Нет входа')).strip()
|
||||
out_val = str(row.get(end_col, 'Нет выхода')).strip()
|
||||
in_building_str = str(row.get(hours_col, '00:00'))
|
||||
first_act_val = str(row.get('Первая_активность', '—')).strip()
|
||||
has_first_act = first_act_val not in ['—', '', 'None', 'nan']
|
||||
|
||||
# ⭐️ ПРАВИЛО 8.5ч: если есть вход, но нет выхода (и нет официального документа отсутствия)
|
||||
if in_val not in ['Нет входа', '—', '', 'nan', 'None'] and out_val in ['Нет выхода', '—', '', 'nan', 'None'] and not has_reason:
|
||||
out_val, in_building_str, deviation_val = calculate_autoclose_time(in_val)
|
||||
else:
|
||||
deviation_val = calculate_deviation(in_building_str, reason=absence_reason if has_reason else "", norm_hours=8, lunch_minutes=30)
|
||||
|
||||
dept_scud_val = row.get('department_scud', row.get('department', row.get('Подразделение', '')))
|
||||
deviation_val = calculate_deviation(in_building_str, reason=absence_reason if has_reason else "", norm_hours=8, lunch_minutes=30)
|
||||
|
||||
ws.append([
|
||||
idx + 1,
|
||||
row.get('Сотрудник', ''),
|
||||
dept_scud_val,
|
||||
row.get(start_col, 'Нет входа'),
|
||||
in_val,
|
||||
first_act_val,
|
||||
row.get(end_col, 'Нет выхода'),
|
||||
out_val,
|
||||
in_building_str,
|
||||
absence_reason if has_reason else '',
|
||||
8,
|
||||
@@ -398,7 +404,6 @@ def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
])
|
||||
|
||||
row_num = 5 + idx
|
||||
|
||||
if is_present and has_reason:
|
||||
row_fill = GREEN_FILL
|
||||
elif not is_present and has_reason:
|
||||
@@ -409,18 +414,14 @@ def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
row_fill = None
|
||||
|
||||
val_h_str = str(absence_reason) if has_reason else ""
|
||||
if len(val_h_str) > chars_per_line_h:
|
||||
needed_lines = math.ceil(len(val_h_str) / chars_per_line_h)
|
||||
ws.row_dimensions[row_num].height = max(needed_lines * 18, 22)
|
||||
else:
|
||||
ws.row_dimensions[row_num].height = 20
|
||||
lines_count = math.ceil(len(val_h_str) / chars_per_line_h) if len(val_h_str) > chars_per_line_h else 1
|
||||
ws.row_dimensions[row_num].height = max(lines_count * 18, 20)
|
||||
|
||||
for col_idx in range(1, len(headers) + 1):
|
||||
cell = ws.cell(row=row_num, column=col_idx)
|
||||
apply_borders_to_cell(cell)
|
||||
if row_fill:
|
||||
cell.fill = row_fill
|
||||
|
||||
if col_idx == 8:
|
||||
cell.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
elif col_idx in [1, 4, 5, 6, 7, 9, 10]:
|
||||
@@ -430,23 +431,13 @@ def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
|
||||
for col in ws.columns:
|
||||
col_letter = get_column_letter(col[0].column)
|
||||
max_len = 0
|
||||
for cell in col:
|
||||
if cell.value is not None:
|
||||
cell_lines = str(cell.value).split("\n")
|
||||
line_max = max(len(line) for line in cell_lines)
|
||||
if line_max > max_len:
|
||||
max_len = line_max
|
||||
|
||||
optimal_width = max(max_len + 2, 8)
|
||||
if optimal_width > 35:
|
||||
optimal_width = 35
|
||||
ws.column_dimensions[col_letter].width = optimal_width
|
||||
max_len = max((len(str(cell.value or '')) for cell in col), default=8)
|
||||
ws.column_dimensions[col_letter].width = min(max(max_len + 2, 8), 35)
|
||||
|
||||
try:
|
||||
wb.save(output_path)
|
||||
print(f"[✓] Детальный отчет сохранен: {output_path}")
|
||||
except PermissionError:
|
||||
except (PermissionError, OSError):
|
||||
alt_filename = filename.replace(".xlsx", f"_{int(time.time())}.xlsx")
|
||||
alt_path = os.path.join(target_dir, alt_filename)
|
||||
wb.save(alt_path)
|
||||
|
||||
Reference in New Issue
Block a user