<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 simplejson

from odoo.addons.child_compassion.models.compassion_hold import HoldType
from odoo.addons.queue_job.job import job, related_action

from odoo import api, models, fields

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

LANG_MAPPING = {
    'fr': 'fr_CH',
    'de': 'de_DE',
    'it': 'it_IT'
}


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

    ##########################################################################
    #                                 FIELDS                                 #
    ##########################################################################
    web_data = fields.Text(help='Form data filled from website')
    group_id = fields.Many2one(required=False)
    partner_id = fields.Many2one(required=False)
    mailing_campaign_id = fields.Many2one('mail.mass_mailing.campaign')

    ##########################################################################
    #                             PUBLIC METHODS                             #
    ##########################################################################
    @api.model
    def create_sponsorship(self, child_local_id, form_data, sponsor_lang,
                           mailing_slug):
        """
        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 mailing_slug: slug of the mailing campaign
        :return: True if process is good.
        """
        # Format birthday
        birthday = form_data.get('birthday', '')
        if ('/' in birthday) or (' ' in birthday) or ('.' in birthday) and \
                len(birthday) > 6:
            form_data['birthday'] = birthday[6:] + '-' + birthday[3:5] + \
                '-' + birthday[0:2]

        # Search for existing partner
        partner = self.env['res.partner'].search([
            ('lastname', 'like', form_data['last_name']),
            ('firstname', 'like', form_data['first_name']),
            ('zip', '=', form_data['zipcode'])
        ])
        if partner and len(partner) > 1:
            partner = partner.filtered('has_sponsorships')
        partner_ok = partner and len(partner) == 1

        # Check origin
        campaign_id = False
        if mailing_slug:
            campaign_id = self.env['mail.mass_mailing.campaign'].search([
                ('mailing_slug', '=', mailing_slug)
            ], limit=1).id
        # Create sponsorship
        child = self.env['compassion.child'].search([
            ('local_id', '=', child_local_id)])
        lines = self._get_sponsorship_standard_lines()
        if not form_data.get('patenschaftplus'):
            lines = lines[:-1]
        form_data['lang'] = LANG_MAPPING[sponsor_lang]
        sponsorship = self.create({
            'partner_id': partner_ok and partner.id,
            'correspondant_id': partner_ok and partner.id,
            'child_id': child.id,
            'web_data': simplejson.dumps(form_data),
            'type': 'S',
            'contract_line_ids': lines,
            'next_invoice_date': fields.Date.today(),
            'channel': 'internet',
            'mailing_campaign_id': campaign_id,
        })

        # Notify staff
        staff_param = 'sponsorship_' + sponsor_lang + '_id'
        staff = self.env['staff.notification.settings'].get_param(staff_param)
        notify_text = "A new sponsorship was made on the website. Please " \
                      "verify all information and validate the sponsorship " \
                      "on Odoo: <br/><br/><ul>"
        for field, value in form_data.iteritems():
            notify_text += "<li>" + field + ': ' + unicode(value) + '</li>'
        sponsorship.message_post(
            body=notify_text,
            subject="New sponsorship from the website",
            partner_ids=[staff],
            type='comment',
            subtype='mail.mt_comment',
            content_subtype='html'
        )

        if partner_ok:
            # Update sponsor info
            sponsorship.with_delay().update_partner_from_web_data()

        # Convert to No Money Hold
        sponsorship.with_delay().update_child_hold()

        return True

    ##########################################################################
    #                             VIEW CALLBACKS                             #
    ##########################################################################
    @api.multi
    def create_sponsor_from_web(self):
        """
        Use the form filled in website to create a new partner.
        :return: view of the partner<commit_msg>CO-1313 Mark child as sponsored when sponsor is not yet created from...<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 simplejson

from odoo.addons.child_compassion.models.compassion_hold import HoldType
from odoo.addons.queue_job.job import job, related_action

from odoo import api, models, fields

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

LANG_MAPPING = {
    'fr': 'fr_CH',
    'de': 'de_DE',
    'it': 'it_IT'
}


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

    ##########################################################################
    #                                 FIELDS                                 #
    ##########################################################################
    web_data = fields.Text(help='Form data filled from website')
    group_id = fields.Many2one(required=False)
    partner_id = fields.Many2one(required=False)
    mailing_campaign_id = fields.Many2one('mail.mass_mailing.campaign')

    ##########################################################################
    #                             PUBLIC METHODS                             #
    ##########################################################################
    @api.model
    def create_sponsorship(self, child_local_id, form_data, sponsor_lang,
                           mailing_slug):
        """
        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 mailing_slug: slug of the mailing campaign
        :return: True if process is good.
        """
        # Format birthday
        birthday = form_data.get('birthday', '')
        if ('/' in birthday) or (' ' in birthday) or ('.' in birthday) and \
                len(birthday) > 6:
            form_data['birthday'] = birthday[6:] + '-' + birthday[3:5] + \
                '-' + birthday[0:2]

        # Search for existing partner
        partner = self.env['res.partner'].search([
            ('lastname', 'like', form_data['last_name']),
            ('firstname', 'like', form_data['first_name']),
            ('zip', '=', form_data['zipcode'])
        ])
        if partner and len(partner) > 1:
            partner = partner.filtered('has_sponsorships')
        partner_ok = partner and len(partner) == 1

        # Check origin
        campaign_id = False
        if mailing_slug:
            campaign_id = self.env['mail.mass_mailing.campaign'].search([
                ('mailing_slug', '=', mailing_slug)
            ], limit=1).id
        # Create sponsorship
        child = self.env['compassion.child'].search([
            ('local_id', '=', child_local_id)])
        lines = self._get_sponsorship_standard_lines()
        if not form_data.get('patenschaftplus'):
            lines = lines[:-1]
        form_data['lang'] = LANG_MAPPING[sponsor_lang]
        sponsorship = self.create({
            'partner_id': partner_ok and partner.id,
            'correspondant_id': partner_ok and partner.id,
            'child_id': child.id,
            'web_data': simplejson.dumps(form_data),
            'type': 'S',
            'contract_line_ids': lines,
            'next_invoice_date': fields.Date.today(),
            'channel': 'internet',
            'mailing_campaign_id': campaign_id,
        })

        # Notify staff
        staff_param = 'sponsorship_' + sponsor_lang + '_id'
        staff = self.env['staff.notification.settings'].get_param(staff_param)
        notify_text = "A new sponsorship was made on the website. Please " \
                      "verify all information and validate the sponsorship " \
                      "on Odoo: <br/><br/><ul>"
        for field, value in form_data.iteritems():
            notify_text += "<li>" + field + ': ' + unicode(value) + '</li>'
        sponsorship.message_post(
            body=notify_text,
            subject="New sponsorship from the website",
            partner_ids=[staff],
            type='comment',
            subtype='mail.mt_comment',
            content_subtype='html'
        )

        if partner_ok:
            # Update sponsor info
            sponsorship.with_delay().update_partner_from_web_data()
        else:
            # Mark child as sponsored even if not yet linked to sponsor
            child.state = 'P'

        # Convert to No Money Hold
        sponsorship.with_delay().update_child_hold()

        return True

    ##########################################################################
    #                             VIEW CALLBACKS                             #
    ##########################################################################
    @api.multi
    def create_sponsor_from_web(self):
        """
        Use the form filled in website to create a new partner.
        :return: view of the partner
{'fraction_non_alphanumeric': 0.20517676767676768, 'fraction_numerical': 0.007575757575757576, 'mean_word_length': 2.143884892086331, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 25, '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': '3215863', 'n_tokens_mistral': 3593, 'n_tokens_neox': 3388, 'n_words': 786}