llm_ticket3/utils/attachment_manager.py
2025-04-03 14:59:35 +02:00

51 lines
2.2 KiB
Python

import os
import base64
import json
from typing import List, Dict, Any
from datetime import datetime
class AttachmentManager:
def __init__(self, odoo_instance, model_name: str = "project.task"):
self.odoo = odoo_instance
self.model_name = model_name
def fetch_attachments(self, ticket_id: int) -> List[Dict[str, Any]]:
attachments = self.odoo.execute('ir.attachment', 'search_read', [
[('res_model', '=', self.model_name), ('res_id', '=', ticket_id)]
], ['id', 'name', 'datas', 'mimetype', 'create_date', 'description'])
return attachments if isinstance(attachments, list) else []
def save_attachments(self, ticket_id: int, ticket_dir: str, attachments: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
attachment_dir = os.path.join(ticket_dir, "attachments")
os.makedirs(attachment_dir, exist_ok=True)
attachment_info_list = []
for attachment in attachments:
if attachment.get("datas"):
attachment_name = f"{attachment['id']}_{attachment['name'].replace('/', '_')}"
file_path = os.path.join(attachment_dir, attachment_name)
try:
with open(file_path, "wb") as f:
f.write(base64.b64decode(attachment["datas"]))
attachment_info_list.append({
"id": attachment["id"],
"name": attachment["name"],
"file_path": file_path,
"mimetype": attachment.get("mimetype"),
"create_date": attachment.get("create_date"),
"description": attachment.get("description"),
})
except Exception as e:
print(f"Erreur lors de l'enregistrement de l'attachement {attachment['name']}: {e}")
# Sauvegarde des métadonnées dans un fichier JSON
attachments_info_path = os.path.join(ticket_dir, "attachments_info.json")
with open(attachments_info_path, "w", encoding="utf-8") as f:
json.dump(attachment_info_list, f, indent=4, ensure_ascii=False)
return attachment_info_list