<commit_before>##############################################################################
#
#    Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: <NAME> <<EMAIL>>
#
#    The licence is in the file __manifest__.py
#
##############################################################################
import logging
import math
from datetime import datetime

from babel.dates import format_date

from odoo import api, models, fields, _
from odoo.exceptions import Warning as odooWarning
from odoo.tools import mod10r

logger = logging.getLogger(__name__)

COMPASSION_BVR = "01-44443-7"


class ContractGroup(models.Model):
    _inherit = "recurring.contract.group"

    scan_line = fields.Char(compute="_compute_scan_line")
    format_ref = fields.Char(compute="_compute_format_ref")

    @api.multi
    def _compute_scan_line(self):
        """ Generate a scan line for contract group. """
        acc_number = self.get_company_bvr_account()
        for group in self.filtered("bvr_reference"):
            group.scan_line = self.get_scan_line(acc_number, group.bvr_reference)

    @api.multi
    def _compute_format_ref(self):
        slip_obj = self.env["l10n_ch.payment_slip"]
        for group in self:
            ref = group.bvr_reference or group.compute_partner_bvr_ref()
            group.format_ref = slip_obj._space(ref.lstrip("0"))

    @api.multi
    def get_months(self, months, sponsorships):
        """
        Given the list of months to print,
        returns the list of months grouped by the frequency payment
        of the contract group and only containing unpaid sponsorships.
        :param months: list of dates (date, datetime or string)
        :param sponsorships: recordset of included sponsorships
        :return: list of dates grouped in string format
        """
        self.ensure_one()
        freq = self.advance_billing_months
        payment_mode = self.with_context(lang="en_US").payment_mode_id
        # Take first open invoice or next_invoice_date
        open_invoice = min([i for i in sponsorships.mapped("first_open_invoice") if i])
        if open_invoice:
            first_invoice_date = open_invoice.replace(day=1)
        else:
            raise odooWarning(_("No open invoice found !"))

        for i, month in enumerate(months):
            if isinstance(month, str):
                months[i] = fields.Date.from_string(month)
            if isinstance(month, datetime):
                months[i] = month.date()

        # Only keep unpaid months
        valid_months = [
            fields.Date.to_string(month) for month in months
            if month >= first_invoice_date
        ]
        if "Permanent" in payment_mode.name:
            return valid_months[:1]
        if freq == 1:
            return valid_months
        else:
            # Group months
            result = list()
            count = 1
            month_start = ""
            for month in valid_months:
                if not month_start:
                    month_start = month
                if count < freq:
                    count += 1
                else:
                    result.append(fields.Date.to_string(month_start) + " - " +
                                  fields.Date.to_string(month))
                    month_start = ""
                    count = 1
            if not result:
                result.append(fields.Date.to_string(month_start) + " - " +
                              fields.Date.to_string(month))
            return result

    @api.multi
    def get_communication(self, start, stop, sponsorships):
        """
        Get the communication to print on the payment slip for sponsorship
        :param start: the month start for which we print the payment slip (string)
        :param stop: the month stop for which we print the payment slip (string)
        :param sponsorships: recordset of sponsorships for which to print the
                             payment slips
        :return: string of the communication
        """
        self.ensure_one()
        payment_mode = self.with_context(lang="en_US").payment_mode_id
        amount = sum(sponsorships.mapped("total_amount"))
        valid = sponsorships
        number_sponsorship = len(sponsorships)
        date_start = fields.Date.to_date(start)
        date_stop = fields.Date.to_date(stop)
        vals = {
            "amount": f"CHF {amount:.0f}",
            "subject": _("for") + " ",
            "date": "",
        }
        locale = self.partner_id.lang
        context = {"lang": locale}
        if start and stop:<commit_msg>CO-3332 fix datetime bug at bvr printing<commit_after>##############################################################################
#
#    Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: <NAME> <<EMAIL>>
#
#    The licence is in the file __manifest__.py
#
##############################################################################
import logging
import math
from datetime import datetime

from babel.dates import format_date

from odoo import api, models, fields, _
from odoo.exceptions import Warning as odooWarning
from odoo.tools import mod10r

logger = logging.getLogger(__name__)

COMPASSION_BVR = "01-44443-7"


class ContractGroup(models.Model):
    _inherit = "recurring.contract.group"

    scan_line = fields.Char(compute="_compute_scan_line")
    format_ref = fields.Char(compute="_compute_format_ref")

    @api.multi
    def _compute_scan_line(self):
        """ Generate a scan line for contract group. """
        acc_number = self.get_company_bvr_account()
        for group in self.filtered("bvr_reference"):
            group.scan_line = self.get_scan_line(acc_number, group.bvr_reference)

    @api.multi
    def _compute_format_ref(self):
        slip_obj = self.env["l10n_ch.payment_slip"]
        for group in self:
            ref = group.bvr_reference or group.compute_partner_bvr_ref()
            group.format_ref = slip_obj._space(ref.lstrip("0"))

    @api.multi
    def get_months(self, months, sponsorships):
        """
        Given the list of months to print,
        returns the list of months grouped by the frequency payment
        of the contract group and only containing unpaid sponsorships.
        :param months: list of dates (date, datetime or string)
        :param sponsorships: recordset of included sponsorships
        :return: list of dates grouped in string format
        """
        self.ensure_one()
        freq = self.advance_billing_months
        payment_mode = self.with_context(lang="en_US").payment_mode_id
        # Take first open invoice or next_invoice_date
        open_invoice = min([i for i in sponsorships.mapped("first_open_invoice") if i])
        if open_invoice:
            first_invoice_date = open_invoice.replace(day=1)
        else:
            raise odooWarning(_("No open invoice found !"))

        for i, month in enumerate(months):
            if isinstance(month, str):
                months[i] = fields.Date.from_string(month)
            if isinstance(month, datetime):
                months[i] = month.date()

        # check if first invoice is after last month
        if first_invoice_date > months[-1]:
            raise odooWarning(_(f"First invoice is after Date Stop"))

        # Only keep unpaid months
        valid_months = [
            fields.Date.to_string(month) for month in months
            if month >= first_invoice_date
        ]
        if "Permanent" in payment_mode.name:
            return valid_months[:1]
        if freq == 1:
            return valid_months
        else:
            # Group months
            result = list()
            count = 1
            month_start = ""
            for month in valid_months:
                if not month_start:
                    month_start = month
                if count < freq:
                    count += 1
                else:
                    result.append(month_start + " - " + month)
                    month_start = ""
                    count = 1
            if not result:
                result.append(month_start + " - " + month)
            return result

    @api.multi
    def get_communication(self, start, stop, sponsorships):
        """
        Get the communication to print on the payment slip for sponsorship
        :param start: the month start for which we print the payment slip (string)
        :param stop: the month stop for which we print the payment slip (string)
        :param sponsorships: recordset of sponsorships for which to print the
                             payment slips
        :return: string of the communication
        """
        self.ensure_one()
        payment_mode = self.with_context(lang="en_US").payment_mode_id
        amount = sum(sponsorships.mapped("total_amount"))
        valid = sponsorships
        number_sponsorship = len(sponsorships)
        date_start = fields.Date.to_date(start)
        date_stop = fields.Date.to_date(stop)
        vals = {
            "amount": f"CHF {amount:.0f}",
            "subject": _("for") + " ",
            "date": "",
        }
        locale = self.partner_id.lang
        context = {"lang": locale}
        if start and stop:
{'fraction_non_alphanumeric': 0.11544645728373888, 'fraction_numerical': 0.005681209132811662, 'mean_word_length': 2.1995884773662553, 'pattern_counts': {'":': 8, '<': 11, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5989835', 'n_tokens_mistral': 2624, 'n_tokens_neox': 2467, 'n_words': 711}