212 lines
9.4 KiB
Python
212 lines
9.4 KiB
Python
import os
|
|
import sys
|
|
import argparse
|
|
import sqlite3
|
|
import pandas as pd
|
|
from datetime import datetime
|
|
|
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
from config import DATA_DIR, DATE_TODAY, OUTPUT_DIR
|
|
from core.database import (
|
|
get_connection,
|
|
get_available_snapshots,
|
|
get_all_rules_from_db,
|
|
load_scud_from_db_by_snapshot,
|
|
get_latest_snapshot_time
|
|
)
|
|
|
|
DB_PATH = os.path.join(DATA_DIR, "scud_orion_ai.db")
|
|
|
|
|
|
def print_stats():
|
|
"""Выводит общую статистику по записям в таблицах БД."""
|
|
print("\n" + "=" * 60)
|
|
print("📊 СТАТИСТИКА БАЗЫ ДАННЫХ SQLITE (scud_orion_ai.db):")
|
|
print("=" * 60)
|
|
with get_connection() as conn:
|
|
cursor = conn.cursor()
|
|
tables = ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base']
|
|
for t in tables:
|
|
cursor.execute(f"SELECT COUNT(*) FROM {t}")
|
|
cnt = cursor.fetchone()[0]
|
|
print(f" • Таблица [{t:<18}]: {cnt:>6} записей")
|
|
print("=" * 60 + "\n")
|
|
|
|
|
|
def print_snapshots_list(date_str=None):
|
|
"""Выводит реестр снапшотов с идеальным вертикальным выравниванием дефисов и цифр."""
|
|
rows = get_available_snapshots(date_str)
|
|
|
|
print("\n" + "=" * 95)
|
|
print(f"📸 РЕЕСТР СОХРАНЕННЫХ СНАПШОТОВ (СВЕРХУ СВЕЖИЕ) {'ЗА ЛОГИ ' + date_str if date_str else ''}:")
|
|
print("=" * 95)
|
|
|
|
header = f"{'ID снапшота':<16} | {'Дата снапшота (создания)':<24} | {'Дата среза':<12} | {'Записей':<8}"
|
|
print(header)
|
|
print("-" * 95)
|
|
|
|
if not rows:
|
|
print("Снапшотов пока нет.")
|
|
print("=" * 95 + "\n")
|
|
return
|
|
|
|
# Внутрипитоновская хронологическая сортировка: сначала snap_time DESC, затем seq_num DESC
|
|
def snapshot_sort_key(row):
|
|
snap_id = row[0] or ""
|
|
snap_time = row[2] or ""
|
|
|
|
seq_num = 0
|
|
if "-" in snap_id:
|
|
parts = snap_id.replace("Y", "").split("-")
|
|
if len(parts) > 1 and parts[1].isdigit():
|
|
seq_num = int(parts[1])
|
|
|
|
return (snap_time, seq_num)
|
|
|
|
sorted_rows = sorted(rows, key=snapshot_sort_key, reverse=True)
|
|
|
|
for r in sorted_rows:
|
|
snap_id = r[0] if r[0] else '----------'
|
|
log_date = r[1] if r[1] else '—'
|
|
snap_time = r[2] if r[2] else '—'
|
|
count = r[3]
|
|
|
|
# 💡 ИДЕАЛЬНОЕ ВЫРАВНИВАНИЕ: если нет префикса Y, добавляем ведущий пробел
|
|
if not snap_id.startswith("Y"):
|
|
formatted_snap_id = f" {snap_id}"
|
|
else:
|
|
formatted_snap_id = snap_id
|
|
|
|
print(f"{formatted_snap_id:<16} | {snap_time:<24} | {log_date:<12} | {count:<8}")
|
|
|
|
print("=" * 95 + "\n")
|
|
|
|
|
|
def inspect_scud(snapshot_id=None, date_str=None, export_xlsx=None):
|
|
"""Инспектирует логи СКУД за выбранный снапшот или дату и опционально сохраняет XLSX."""
|
|
target_date = date_str if date_str else DATE_TODAY
|
|
|
|
print("\n" + "=" * 90)
|
|
if snapshot_id:
|
|
print(f"🔍 ИНСПЕКЦИЯ СКУД ПО СНАПШОТУ [{snapshot_id}] (Дата: {target_date}):")
|
|
else:
|
|
print(f"🔍 ИНСПЕКЦИЯ СКУД ЗА ТЕКУЩУЮ ДАТУ [{target_date}] (ПОСЛЕДНИЙ СРЕЗ):")
|
|
print("=" * 90)
|
|
|
|
df = load_scud_from_db_by_snapshot(target_date, snapshot_param=snapshot_id)
|
|
|
|
if df.empty:
|
|
print(f"Записи СКУД не найдены.")
|
|
print("=" * 90 + "\n")
|
|
return
|
|
|
|
total = len(df)
|
|
present_cnt = len(df[df['Пришел'] == True]) if 'Пришел' in df.columns else 0
|
|
absent_cnt = total - present_cnt
|
|
|
|
print(f"Всего записей: {total} | Пришли: {present_cnt} | Не пришли: {absent_cnt}")
|
|
print("-" * 90)
|
|
|
|
cols_to_show = ['fio', 'department', 'position', 'time_in', 'first_activity', 'time_out', 'is_present', 'anomaly_flag', 'snapshot_id']
|
|
existing_cols = [c for c in cols_to_show if c in df.columns]
|
|
|
|
print(df[existing_cols].head(30).to_string(index=False))
|
|
if len(df) > 30:
|
|
print(f"\n... и ещё {len(df) - 30} строк.")
|
|
|
|
if export_xlsx:
|
|
out_path = export_xlsx if export_xlsx.endswith('.xlsx') else f"{export_xlsx}.xlsx"
|
|
if not os.path.isabs(out_path):
|
|
out_path = os.path.join(OUTPUT_DIR, out_path)
|
|
|
|
df.to_excel(out_path, index=False)
|
|
print("\n" + "*" * 90)
|
|
print(f"[✓] УСПЕШНЫЙ ЭКСПОРТ ДЕБАГ-ФАЙЛА В EXCEL: {out_path}")
|
|
print("*" * 90)
|
|
|
|
print("=" * 90 + "\n")
|
|
|
|
|
|
def print_anomalies():
|
|
"""Выводит список аномалий СКУД из БД."""
|
|
print("\n" + "=" * 80)
|
|
print("🚨 ИСТОРИЯ НАЙДЕННЫХ АНОМАЛИЙ СКУД ⟷ 1С:")
|
|
print("=" * 80)
|
|
with get_connection() as conn:
|
|
df = pd.read_sql_query("SELECT anomaly_date, fio, anomaly_type, details FROM anomalies_history ORDER BY id DESC LIMIT 50", conn)
|
|
if df.empty:
|
|
print("Аномалии не найдены.")
|
|
else:
|
|
print(df.to_string(index=False))
|
|
print("=" * 80 + "\n")
|
|
|
|
|
|
def print_rules():
|
|
"""Выводит правила базы знаний ИИ."""
|
|
rules = get_all_rules_from_db()
|
|
print("\n" + "=" * 80)
|
|
print("🧠 ПРАВИЛА БАЗЫ ЗНАНИЙ ИИ:")
|
|
print("=" * 80)
|
|
if not rules:
|
|
print("База знаний пуста.")
|
|
else:
|
|
for idx, r in enumerate(rules, 1):
|
|
print(f" {idx}. {r}")
|
|
print("=" * 80 + "\n")
|
|
|
|
|
|
def dump_all_to_excel(out_filename="db_dump_full.xlsx"):
|
|
"""Дампит всю базу SQLite во многостраничный Excel."""
|
|
out_path = os.path.join(OUTPUT_DIR, out_filename)
|
|
print(f"\n[🔄] Создание полного дампа БД в файл: {out_path} ...")
|
|
with get_connection() as conn, pd.ExcelWriter(out_path, engine='openpyxl') as writer:
|
|
for table in ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base']:
|
|
df = pd.read_sql_query(f"SELECT * FROM {table}", conn)
|
|
df.to_excel(writer, sheet_name=table[:31], index=False)
|
|
print(f"[✓] Дамп успешно сохранен: {out_path}\n")
|
|
|
|
|
|
def main():
|
|
help_text = """
|
|
CLI-утилита инспекции и управления SQLite базой данных СКУД (scud_orion_ai.db)
|
|
|
|
ПРИМЕРЫ ЗАПУСКА:
|
|
python scripts/db_cli.py scud -- Выгрузка СКУД за текущую дату (последний снапшот)
|
|
python scripts/db_cli.py scud --snapshot 20260805-001 -- Выгрузка СКУД строго по ID конкретного снапшота
|
|
python scripts/db_cli.py scud --export-xlsx debug_today -- Выгрузить срез СКУД в форматированный Excel-файл
|
|
python scripts/db_cli.py snapshots -- Посмотреть список всех снапшотов с их ID (от новых к старым)
|
|
python scripts/db_cli.py snapshots 04.08.2026 -- Посмотреть снапшоты за конкретную дату
|
|
python scripts/db_cli.py stats -- Общая статистика строк по всем таблицам БД
|
|
python scripts/db_cli.py anomalies -- Посмотреть все найденные аномалии СКУД ⟷ 1С
|
|
python scripts/db_cli.py rules -- Посмотреть правила Базы Знаний ИИ из SQLite
|
|
python scripts/db_cli.py dump [output.xlsx] -- Полный дамп всех таблиц БД в многостраничный Excel
|
|
"""
|
|
parser = argparse.ArgumentParser(
|
|
description=help_text,
|
|
formatter_class=argparse.RawDescriptionHelpFormatter
|
|
)
|
|
parser.add_argument('command', nargs='?', default='stats', choices=['stats', 'snapshots', 'scud', 'anomalies', 'rules', 'dump'], help="Команда: stats | snapshots | scud | anomalies | rules | dump")
|
|
parser.add_argument('param', nargs='?', default=None, help="Параметр команды (дата в формате ДД.ММ.ГГГГ или имя файла)")
|
|
parser.add_argument('--snapshot', type=str, default=None, help="Выбрать конкретный ID снапшота для инспекции (например, '20260805-001', 'Y20260805-001')")
|
|
parser.add_argument('--export-xlsx', type=str, default=None, help="Экспортировать выбранный срез СКУД в Excel-файл")
|
|
|
|
args = parser.parse_args()
|
|
|
|
if args.command == 'stats':
|
|
print_stats()
|
|
elif args.command == 'snapshots':
|
|
print_snapshots_list(date_str=args.param)
|
|
elif args.command == 'scud':
|
|
inspect_scud(snapshot_id=args.snapshot, date_str=args.param, export_xlsx=args.export_xlsx)
|
|
elif args.command == 'anomalies':
|
|
print_anomalies()
|
|
elif args.command == 'rules':
|
|
print_rules()
|
|
elif args.command == 'dump':
|
|
filename = args.param if args.param else "db_dump_full.xlsx"
|
|
dump_all_to_excel(filename)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |