survey_attachment_cleanup/wizard/sh_survey_attachment_cleanup_wizard.py
2025-12-29 13:49:37 +07:00

69 lines
2.7 KiB
Python

# -*- coding: utf-8 -*-
from odoo import api, fields, models
class SurveyAttachmentCleanupWizard(models.TransientModel):
_name = 'sh.survey.attachment.cleanup.wizard'
_description = 'Survey Attachment Cleanup Wizard'
website_id = fields.Many2one('website', string="Website")
limit = fields.Integer(string="Batch Limit", default=0, help="Limit number of deletions per batch (0 for no limit)")
attachment_count = fields.Integer(string="Attachments Found", compute='_compute_attachment_count')
@api.depends('website_id')
def _compute_attachment_count(self):
for record in self:
domain = [
('answer_type', '=', 'upload_file'),
]
# Find all relevant lines first
lines = self.env['survey.user_input.line'].search(domain)
total_count = 0
# Iterate to count attachments
# NOTE: this might be slow for huge datasets, but accurate given the m2m structure
# To optimize, we could do SQL, but ORM is safer for now given < 15k records
# We can't easily search ir.attachment directly because the relationship is via m2m table
# `survey_user_input_line_rel` (or similar, depending on define).
# Actually, `value_file_data_ids` is Many2many('ir.attachment')
# Let's collect IDs first (limit to reasonable number if performance issue?)
# But count needs to be accurate-ish.
# Filter attachments
# We search ir.attachment directly to find ALL matching files, including orphans.
# Criteria: Mimetype JPEG, Website Matches, No Res Model (typical for M2M/Orphans)
domain = [
('mimetype', '=', 'image/jpeg'),
('res_model', '=', False),
('res_field', '=', False),
]
if record.website_id:
domain.append(('website_id', '=', record.website_id.id))
# Count directly
count = self.env['ir.attachment'].search_count(domain)
record.attachment_count = count
def action_delete_attachments(self):
self.ensure_one()
domain = [
('mimetype', '=', 'image/jpeg'),
('res_model', '=', False),
('res_field', '=', False),
]
if self.website_id:
domain.append(('website_id', '=', self.website_id.id))
# Search with limit if needed
limit = self.limit if self.limit > 0 else None
attachments_to_delete = self.env['ir.attachment'].search(domain, limit=limit)
return attachments_to_delete.unlink()