37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
import os
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.document import FilledDocument
|
|
from app.models.template import DocumentTemplate
|
|
from app.models.user import User
|
|
|
|
|
|
def cleanup_user_files(db: Session, user: User) -> None:
|
|
"""Remove uploaded template and rendered document files for a user."""
|
|
templates = (
|
|
db.query(DocumentTemplate).filter(DocumentTemplate.owner_id == user.id).all()
|
|
)
|
|
template_ids = [t.id for t in templates]
|
|
|
|
for template in templates:
|
|
if template.file_path and os.path.exists(template.file_path):
|
|
os.remove(template.file_path)
|
|
|
|
documents = db.query(FilledDocument).filter(
|
|
FilledDocument.owner_id == user.id
|
|
).all()
|
|
if template_ids:
|
|
documents += (
|
|
db.query(FilledDocument)
|
|
.filter(FilledDocument.template_id.in_(template_ids))
|
|
.all()
|
|
)
|
|
|
|
seen_paths: set[str] = set()
|
|
for doc in documents:
|
|
if doc.rendered_docx_path and doc.rendered_docx_path not in seen_paths:
|
|
seen_paths.add(doc.rendered_docx_path)
|
|
if os.path.exists(doc.rendered_docx_path):
|
|
os.remove(doc.rendered_docx_path)
|