<commit_before># -*- encoding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: <NAME> <<EMAIL>>
#
#    The licence is in the file __openerp__.py
#
##############################################################################

from odoo import models, fields
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DF
from odoo.addons.sponsorship_compassion.models.product import \
    GIFT_CATEGORY, GIFT_NAMES

from datetime import datetime
import logging

logger = logging.getLogger(__name__)


class StatementCompletionRule(models.Model):
    """ Rules to complete account bank statements."""
    _inherit = "account.statement.completion.rule"

    ##########################################################################
    #                                 FIELDS                                 #
    ##########################################################################

    sequence = fields.Integer('Sequence',
                              help="Lower means parsed first.")
    name = fields.Char('Name', size=128)
    journal_ids = fields.Many2many(
        'account.journal',
        string='Related statement journal')
    function_to_call = fields.Selection('_get_functions', 'Method')

    ##########################################################################
    #                             FIELDS METHODS                             #
    ##########################################################################

    def _get_functions(self):
        res = super(StatementCompletionRule, self)._get_functions()
        res.extend([
            ('get_from_partner_ref',
             'Compassion: From line reference '
             '(based on the partner reference)'),
            ('get_from_bvr_ref',
             'Compassion: From line reference '
             '(based on the BVR reference of the sponsor)'),
            ('lsv_dd_get_from_bvr_ref',
             'Compassion [LSV/DD]: From line reference '
             '(based on the BVR reference of the sponsor)'),
            ('get_from_lsv_dd', 'Compassion: Put LSV DD Credits in 1098'),
            ('get_sponsor_name',
             'Compassion[POST]: From sponsor reference '
             '(based the sponsor name in the description)'),
        ])
        return res

    ##########################################################################
    #                             PUBLIC METHODS                             #
    ##########################################################################

    def get_from_partner_ref(self, stmts_vals, st_line):
        """
        If line ref match a partner reference, update partner and account
        Then, call the generic st_line method to complete other values.
        :param dict st_line: read of the concerned account.bank.statement.line
        :return:
            A dict of value that can be passed directly to the write method of
            the statement line or {}
           {'partner_id': value,
            'account_id' : value,
            ...}
        """
        ref = st_line['ref']
        res = {}
        partner_obj = self.env['res.partner']
        partner = partner_obj.search(
            [('ref', '=', str(int(ref[9:16]))),
             ('is_company', '=', False)])
        # Test that only one partner matches.
        if partner:
            if len(partner) == 1:
                # If we fall under this rule of completion, it means there is
                # no open invoice corresponding to the payment. We may need to
                # generate one depending on the payment type.
                res.update(
                    self._generate_invoice(stmts_vals, st_line, partner))
                # Get the accounting partner (company)
                partner = partner_obj._find_accounting_partner(partner)
                res['partner_id'] = partner.id
            else:
                logger.warning(
                    'Line named "%s" (Ref:%s) was matched by more '
                    'than one partner while looking on partners' %
                    (st_line['name'], st_line['ref']))
        return res

    def get_from_bvr_ref(self, stmts_vals, st_line):
        """
        If line ref match an invoice BVR Reference, update partner and account
        Then, call the generic st_line method to complete other values.
        """
        ref = st_line['ref']
        res = dict()
        partner = self._search_partner_by_bvr_ref(ref)

        if partner:
            partner_obj = self.env['res.partner']
            partner = partner_obj._find_accounting_partner(partner)
            res['partner_id'] = partner.id

        return res

    def lsv_dd_get_from_bvr_ref(self, stmts_vals, st_line):
        """
        If line ref match an invoice BVR Reference, update partner and account
        Then, call the generic st_line method to complete other values.
        For LSV/DD statements, search in all invoices.
        """
        ref = st_line['ref']
        res = dict()
        partner = self._search_partner_by_bvr_ref(ref, True)

        if partner:
            partner_obj = self.env['res.partner']
            partner = partner_obj._find_accounting_partner(partner)
            res['partner_id'] = partner.id

        return res

    def get_from_lsv_dd(self, stmts_vals, st_line):
        """ If line is a LSV or DD credit, change the account to 1098. """
        label = st_line['name'].replace('\n', ' ') if st_line[
            'name'] != '/' else st_line['ref'].replace('\n', ' ')
        lsv_dd_strings = [u'BULLETIN DE VERSEMENT ORANGE',
                          u'ORDRE DEBIT DIRECT',
                          u'Crèdit LSV']
        is_lsv_dd = False
        res = {}
        account_id = False
        if u'KREDITKARTEN' in label:
            account_id = self.env['account.account'].search(
                [('code', '=', '2000')], limit=1).id
            res['partner_id'] = self.env['res.partner'].search([
                ('name', '=', 'Postfinance SA')], limit=1).id
        elif u'CRÉDIT TRANSACTIONS E-PAYMENT POSTFINANCE CARD' in label:
            account_id = self.env['account.account'].search(
                [('code', '=', '1015')], limit=1).id
            res['partner_id'] = self.env['res.partner'].search([
                ('name', '=', 'Postfinance SA')], limit=1).id
        else:
            for credit_string in lsv_dd_strings:
                is_lsv_dd = is_lsv_dd or credit_string in label
        if is_lsv_dd:
            account_id = self.env['account.account'].search(<commit_msg>CO-852 - Direct Debit not in 1098<commit_after># -*- encoding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: <NAME> <<EMAIL>>
#
#    The licence is in the file __openerp__.py
#
##############################################################################

from odoo import models, fields
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DF
from odoo.addons.sponsorship_compassion.models.product import \
    GIFT_CATEGORY, GIFT_NAMES

from datetime import datetime
import logging

logger = logging.getLogger(__name__)


class StatementCompletionRule(models.Model):
    """ Rules to complete account bank statements."""
    _inherit = "account.statement.completion.rule"

    ##########################################################################
    #                                 FIELDS                                 #
    ##########################################################################

    sequence = fields.Integer('Sequence',
                              help="Lower means parsed first.")
    name = fields.Char('Name', size=128)
    journal_ids = fields.Many2many(
        'account.journal',
        string='Related statement journal')
    function_to_call = fields.Selection('_get_functions', 'Method')

    ##########################################################################
    #                             FIELDS METHODS                             #
    ##########################################################################

    def _get_functions(self):
        res = super(StatementCompletionRule, self)._get_functions()
        res.extend([
            ('get_from_partner_ref',
             'Compassion: From line reference '
             '(based on the partner reference)'),
            ('get_from_bvr_ref',
             'Compassion: From line reference '
             '(based on the BVR reference of the sponsor)'),
            ('lsv_dd_get_from_bvr_ref',
             'Compassion [LSV/DD]: From line reference '
             '(based on the BVR reference of the sponsor)'),
            ('get_from_lsv_dd', 'Compassion: Put LSV DD Credits in 1098'),
            ('get_sponsor_name',
             'Compassion[POST]: From sponsor reference '
             '(based the sponsor name in the description)'),
        ])
        return res

    ##########################################################################
    #                             PUBLIC METHODS                             #
    ##########################################################################

    def get_from_partner_ref(self, stmts_vals, st_line):
        """
        If line ref match a partner reference, update partner and account
        Then, call the generic st_line method to complete other values.
        :param dict st_line: read of the concerned account.bank.statement.line
        :return:
            A dict of value that can be passed directly to the write method of
            the statement line or {}
           {'partner_id': value,
            'account_id' : value,
            ...}
        """
        ref = st_line['ref']
        res = {}
        partner_obj = self.env['res.partner']
        partner = partner_obj.search(
            [('ref', '=', str(int(ref[9:16]))),
             ('is_company', '=', False)])
        # Test that only one partner matches.
        if partner:
            if len(partner) == 1:
                # If we fall under this rule of completion, it means there is
                # no open invoice corresponding to the payment. We may need to
                # generate one depending on the payment type.
                res.update(
                    self._generate_invoice(stmts_vals, st_line, partner))
                # Get the accounting partner (company)
                partner = partner_obj._find_accounting_partner(partner)
                res['partner_id'] = partner.id
            else:
                logger.warning(
                    'Line named "%s" (Ref:%s) was matched by more '
                    'than one partner while looking on partners' %
                    (st_line['name'], st_line['ref']))
        return res

    def get_from_bvr_ref(self, stmts_vals, st_line):
        """
        If line ref match an invoice BVR Reference, update partner and account
        Then, call the generic st_line method to complete other values.
        """
        ref = st_line['ref']
        res = dict()
        partner = self._search_partner_by_bvr_ref(ref)

        if partner:
            partner_obj = self.env['res.partner']
            partner = partner_obj._find_accounting_partner(partner)
            res['partner_id'] = partner.id

        return res

    def lsv_dd_get_from_bvr_ref(self, stmts_vals, st_line):
        """
        If line ref match an invoice BVR Reference, update partner and account
        Then, call the generic st_line method to complete other values.
        For LSV/DD statements, search in all invoices.
        """
        ref = st_line['ref']
        res = dict()
        partner = self._search_partner_by_bvr_ref(ref, True)

        if partner:
            partner_obj = self.env['res.partner']
            partner = partner_obj._find_accounting_partner(partner)
            res['partner_id'] = partner.id

        return res

    def get_from_lsv_dd(self, stmts_vals, st_line):
        """ If line is a LSV or DD credit, change the account to 1098. """
        label = st_line['name'].replace('\n', ' ') if st_line[
            'name'] != '/' else st_line['ref'].replace('\n', ' ')
        lsv_dd_strings = [u'BULLETIN DE VERSEMENT ORANGE',
                          u'ORDRE DEBIT DIRECT',
                          u'CRÉDIT GROUPÉ BVR',
                          u'Crèdit LSV']
        is_lsv_dd = False
        res = {}
        account_id = False
        if u'KREDITKARTEN' in label:
            account_id = self.env['account.account'].search(
                [('code', '=', '2000')], limit=1).id
            res['partner_id'] = self.env['res.partner'].search([
                ('name', '=', 'Postfinance SA')], limit=1).id
        elif u'CRÉDIT TRANSACTIONS E-PAYMENT POSTFINANCE CARD' in label:
            account_id = self.env['account.account'].search(
                [('code', '=', '1015')], limit=1).id
            res['partner_id'] = self.env['res.partner'].search([
                ('name', '=', 'Postfinance SA')], limit=1).id
        else:
            for credit_string in lsv_dd_strings:
                is_lsv_dd = is_lsv_dd or credit_string in label
        if is_lsv_dd:
            account_id = self.env['account.account'].search(
{'fraction_non_alphanumeric': 0.18274375743162902, 'fraction_numerical': 0.005425089179548157, 'mean_word_length': 2.132448789571695, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6981057', 'n_tokens_mistral': 3694, 'n_tokens_neox': 3489, 'n_words': 947}