import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) SUCCESS_RETENTION_DAYS = 30 ERROR_RETENTION_DAYS = 90 class WooSyncLog(models.Model): _name = 'woo.sync.log' _description = 'WooCommerce Sync Log' _order = 'create_date desc' _rec_name = 'record_ref' instance_id = fields.Many2one('woo.instance', ondelete='cascade') sync_type = fields.Selection([ ('product', 'Product'), ('order', 'Order'), ('invoice', 'Invoice'), ('inventory', 'Inventory'), ('customer', 'Customer'), ]) direction = fields.Selection([ ('odoo_to_woo', 'Odoo \u2192 WooCommerce'), ('woo_to_odoo', 'WooCommerce \u2192 Odoo'), ]) record_ref = fields.Char() state = fields.Selection([ ('success', 'Success'), ('failed', 'Failed'), ('conflict', 'Conflict'), ]) message = fields.Text() company_id = fields.Many2one( 'res.company', default=lambda self: self.env.company, ) @api.model def _cron_cleanup_logs(self): """Purge success/conflict logs older than 30 days, errors older than 90.""" now = fields.Datetime.now() cutoff_success = fields.Datetime.subtract(now, days=SUCCESS_RETENTION_DAYS) cutoff_error = fields.Datetime.subtract(now, days=ERROR_RETENTION_DAYS) logs = self.search([ '|', '&', ('state', '!=', 'failed'), ('create_date', '<', cutoff_success), '&', ('state', '=', 'failed'), ('create_date', '<', cutoff_error), ]) count = len(logs) if count: logs.unlink() _logger.info("WooCommerce: purged %d old sync log entries", count) def action_purge_old_logs(self): """Manual purge: delete success logs > 7 days, error logs > 30 days.""" self.env['woo.sync.log'].check_access_rights('unlink') now = fields.Datetime.now() cutoff_success = fields.Datetime.subtract(now, days=7) cutoff_error = fields.Datetime.subtract(now, days=30) logs = self.env['woo.sync.log'].search([ '|', '&', ('state', '!=', 'failed'), ('create_date', '<', cutoff_success), '&', ('state', '=', 'failed'), ('create_date', '<', cutoff_error), ]) count = len(logs) logs.unlink() return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'title': 'Sync Logs Purged', 'message': f'{count} old log entries deleted.', 'type': 'success', 'next': {'type': 'ir.actions.act_window_close'}, }, } @api.model def action_clear_errors(self): """Clear all failed sync log entries. Called from dashboard.""" self.check_access_rights('unlink') logs = self.search([('state', '=', 'failed')]) count = len(logs) logs.unlink() _logger.info("WooCommerce: manually cleared %d error log entries", count) return count