|
| 1 | +import dataclasses |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import pathlib |
| 6 | +import shutil |
| 7 | +import tempfile |
| 8 | +import uuid |
| 9 | +from datetime import datetime |
| 10 | +from typing import List |
| 11 | + |
| 12 | +from flask import ( |
| 13 | + Blueprint, |
| 14 | + current_app, |
| 15 | + flash, |
| 16 | + redirect, |
| 17 | + render_template, |
| 18 | + request, |
| 19 | + url_for, |
| 20 | +) |
| 21 | +from werkzeug.utils import secure_filename |
| 22 | + |
| 23 | +from app.db.database import db |
| 24 | +from app.models.models import Employee, ScheduleEntry |
| 25 | +from app.services.importer.factory import ImporterFactory |
| 26 | +from app.services.importer.protocol import ImportResult |
| 27 | +from app.utils.time_calculator import calculate_daily_hours |
| 28 | + |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | + |
| 32 | +import_log_bp = Blueprint("import_log", __name__, url_prefix="/import") |
| 33 | + |
| 34 | +# Configure upload folder |
| 35 | +UPLOAD_FOLDER = os.path.join(os.getcwd(), "uploads") |
| 36 | +os.makedirs(UPLOAD_FOLDER, exist_ok=True) |
| 37 | + |
| 38 | + |
| 39 | +@import_log_bp.route("/", methods=["GET", "POST"]) |
| 40 | +def upload_file(): |
| 41 | + if request.method == "POST": |
| 42 | + if "file" not in request.files: |
| 43 | + flash("No file part", "error") |
| 44 | + return redirect(request.url) |
| 45 | + |
| 46 | + file = request.files["file"] |
| 47 | + if file.filename == "": |
| 48 | + flash("No selected file", "error") |
| 49 | + return redirect(request.url) |
| 50 | + |
| 51 | + if file: |
| 52 | + filename = secure_filename(file.filename or "") |
| 53 | + file_ext = filename.split(".")[-1].lower() |
| 54 | + |
| 55 | + if file_ext not in ["pdf", "xlsx", "xls"]: |
| 56 | + flash("Unsupported file type", "error") |
| 57 | + return redirect(request.url) |
| 58 | + |
| 59 | + # Generate unique ID for this upload |
| 60 | + upload_id = str(uuid.uuid4()) |
| 61 | + temp_filename = f"{upload_id}.{file_ext}" |
| 62 | + filepath = os.path.join(UPLOAD_FOLDER, temp_filename) |
| 63 | + file.save(filepath) |
| 64 | + |
| 65 | + return redirect(url_for("import_log.preview", upload_id=upload_id)) |
| 66 | + |
| 67 | + return render_template("import_upload.html") |
| 68 | + |
| 69 | + |
| 70 | +@import_log_bp.route("/preview/<upload_id>", methods=["GET"]) |
| 71 | +def preview(upload_id): |
| 72 | + # Find file |
| 73 | + filepath = _get_filepath(upload_id) |
| 74 | + if not filepath: |
| 75 | + flash("File not found or expired", "error") |
| 76 | + return redirect(url_for("import_log.upload_file")) |
| 77 | + |
| 78 | + try: |
| 79 | + importer = ImporterFactory.get_importer(filepath) |
| 80 | + with open(filepath, "rb") as f: |
| 81 | + content = f.read() |
| 82 | + result = importer.parse(content) |
| 83 | + |
| 84 | + return render_template( |
| 85 | + "import_preview.html", result=result, upload_id=upload_id |
| 86 | + ) |
| 87 | + except Exception as e: |
| 88 | + flash(f"Error parsing file: {str(e)}", "error") |
| 89 | + return redirect(url_for("import_log.upload_file")) |
| 90 | + |
| 91 | + |
| 92 | +@import_log_bp.route("/confirm/<upload_id>", methods=["POST"]) |
| 93 | +def confirm(upload_id): |
| 94 | + filepath = _get_filepath(upload_id) |
| 95 | + if not filepath: |
| 96 | + flash("File not found or expired", "error") |
| 97 | + return redirect(url_for("import_log.upload_file")) |
| 98 | + |
| 99 | + try: |
| 100 | + importer = ImporterFactory.get_importer(filepath) |
| 101 | + with open(filepath, "rb") as f: |
| 102 | + content = f.read() |
| 103 | + result = importer.parse(content) |
| 104 | + |
| 105 | + # Import valid records |
| 106 | + count = 0 |
| 107 | + # Assume for now we are importing for Employee ID 1 or passed in form |
| 108 | + # Ideally user selects employee in Upload or Preview |
| 109 | + # For now, let's hardcode 1 or get from request if we added it |
| 110 | + employee_id = 1 |
| 111 | + |
| 112 | + for record in result.records: |
| 113 | + if not record.is_valid: |
| 114 | + continue |
| 115 | + |
| 116 | + # Check duplicate/overwrite? |
| 117 | + entry_date = datetime.strptime(record.date, "%Y-%m-%d").date() |
| 118 | + existing = ScheduleEntry.query.filter_by( |
| 119 | + employee_id=employee_id, date=entry_date |
| 120 | + ).first() |
| 121 | + |
| 122 | + entries_data = [] |
| 123 | + if record.entry_time and record.exit_time: |
| 124 | + entries_data.append( |
| 125 | + {"entry": record.entry_time, "exit": record.exit_time} |
| 126 | + ) |
| 127 | + |
| 128 | + if existing: |
| 129 | + existing.entries = entries_data |
| 130 | + existing.observation = record.observation |
| 131 | + # If valid entries exist, we assume normal work day, so unset absence? |
| 132 | + if entries_data: |
| 133 | + existing.absence_code = None |
| 134 | + else: |
| 135 | + new_entry = ScheduleEntry( |
| 136 | + employee_id=employee_id, |
| 137 | + date=entry_date, |
| 138 | + entries=entries_data, |
| 139 | + observation=record.observation, |
| 140 | + ) |
| 141 | + db.session.add(new_entry) |
| 142 | + count += 1 |
| 143 | + |
| 144 | + db.session.commit() |
| 145 | + |
| 146 | + # Cleanup |
| 147 | + os.remove(filepath) |
| 148 | + |
| 149 | + flash(f"Successfully imported {count} records", "success") |
| 150 | + return redirect(url_for("monthly_log.view_monthly_log")) |
| 151 | + |
| 152 | + except Exception as e: |
| 153 | + db.session.rollback() |
| 154 | + flash(f"Error importing data: {str(e)}", "error") |
| 155 | + return redirect(url_for("import_log.preview", upload_id=upload_id)) |
| 156 | + |
| 157 | + |
| 158 | +@import_log_bp.route("/cancel/<upload_id>", methods=["POST"]) |
| 159 | +def cancel(upload_id): |
| 160 | + filepath = _get_filepath(upload_id) |
| 161 | + if filepath: |
| 162 | + try: |
| 163 | + os.remove(filepath) |
| 164 | + except: |
| 165 | + pass |
| 166 | + return redirect(url_for("import_log.upload_file")) |
| 167 | + |
| 168 | + |
| 169 | +def _get_filepath(upload_id): |
| 170 | + # Search for file with upload_id prefix |
| 171 | + for f in os.listdir(UPLOAD_FOLDER): |
| 172 | + if f.startswith(upload_id): |
| 173 | + return os.path.join(UPLOAD_FOLDER, f) |
| 174 | + return None |
0 commit comments