""" =============================================================================== FILE: scripts/import_schedules.py ROLE: Импорт режимов работы сотрудников из файла '_СВОДНАЯ_на 04.09.2026.xlsx' в таблицы work_schedule_templates и employee_schedules. =============================================================================== """ import os import sys import re import pandas as pd # Добавляем корень проекта в путь поиска модулей BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if BASE_DIR not in sys.path: sys.path.insert(0, BASE_DIR) from core.connection import get_connection from core.schema import init_all_tables from config import normalize_fio def find_schedules_file(): candidates = [ os.path.join(BASE_DIR, "_СВОДНАЯ_на 04.09.2026.xlsx"), os.path.join(BASE_DIR, "data", "_СВОДНАЯ_на 04.09.2026.xlsx"), os.path.join(BASE_DIR, "data", "uploads", "_СВОДНАЯ_на 04.09.2026.xlsx"), ] for c in candidates: if os.path.exists(c): return c # Поиск любого файла с похожим именем for root, _, files in os.walk(BASE_DIR): for f in files: if "сводная" in f.lower() and f.endswith(".xlsx"): return os.path.join(root, f) return None def clean_time_str(val): if pd.isna(val) or val is None: return None s = str(val).strip().replace('.', ':').rstrip(':').rstrip('.') # Поиск ЧЧ:ММ m = re.search(r'(\d{1,2}):(\d{2})', s) if m: hh = int(m.group(1)) mm = int(m.group(2)) return f"{hh:02d}:{mm:02d}" return None def clean_norm_hours(val): if pd.isna(val) or val is None: return 8.0 try: return float(val) except (ValueError, TypeError): s = str(val).strip() m = re.search(r'(\d+)', s) if m: return float(m.group(1)) return 8.0 def determine_template_code(work_mode_raw, norm_hours, time_start, time_end): mode = str(work_mode_raw).strip().lower() if pd.notna(work_mode_raw) else "офис" if "декрет" in mode: return "MATERNITY", "Декретный отпуск", "MATERNITY", 0.0, None, None, 0, 0 if "дистанцион" in mode: return "REMOTE_STD", "Дистанционная работа (09:00 - 17:30)", "REMOTE", norm_hours, time_start or "09:00", time_end or "17:30", 30, 0 if "гибрид" in mode: code = f"HYBRID_{time_start.replace(':', '') if time_start else '0900'}_{time_end.replace(':', '') if time_end else '1730'}" name = f"Гибридный график ({time_start or '09:00'} - {time_end or '17:30'})" return code, name, "HYBRID", norm_hours, time_start or "09:00", time_end or "17:30", 30, 0 if norm_hours == 22 or (time_start == "07:00" and time_end == "07:00"): return "SHIFT_22H", "Суточная смена (07:00 - 07:00, 22ч)", "OFFICE", 22.0, "07:00", "07:00", 120, 1 if not time_start and not time_end: if norm_hours == 4: return "PART_FLEX_4H", "Неполный день гибкий (4ч)", "OFFICE", 4.0, None, None, 0, 0 return "OFFICE_FLEX", "Гибкий офисный график", "OFFICE", norm_hours, None, None, 30, 0 # Стандартные офисные графики с фиксированным временем ts_clean = time_start.replace(':', '') if time_start else "0900" te_clean = time_end.replace(':', '') if time_end else "1730" h_str = int(norm_hours) if norm_hours.is_integer() else norm_hours code = f"OFFICE_{ts_clean}_{te_clean}_{h_str}H" name = f"Офис {time_start} - {time_end} ({h_str}ч)" lunch = 30 if norm_hours >= 6 else 0 return code, name, "OFFICE", norm_hours, time_start, time_end, lunch, 0 def run_import(): init_all_tables() file_path = find_schedules_file() if not file_path: print("[❌] Файл '_СВОДНАЯ_на 04.09.2026.xlsx' не найден в корне или data/!") return print(f"[1/3] Чтение файла: {file_path} ...") df_raw = pd.read_excel(file_path, header=None) # Заголовок находится на строке 2 (индекс 2) headers = [str(h).strip() for h in df_raw.iloc[2].values[:9]] df = df_raw.iloc[3:, :9].copy() df.columns = headers df = df.dropna(subset=['ФИО сотрудника']).reset_index(drop=True) print(f" Найдено записей сотрудников: {len(df)}") # Словарь шаблонов: code -> template_id template_ids = {} with get_connection() as conn: cursor = conn.cursor() print("[2/3] Формирование справочника шаблонов графиков...") for _, row in df.iterrows(): w_mode = row.get('Место работы (офис/гибрид/дистанционная работа)') norm_h = clean_norm_hours(row.get('Продолжительность рабочего дня')) t_start = clean_time_str(row.get('Начало рабочего дня')) t_end = clean_time_str(row.get('Окончание рабочего дня')) code, name, mode_enum, norm_calc, start_val, end_val, lunch, is_shift = determine_template_code( w_mode, norm_h, t_start, t_end ) if code not in template_ids: cursor.execute(""" INSERT INTO work_schedule_templates (code, name, work_mode, norm_hours, time_start, time_end, lunch_break_minutes, is_shift) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(code) DO UPDATE SET name = excluded.name, norm_hours = excluded.norm_hours, time_start = excluded.time_start, time_end = excluded.time_end """, (code, name, mode_enum, norm_calc, start_val, end_val, lunch, is_shift)) cursor.execute("SELECT id FROM work_schedule_templates WHERE code = ?", (code,)) template_ids[code] = cursor.fetchone()[0] conn.commit() print(f" Создано/обновлено шаблонов графиков: {len(template_ids)}") print("[3/3] Привязка сотрудников к графикам...") imported_count = 0 for _, row in df.iterrows(): fio_raw = str(row.get('ФИО сотрудника', '')).strip() fio_clean = normalize_fio(fio_raw) if not fio_clean: continue dept = str(row.get('Подразделение', '—')).strip() pos = str(row.get('Должность', '—')).strip() w_mode = row.get('Место работы (офис/гибрид/дистанционная работа)') norm_h = clean_norm_hours(row.get('Продолжительность рабочего дня')) t_start = clean_time_str(row.get('Начало рабочего дня')) t_end = clean_time_str(row.get('Окончание рабочего дня')) notes_col = [c for c in df.columns if 'примечани' in c.lower()] comment = str(row.get(notes_col[0], '')).strip() if notes_col and pd.notna(row.get(notes_col[0])) else None basis_col = [c for c in df.columns if 'основани' in c.lower()] basis = str(row.get(basis_col[0], '')).strip() if basis_col and pd.notna(row.get(basis_col[0])) else None code, _, _, _, _, _, _, _ = determine_template_code(w_mode, norm_h, t_start, t_end) t_id = template_ids[code] cursor.execute(""" INSERT INTO employee_schedules (fio, fio_clean, department, position, schedule_template_id, doc_basis, comment, date_from) VALUES (?, ?, ?, ?, ?, ?, ?, '2026-01-01') ON CONFLICT(fio_clean, date_from) DO UPDATE SET department = excluded.department, position = excluded.position, schedule_template_id = excluded.schedule_template_id, doc_basis = excluded.doc_basis, comment = excluded.comment, updated_at = CURRENT_TIMESTAMP """, (fio_raw, fio_clean, dept, pos, t_id, basis, comment)) imported_count += 1 conn.commit() print(f"[✓] Успешно импортировано сотрудников с индивидуальными графиками: {imported_count} чел.") if __name__ == "__main__": run_import()