approval_cleaner/models/approval_cleaner_wizard.py
2026-01-27 11:39:27 +07:00

49 lines
2.0 KiB
Python

from odoo import models, fields, _
from odoo.exceptions import UserError
class ApprovalCleanerWizard(models.TransientModel):
_name = 'approval.cleaner.wizard'
_description = 'Approval Cleaner Wizard'
date_end = fields.Date(string="End Date", required=True, help="Delete all approvals created before this date")
def action_clean_approvals(self):
self.ensure_one()
# Search for approvals created before the specified date
# using 'create_date' as it is the standard Odoo field for creation time.
# However, the user request mentioned "Date below specified date i provide".
# 'approval.request' has a 'date' field (which seems to be a datetime) and 'create_date'.
# I will use 'date' field as per the user's initial description if implicit, but looking at approval_request.py
# date = fields.Datetime(string="Date")
# So I will use that.
domain = [('date', '<', self.date_end)]
approvals_to_delete = self.env['approval.request'].sudo().search(domain)
count = len(approvals_to_delete)
# Detach attachments to bypass ir.attachment unlink restriction
attachments = self.env['ir.attachment'].sudo().search([
('res_model', '=', 'approval.request'),
('res_id', 'in', approvals_to_delete.ids),
])
if attachments:
attachments.write({'res_model': 'approval.cleaner.temp', 'res_id': 0})
approvals_to_delete.unlink()
# Now delete the attachments safely
if attachments:
attachments.unlink()
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': _('Success'),
'message': _('%s approvals have been deleted.', count),
'type': 'success',
'sticky': False,
'next': {'type': 'ir.actions.act_window_close'},
}
}