import csv import io from datetime import date, datetime from odoo import api, models, fields, _ from odoo.exceptions import ValidationError, UserError class AccountBatchPayment(models.Model): _inherit = 'account.batch.payment' country_code = fields.Char( string="Country Code", related='journal_id.country_code', ) l10n_in_enet_vendor_batch_payment_feature_enabled = fields.Boolean(related='company_id.l10n_in_enet_vendor_batch_payment_feature') l10n_in_pay_order_attachment_ids = fields.Many2many('ir.attachment', string='Pay Order Attachments', bypass_search_access=True) def generate_pay_order(self): journal = self.journal_id if not journal.bank_template_id: raise UserError(_("Please configure the bank template in the %s Journal to generate the csv file.", journal.name)) attachment = self.env['ir.attachment'].create({ 'name': f"{self.name}_payorder.csv", 'raw': self.get_csv_data(), 'res_model': 'account.batch.payment', 'res_id': self.id, }) self.l10n_in_pay_order_attachment_ids += attachment self.message_post( subject=_("Payorder CSV file"), body=_("Payorder has been generated by %s", self.env.user.name), attachment_ids=[attachment.id]) return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'type': 'success', 'sticky': False, 'message': _('Payorder has been generated successfully!.'), 'next': {'type': 'ir.actions.act_window_close'}, }, } def get_csv_data(self): header = [config.get('label', '') for config in self.journal_id.bank_template_id.bank_configuration] rows = [ self._get_value_from_field_path(payment_record) for payment_record in self.payment_ids ] with io.StringIO() as csv_output: csv_writer = csv.writer(csv_output) if self.journal_id.bank_template_id.include_header: csv_writer.writerow(header) csv_writer.writerows(rows) return csv_output.getvalue() def _get_value_from_field_path(self, payment): values = [] bank_configuration = self.journal_id.bank_template_id.bank_configuration for config in bank_configuration: value = '' field_path = config.get('field_name') if field_path: field_value = payment for part in field_path.split('.'): if isinstance(field_value, models.Model): field_value = field_value[part] if part in field_value._fields else '' else: field_value = '' break value = field_value or '' # Map the values according to the bank configuration mapping = config.get('mapping') if mapping and value: value = mapping.get(str(value), value) # Format the date according to the format in the bank configuration date_format = config.get('date_format') if date_format and isinstance(value, (date, datetime)): value = value.strftime(date_format) values.append(value) return values @api.ondelete(at_uninstall=False) def _check_payorder_deletion(self): for record in self: if record.l10n_in_pay_order_attachment_ids: raise ValidationError(_("You cannot delete the record because one or more Pay Orders have been generated."))