# All local filesystem data access: saving an upload, removing it after # processing, writing an Excel workbook, resolving an output file's path. # No business logic - callers decide what to save and when; this just # does the I/O. import os import uuid from werkzeug.utils import secure_filename def save_upload(file_storage, upload_folder): """ Saves an uploaded Werkzeug FileStorage to disk under a UUID-prefixed, sanitized filename (avoids both path traversal and same-name collisions between concurrent uploads). Data flow: file_storage (FileStorage) - the uploaded file from a Flask request upload_folder (str) - directory to save into returns (str) - the full saved path """ path = os.path.join(upload_folder, f"{uuid.uuid4()}_{secure_filename(file_storage.filename)}") file_storage.save(path) return path def remove_upload(path): """Deletes a previously-saved upload - called once processing (success or failure) is done with it, so uploads/ doesn't accumulate.""" os.remove(path) def new_output_filename(): """A fresh, collision-safe filename for a generated Excel export.""" return f"Statement_Extraction_{uuid.uuid4().hex[:8]}.xlsx" def save_workbook(workbook, output_folder, filename): """ Writes an openpyxl Workbook to disk. Data flow: workbook (openpyxl.Workbook) - the built workbook (see excel_service.build_workbook) output_folder (str) filename (str) returns (str) - the full saved path """ path = os.path.join(output_folder, filename) workbook.save(path) return path def resolve_output_path(output_folder, filename): """Full path for a previously-saved output file, sanitized against path traversal - or None if it doesn't exist.""" safe = secure_filename(filename) path = os.path.join(output_folder, safe) return path if os.path.exists(path) else None