<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2016 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 re

from odoo.addons.queue_job.job import job, related_action

from odoo import api, models, fields, _
from odoo.tools import config
from werkzeug.utils import escape

_logger = logging.getLogger(__name__)

# Mapping from Website form fields to res.partner fields in Odoo
SPONSOR_MAPPING = {
    'city': 'city',
    'first_name': 'firstname',
    'last_name': 'lastname',
    'zipcode': 'zip',
    'Beruf': 'function',
    'phone': 'phone',
    'street': 'street',
    'email': 'email',
    'kirchgemeinde': 'church_name',
}

test_mode = config.get('test_enable')


class Contracts(models.Model):
    _inherit = 'recurring.contract'

    ##########################################################################
    #                                 FIELDS                                 #
    ##########################################################################
    group_id = fields.Many2one(required=False)
    partner_id = fields.Many2one(required=False)

    ##########################################################################
    #                             PUBLIC METHODS                             #
    ##########################################################################
    @api.model
    def create_sponsorship(self, child_local_id, form_data, sponsor_lang,
                           utm_source, utm_medium, utm_campaign):
        """
        Called by Wordpress to add a new sponsorship.
        :param form_data: all form values entered on the site
        {
            'city': 'Bienne',
            'first_name': 'Emanuel',
            'last_name': 'Cino',
            'language': [u'französich', 'englisch'],
            'zahlungsweise': 'dauerauftrag',
            'consumer_source_text': 'Times Magazine',
            'zipcode': '2503',
            'birthday': '10/04/1989',
            'Beruf': 'Agriculteur paysan',
            'phone': '078 936 45 95',
            'consumer_source': 'Anzeige in Zeitschrift',
            'street': 'Rue test 1',
            'kirchgemeinde': u'Mon église',
            'mithelfen': {
                'checkbox': 'on'
            },
            'salutation': 'Herr',
            'patenschaftplus': {
                'checkbox': 'on'
            },
            'email': '<EMAIL>',
            'childID': '15783',
            'land': 'Suisse'
        }
        :param child_local_id: local id of child
        :param sponsor_lang: language used in the website
        :param utm_source: identifier from the url tracking
        :param utm_medium: identifier from the url tracking
        :param utm_campaign: identifier from the url tracking
        :return: True if process is good.
        """
        _logger.info("New sponsorship for child %s from Wordpress: %s",
                     child_local_id, str(form_data))
        try:
            form_data['Child reference'] = child_local_id

            for field in ['city', 'first_name', 'last_name',
                          'consumer_source_text', 'zipcode', 'Beruf', 'phone',
                          'street', 'kirchgemeinde', 'email', 'land']:
                form_data[field] = escape(form_data.get(field))

            match_obj = self.env['res.partner.match.wp']

            partner_infos = {
                'company_id': self.env.user.company_id.id
            }
            for wp_field, odoo_field in SPONSOR_MAPPING.iteritems():
                partner_infos[odoo_field] = form_data.get(wp_field)

            # Match lang + title + spoken langs + country
            partner_infos['lang'] = match_obj.match_lang(sponsor_lang)
            form_data['lang'] = partner_infos['lang']
            partner_infos['title'] = match_obj.match_title(
                form_data['salutation']
            )
            if form_data.get('language'):
                partner_infos['spoken_lang_ids'] = match_obj.\
                    match_spoken_langs(
                        form_data['language']
                )
            partner_infos['country_id'] = match_obj.match_country(
                form_data['land'], partner_infos['lang']).id

            # Format birthday
            birthday = form_data.get('birthday', '')
            if birthday:
                d = birthday.split('/')  # 'dd/mm/YYYY' => ['dd', 'mm', 'YYYY']
                partner_infos['birthdate'] = '%s-%s-%s' % (d[2], d[1], d[0])

            # Search for existing partner
            partner = match_obj.match_partner_to_infos(partner_infos)

            # Check origin
            internet_id = self.env.ref('utm.utm_medium_website').id
            utms = self.env['utm.mixin'].get_utms(
                utm_source, utm_medium, utm_campaign)

            # Create sponsorship
            child = self.env['compassion.child'].search([
                ('local_id', '=', child_local_id)], limit=1)
            lines = self._get_sponsorship_standard_lines(utm_source == 'wrpr')
            if not form_data.get('patenschaftplus'):
                lines = lines[:-1]
            sponsorship_type = 'S'
            partner_id = partner.id
            if utm_source == 'wrpr':
                # Special case Write&Pray sponsorship
                sponsorship_type = 'SC'
                partner_id = partner.search([
                    ('name', '=', '<NAME>')
                ], limit=1).id or partner.id
            sponsorship_vals = {
                'partner_id': partner_id,
                'correspondent_id': partner.id,
                'child_id': child.id,
                'type': sponsorship_type,
                'contract_line_ids': lines,
                'next_invoice_date': fields.Date.today(),
                'source_id': utms['source'],
                'medium_id': utms.get('medium', internet_id),
                'campaign_id': utms['campaign'],
            }
        except:
            # We catch any exception to make sure we don't lose any
            # sponsorship made from the website
            _logger.error("Error during wordpress sponsorship import",<commit_msg>WP-46 write & pray sponsor can contribute<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2016 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 re

from odoo.addons.queue_job.job import job, related_action

from odoo import api, models, fields, _
from odoo.tools import config
from werkzeug.utils import escape

_logger = logging.getLogger(__name__)

# Mapping from Website form fields to res.partner fields in Odoo
SPONSOR_MAPPING = {
    'city': 'city',
    'first_name': 'firstname',
    'last_name': 'lastname',
    'zipcode': 'zip',
    'Beruf': 'function',
    'phone': 'phone',
    'street': 'street',
    'email': 'email',
    'kirchgemeinde': 'church_name',
}

test_mode = config.get('test_enable')


class Contracts(models.Model):
    _inherit = 'recurring.contract'

    ##########################################################################
    #                                 FIELDS                                 #
    ##########################################################################
    group_id = fields.Many2one(required=False)
    partner_id = fields.Many2one(required=False)

    ##########################################################################
    #                             PUBLIC METHODS                             #
    ##########################################################################
    @api.model
    def create_sponsorship(self, child_local_id, form_data, sponsor_lang,
                           utm_source, utm_medium, utm_campaign):
        """
        Called by Wordpress to add a new sponsorship.
        :param form_data: all form values entered on the site
        {
            'city': 'Bienne',
            'first_name': 'Emanuel',
            'last_name': 'Cino',
            'language': [u'französich', 'englisch'],
            'zahlungsweise': 'dauerauftrag',
            'consumer_source_text': 'Times Magazine',
            'zipcode': '2503',
            'birthday': '10/04/1989',
            'Beruf': 'Agriculteur paysan',
            'phone': '078 936 45 95',
            'consumer_source': 'Anzeige in Zeitschrift',
            'street': 'Rue test 1',
            'kirchgemeinde': u'Mon église',
            'mithelfen': {
                'checkbox': 'on'
            },
            'salutation': 'Herr',
            'patenschaftplus': {
                'checkbox': 'on'
            },
            'email': '<EMAIL>',
            'childID': '15783',
            'land': 'Suisse'
        }
        :param child_local_id: local id of child
        :param sponsor_lang: language used in the website
        :param utm_source: identifier from the url tracking
        :param utm_medium: identifier from the url tracking
        :param utm_campaign: identifier from the url tracking
        :return: True if process is good.
        """
        _logger.info("New sponsorship for child %s from Wordpress: %s",
                     child_local_id, str(form_data))
        try:
            form_data['Child reference'] = child_local_id

            for field in ['city', 'first_name', 'last_name',
                          'consumer_source_text', 'zipcode', 'Beruf', 'phone',
                          'street', 'kirchgemeinde', 'email', 'land']:
                form_data[field] = escape(form_data.get(field))

            match_obj = self.env['res.partner.match.wp']

            partner_infos = {
                'company_id': self.env.user.company_id.id
            }
            for wp_field, odoo_field in SPONSOR_MAPPING.iteritems():
                partner_infos[odoo_field] = form_data.get(wp_field)

            # Match lang + title + spoken langs + country
            partner_infos['lang'] = match_obj.match_lang(sponsor_lang)
            form_data['lang'] = partner_infos['lang']
            partner_infos['title'] = match_obj.match_title(
                form_data['salutation']
            )
            if form_data.get('language'):
                partner_infos['spoken_lang_ids'] = match_obj.\
                    match_spoken_langs(
                        form_data['language']
                )
            partner_infos['country_id'] = match_obj.match_country(
                form_data['land'], partner_infos['lang']).id

            # Format birthday
            birthday = form_data.get('birthday', '')
            if birthday:
                d = birthday.split('/')  # 'dd/mm/YYYY' => ['dd', 'mm', 'YYYY']
                partner_infos['birthdate'] = '%s-%s-%s' % (d[2], d[1], d[0])

            # Search for existing partner
            partner = match_obj.match_partner_to_infos(partner_infos)

            # Check origin
            internet_id = self.env.ref('utm.utm_medium_website').id
            utms = self.env['utm.mixin'].get_utms(
                utm_source, utm_medium, utm_campaign)

            # Create sponsorship
            child = self.env['compassion.child'].search([
                ('local_id', '=', child_local_id)], limit=1)
            lines = self._get_sponsorship_standard_lines(utm_source == 'wrpr')
            if not form_data.get('patenschaftplus'):
                lines = lines[:-1]
            sponsorship_type = 'S'
            partner_id = partner.id
            if utm_source == 'wrpr':
                # Special case Write&Pray sponsorship
                sponsorship_type = 'SC'
                if form_data.get('writepray') == 'WRPR+DON':
                    contribution = float(form_data.get('writepray-contribution'))
                    for line in lines:
                        if line[2]['product_id'] == 2:
                            line[2].update({'amount': contribution,
                                            'subtotal': contribution,
                                            'quantity': 1})
                else:
                    partner_id = partner.search([
                        ('name', '=', '<NAME>')
                    ], limit=1).id or partner.id
            sponsorship_vals = {
                'partner_id': partner_id,
                'correspondent_id': partner.id,
                'child_id': child.id,
                'type': sponsorship_type,
                'contract_line_ids': lines,
                'next_invoice_date': fields.Date.today(),
                'source_id': utms['source'],
                'medium_id': utms.get('medium', internet_id),
                'campaign_id': utms['campaign'],
            }
        except:
            # We catch any exception to make sure we don't lose any
            # sponsorship made from the website
            _logger.error("Error during wordpress sponsorship import",
{'fraction_non_alphanumeric': 0.1764441447516296, 'fraction_numerical': 0.0065932419270247995, 'mean_word_length': 1.9400881057268722, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3616815', 'n_tokens_mistral': 3800, 'n_tokens_neox': 3592, 'n_words': 791}