from odoo import fields, models from odoo.exceptions import ValidationError class DanceBatch(models.Model): _inherit = "dance.batch" fee_structure_id = fields.Many2one( "dance.fee.structure", string="Fee Structure", ondelete="restrict", ) invoice_count = fields.Integer(compute="_compute_invoice_count") def _compute_invoice_count(self): grouped = self.env["account.move"].read_group( [ ("dance_batch_id", "in", self.ids), ("move_type", "=", "out_invoice"), ], ["dance_batch_id"], ["dance_batch_id"], ) count_map = { record["dance_batch_id"][0]: record["dance_batch_id_count"] for record in grouped } for batch in self: batch.invoice_count = count_map.get(batch.id, 0) def action_view_invoices(self): self.ensure_one() return { "name": "Invoices", "type": "ir.actions.act_window", "res_model": "account.move", "view_mode": "tree,form", "domain": [ ("dance_batch_id", "=", self.id), ("move_type", "=", "out_invoice"), ], "context": { "default_move_type": "out_invoice", "default_dance_batch_id": self.id, }, } def action_generate_batch_invoices(self): for batch in self: active_enrollments = batch.enrollment_ids.filtered(lambda rec: rec.status == "active") if not batch.fee_structure_id: raise ValidationError( "Set a fee structure on the batch before generating invoices." ) for enrollment in active_enrollments: enrollment.action_create_fee_invoice() return self.action_view_invoices()