<commit_before># -*- coding: utf-8 -*-

from osv import osv, fields
from .erpwrapper import ErpWrapper
import datetime
from yamlns import namespace as ns
from generationkwh.isodates import isodate
from tools.translate import _

# TODO: sort rights sources if many members assigned the same contract
# TODO: Filter out inactive contracts

FF_CONTRACT_FIELDS = [
    ('contract_state', 'state'),
    ('contract_last_invoiced', 'data_ultima_lectura'),
    ('cups_direction', 'cups_direccio'),
]


# TODO: This function is duplicated in other sources
def _sqlfromfile(sqlname):
    from tools import config
    import os
    sqlfile = os.path.join(
        config['addons_path'], 'som_generationkwh',
            'sql', sqlname+'.sql')
    with open(sqlfile) as f:
        return f.read()


class GenerationkWhAssignment(osv.osv):

    _name = 'generationkwh.assignment'
    _order = 'member_id, priority, contract_id'

    def _ff_contract(self, cursor, uid, ids, field_names, args, context=None):
        """  Function to read contract values from function fields"""
        contract_obj = self.pool.get('giscedata.polissa')
        cups_obj = self.pool.get('giscedata.cups.ps')

        if not isinstance(ids, (tuple, list)):
            ids = [ids]

        init_dict = dict([(f, False) for f in field_names])
        res = {}.fromkeys(ids, {})
        for k in res.keys():
            res[k] = init_dict.copy()

        for assigment_vals in self.read(cursor, uid, ids, ['contract_id']):
            assignment_id = assigment_vals['id']
            contract_id = assigment_vals['contract_id'][0]
            contract_fields = ['cups', 'state', 'data_ultima_lectura',
                               'cups_direccio']
            contract_vals = contract_obj.read(
                cursor, uid, contract_id, contract_fields
            )
            if 'cups_anual_use' in field_names:
                cups_id = contract_vals['cups'][0]
                cups_vals = cups_obj.read(cursor, uid, cups_id, ['conany_kwh'])
                res[assignment_id]['cups_anual_use'] = cups_vals['conany_kwh']

            for field, contract_field in FF_CONTRACT_FIELDS:
                if field in field_names:
                    res[assignment_id][field] = contract_vals[contract_field]

        return res

    def _default_member_id(self, cursor, uid, context=None):
        """Gets default member_id from context
        :return: member_id
        """
        if context is None:
            context = {}

        return context.get('member_id', False)

    _columns = dict(
        contract_id=fields.many2one(
            'giscedata.polissa',
            'Contracte',
            required=True,
            help="Contracte que te els drets per utilitzar els kWh generats",
            ),
        member_id=fields.many2one(
            'somenergia.soci',
            'Soci',
            readonly=True,
            required=True,
            help="Soci que va comprar accions Generation kWh i els assigna",
            ),
        priority=fields.integer(
            'Prioritat',
            required=True,
            help="Ordre d'assignacions. "
                 "Aquesta assignació no usara drets generats en els dates que"
                 "encara no han estat facturades a assignacions del mateix soci"
                 " que tinguin una prioritat mes alta."
                 "(a valor més petit, més prioritat",
            ),
        end_date=fields.date(
            "Data d'Expiració",
            help="Data a partir de la qual l'assignació ja no serà activa",
            ),
        # Contract fields
        contract_state=fields.function(
            _ff_contract, string='Contract State', readonly=True, type='char',
            method=True, multi='contract',
            help="Estat del contracte seleccionat",
            ),
        contract_last_invoiced=fields.function(
            _ff_contract, string='Data última factura', readonly=True,
            type='date', method=True, multi='contract',
            help="Data Última lectura facturada",
            ),
        cups_direction=fields.function(
            _ff_contract, string='Direcció CUPS', readonly=True, type='char',
            method=True, multi='contract',
            help="Direcció del CUPS",
            ),
        # Contract fields
        cups_anual_use=fields.function(
            _ff_contract, string='Consum anual', readonly=True, type='integer',
            method=True, multi='contract',
            help="Consum anyal del CUPS. Pot ser estimat.",
            ),
        )

    _defaults = dict(
        member_id=_default_member_id,
    )

    def log_action(self, cursor, uid, ass_id, text, context=None):
        """
        :param text: Text to log
        :return: added text
        """
        Member = self.pool.get('somenergia.soci')

        member_id = self.read(
            cursor, uid, ass_id, ['member_id']
        )['member_id'][0]
        return Member.add_gkwh_comment(cursor, uid, member_id, text)

    def create(self, cr, uid, values, context=None):

        Contract = self.pool.get('giscedata.polissa')

        member_id = values.get('member_id',None)
        contract_id = values.get('contract_id',None)
        priority = values.get('priority', 0)

        self.expire(cr, uid, contract_id, member_id, context=context)

        assignment_id = super(GenerationkWhAssignment, self).create(
            cr, uid, values, context=context
        )

        if contract_id:
            contract_name = Contract.read(
                cr, uid, contract_id, ['name'], context=context
            )['name']

            text_tmpl = _(u"NOVA assignació ({0}) al contracte  {1} amb "
                          u"prioritat {2}")
            text = text_tmpl.format(assignment_id, contract_name, priority)

            self.log_action(cr, uid, assignment_id, text, context=context)

        return assignment_id

    def write(self, cr, uid, ids, values, context=None):

        res = super(GenerationkWhAssignment, self).write(
            cr, uid, ids, values, context=context
        )

        assignment_vals = self.read(cr, uid, ids, ['contract_id', 'priority'])
        for assignment in assignment_vals:
            assignment_id = assignment['id']
            text_tmpl = _(u"MODIFICADA assignació ({0}):  contracte {1} amb "
                          u"prioritat {2}")
            text = text_tmpl.format(
                assignment_id,
                assignment['contract_id'][1],
                assignment['priority'],
            )

            self.log_action(cr, uid, assignment_id, text, context=context)

        return res

    def unlink(self, cr, uid, ids, context=None):

        assignment_vals = self.read(cr, uid, ids, ['contract_id', 'priority'])
        for assignment in assignment_vals:
            assignment_id = assignment['id']
            text_tmpl = _(u"ESBORRADA assignació ({0}):  contracte {1} amb "
                          u"prioritat {2}")
            text = text_tmpl.format(
                assignment_id,
                assignment['contract_id'][1],
                assignment['priority'],
            )
            self.log_action(cr, uid, assignment_id, text, context=context)

        return super(GenerationkWhAssignment, self).unlink(<commit_msg>IMP Better assigment write log<commit_after># -*- coding: utf-8 -*-

from osv import osv, fields
from .erpwrapper import ErpWrapper
import datetime
from yamlns import namespace as ns
from generationkwh.isodates import isodate
from tools.translate import _

# TODO: sort rights sources if many members assigned the same contract
# TODO: Filter out inactive contracts

FF_CONTRACT_FIELDS = [
    ('contract_state', 'state'),
    ('contract_last_invoiced', 'data_ultima_lectura'),
    ('cups_direction', 'cups_direccio'),
]


# TODO: This function is duplicated in other sources
def _sqlfromfile(sqlname):
    from tools import config
    import os
    sqlfile = os.path.join(
        config['addons_path'], 'som_generationkwh',
            'sql', sqlname+'.sql')
    with open(sqlfile) as f:
        return f.read()


class GenerationkWhAssignment(osv.osv):

    _name = 'generationkwh.assignment'
    _order = 'member_id, priority, contract_id'

    def _ff_contract(self, cursor, uid, ids, field_names, args, context=None):
        """  Function to read contract values from function fields"""
        contract_obj = self.pool.get('giscedata.polissa')
        cups_obj = self.pool.get('giscedata.cups.ps')

        if not isinstance(ids, (tuple, list)):
            ids = [ids]

        init_dict = dict([(f, False) for f in field_names])
        res = {}.fromkeys(ids, {})
        for k in res.keys():
            res[k] = init_dict.copy()

        for assigment_vals in self.read(cursor, uid, ids, ['contract_id']):
            assignment_id = assigment_vals['id']
            contract_id = assigment_vals['contract_id'][0]
            contract_fields = ['cups', 'state', 'data_ultima_lectura',
                               'cups_direccio']
            contract_vals = contract_obj.read(
                cursor, uid, contract_id, contract_fields
            )
            if 'cups_anual_use' in field_names:
                cups_id = contract_vals['cups'][0]
                cups_vals = cups_obj.read(cursor, uid, cups_id, ['conany_kwh'])
                res[assignment_id]['cups_anual_use'] = cups_vals['conany_kwh']

            for field, contract_field in FF_CONTRACT_FIELDS:
                if field in field_names:
                    res[assignment_id][field] = contract_vals[contract_field]

        return res

    def _default_member_id(self, cursor, uid, context=None):
        """Gets default member_id from context
        :return: member_id
        """
        if context is None:
            context = {}

        return context.get('member_id', False)

    _columns = dict(
        contract_id=fields.many2one(
            'giscedata.polissa',
            'Contracte',
            required=True,
            help="Contracte que te els drets per utilitzar els kWh generats",
            ),
        member_id=fields.many2one(
            'somenergia.soci',
            'Soci',
            readonly=True,
            required=True,
            help="Soci que va comprar accions Generation kWh i els assigna",
            ),
        priority=fields.integer(
            'Prioritat',
            required=True,
            help="Ordre d'assignacions. "
                 "Aquesta assignació no usara drets generats en els dates que"
                 "encara no han estat facturades a assignacions del mateix soci"
                 " que tinguin una prioritat mes alta."
                 "(a valor més petit, més prioritat",
            ),
        end_date=fields.date(
            "Data d'Expiració",
            help="Data a partir de la qual l'assignació ja no serà activa",
            ),
        # Contract fields
        contract_state=fields.function(
            _ff_contract, string='Contract State', readonly=True, type='char',
            method=True, multi='contract',
            help="Estat del contracte seleccionat",
            ),
        contract_last_invoiced=fields.function(
            _ff_contract, string='Data última factura', readonly=True,
            type='date', method=True, multi='contract',
            help="Data Última lectura facturada",
            ),
        cups_direction=fields.function(
            _ff_contract, string='Direcció CUPS', readonly=True, type='char',
            method=True, multi='contract',
            help="Direcció del CUPS",
            ),
        # Contract fields
        cups_anual_use=fields.function(
            _ff_contract, string='Consum anual', readonly=True, type='integer',
            method=True, multi='contract',
            help="Consum anyal del CUPS. Pot ser estimat.",
            ),
        )

    _defaults = dict(
        member_id=_default_member_id,
    )

    def log_action(self, cursor, uid, ass_id, text, context=None):
        """
        :param text: Text to log
        :return: added text
        """
        Member = self.pool.get('somenergia.soci')

        member_id = self.read(
            cursor, uid, ass_id, ['member_id']
        )['member_id'][0]
        return Member.add_gkwh_comment(cursor, uid, member_id, text)

    def create(self, cr, uid, values, context=None):

        Contract = self.pool.get('giscedata.polissa')

        member_id = values.get('member_id',None)
        contract_id = values.get('contract_id',None)
        priority = values.get('priority', 0)

        self.expire(cr, uid, contract_id, member_id, context=context)

        assignment_id = super(GenerationkWhAssignment, self).create(
            cr, uid, values, context=context
        )

        if contract_id:
            contract_name = Contract.read(
                cr, uid, contract_id, ['name'], context=context
            )['name']

            text_tmpl = _(u"NOVA assignació ({0}) al contracte  {1} amb "
                          u"prioritat {2}")
            text = text_tmpl.format(assignment_id, contract_name, priority)

            self.log_action(cr, uid, assignment_id, text, context=context)

        return assignment_id

    def write(self, cr, uid, ids, values, context=None):

        # fields to log
        assignment_fields = ['contract_id', 'priority']

        # current values
        current_assignment_vals = self.read(cr, uid, ids, assignment_fields)
        current_assignments = dict(
            [(a['id'], a) for a in current_assignment_vals]
        )

        # write
        res = super(GenerationkWhAssignment, self).write(
            cr, uid, ids, values, context=context
        )

        # new_values
        fields_txt_list = []
        tuple_fields = ['contract_id']
        assignment_vals = self.read(cr, uid, ids, assignment_fields)
        for assignment in assignment_vals:
            assignment_id = assignment['id']
            header = _(u"MODIFICADA assignació ({0}):").format(assignment_id)

            current_assignment = current_assignments[assignment_id]
            fields_txt = ''
            for field in assignment_fields:
                current_value = current_assignment[field]
                new_value = assignment[field]
                if field in tuple_fields:
                    current_value = current_value[1]
                    new_value = new_value[1]
                if current_value != new_value:
                    fields_txt_list.append(
                        "• {0}: {1} → {2}".format(
                            field,
                            current_value,
                            new_value
                        )
                    )

            text = "{0}\n{1}".format(header, '\n'.join(fields_txt_list))

            self.log_action(cr, uid, assignment_id, text, context=context)

        return res

    def unlink(self, cr, uid, ids, context=None):

        assignment_vals = self.read(cr, uid, ids, ['contract_id', 'priority'])
        for assignment in assignment_vals:
            assignment_id = assignment['id']
            text_tmpl = _(u"ESBORRADA assignació ({0}):  contracte {1} amb "
                          u"prioritat {2}")
            text = text_tmpl.format(
                assignment_id,
                assignment['contract_id'][1],
                assignment['priority'],
            )
            self.log_action(cr, uid, assignment_id, text, context=context)

        return super(GenerationkWhAssignment, self).unlink(
{'fraction_non_alphanumeric': 0.10443058324223523, 'fraction_numerical': 0.002572181853257025, 'mean_word_length': 2.0680607614914184, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5502454', 'n_tokens_mistral': 4486, 'n_tokens_neox': 4445, 'n_words': 1074}