Exemplo n.º 1
0
 def custom(self, dist_model, candidates, values, **kwargs):
     if self.code.strip().startswith('{'):
         return safe_eval(self.code or '{')
     else:
         local_dict = locals()
         local_dict.update(globals().get('__builtins__', {}))
         safe_eval(self.code, local_dict, mode='exec', nocopy=True)
         return local_dict.get('result', None)
Exemplo n.º 2
0
 def get_fields_name(self, mixed=True):
     result = []
     method = getattr(result, 'extend' if mixed else 'append')
     for strategy in self:
         method(safe_eval(strategy.other_fields)
                if strategy.other_fields else [])
     return set(result) if mixed else result
Exemplo n.º 3
0
def distribute(self, signal, values):
    '''Get all distribution configurations for model and apply each one.

    '''
    dist_model = self.env[WORKDIST_MODELNAME]
    for item in dist_model.sudo().search([('model.model', '=', self._name)]):
        # WARNING: Don't use `item` to alter (write or create), because we're
        # sudo-ing.
        if item.applicable(values):
            strategy = False
            if item.group_field:
                group_id = values.get(item.group_field.name, False)
                if group_id:
                    group_model = item.group_field.relation
                    group = self.env[group_model].browse(group_id)
                    strategy = getattr(group, item.strategy_field.name,
                                       False)
            else:
                strategy = item.strategy_ids[0]
            if strategy:
                other_fields = (safe_eval(item.other_fields)
                                if item.other_fields else {})
                # TODO: check if active user have access to destination
                # field
                val = strategy.apply(item, values, **dict(other_fields))
                if val is not None:
                    values[item.destination_field.name] = val
    return values
Exemplo n.º 4
0
    def _eval_python_code(self, widget, today):
        '''Evaluate the python code of a widget

        '''
        python_code = widget.get('python_code', '')
        if not python_code:
            return
        name = widget.get('name', '')
        env = self.env
        local_dict = locals()
        local_dict.update(globals().get('__builtins__', {}))
        try:
            logger.debug('Starting evaluation of Python code for widget %s' %
                         name)
            safe_eval(python_code, local_dict, mode='exec', nocopy=True)
            logger.debug('Python code for widget %s evaluated sussefully.' %
                         name)
        except ValueError:
            logger.exception(
                'An error happen trying to execute the Python '
                'code for \'%s\' board widget, python code: %s', name,
                python_code)
        widget.update(local_dict.get('result', {}))
Exemplo n.º 5
0
    def get_advanced_journal_types(self):
        '''Returns a dictionary of type opendict() with the system params:
        and their precollection_journal_type_id and prepayment_journal_type_id
        values.

        '''
        res = opendict()
        get_param = self.env['ir.config_parameter'].get_param
        for param in DEFAULT_ADVANCED_JOURNAL_TYPES:
            value = safe_eval(str(get_param(param))) or False
            res[param] = value
            if self:
                setattr(self, param, value)
        return res
Exemplo n.º 6
0
    def get_account_types(self):
        '''Returns a dictionary of type opendict() with the system params:
        advanced_receivable_type_id and advanced_payable_type_id and their
        values.

        '''
        res = opendict()
        get_param = self.env['ir.config_parameter'].get_param
        for param in DEFAULT_ACCOUNT_TYPES:
            value = safe_eval(str(get_param(param))) or False
            res[param] = value
            if self:
                setattr(self, param, value)
        return res
Exemplo n.º 7
0
def _evaluate_domain(dist_model, values):
    domain = dist_model.domain or dist_model.build_domain
    self = dist_model.env[dist_model.destination_field.relation]
    context = dict(dist_model.env.context, lang=False)
    if not domain or all(l.strip().startswith('#')
                         for l in domain.splitlines()
                         if l.strip()):
        domain = []
    else:
        group = False
        if dist_model.group_field:
            group = values.get(dist_model.group_field.name, False)
            if group:
                group = self.browse(group)
        if any(l.strip().startswith('result')
               for l in domain.splitlines()):
            local_dict = locals()
            local_dict.update(globals().get('__builtins__', {}))
            safe_eval(domain, local_dict, mode='exec', nocopy=True)
            domain = local_dict.get('result', [])
        else:
            domain = safe_eval(domain)
    return self.with_context(context).search(domain)
Exemplo n.º 8
0
def evaluate(expression, mode='eval', **kwargs):
    '''Evaluate `expression` in the provided `mode`.

    The expression is provided several functions described below.

    If `mode` is 'eval', return the result of the evaluating the expression.

    If `mode` is 'exec', the `expression` SHOULD assign a 'result' variable;
    if it does so, return the value of 'result', otherwise return None.

    Symbols available to `expression`:

    - `xoeuf.tools.date2str`:func:

    - `xoeuf.tools.dt2str`:func:

    - `xoeuf.tools.normalize_datetime`:func:

    - `xoeuf.tools.localize_datetime`:func:

    - `datetime.timedelta`:class:

    - `datetime.datetime`:class:

    - `dateutil.relativedelta.relativedelta`:class:

    '''
    if mode not in ('eval', 'exec'):
        raise ValueError('Invalid value for mode: %r' % mode)
    from xoeuf.tools import date2str, dt2str
    from xoeuf.tools import normalize_datetime, localize_datetime
    from datetime import timedelta, datetime
    from dateutil.relativedelta import relativedelta
    local_dict = kwargs
    local_dict.update(
        date2str=date2str,
        dt2str=dt2str,
        normalize_datetime=normalize_datetime,
        localize_datetime=localize_datetime,
        timedelta=timedelta,
        datetime=datetime,
        relativedelta=relativedelta,
    )
    local_dict.update(globals().get('__builtins__', {}))
    res = safe_eval(expression, local_dict, mode=mode, nocopy=True)
    if mode == 'exec':
        res = local_dict.get('result', None)
    return res
Exemplo n.º 9
0
def str2dict(maybedict, field_name=None, default=Unset):
    from collections import Mapping
    from xoutil.eight import string_types
    try:
        if isinstance(maybedict, Mapping):
            return dict(maybedict)
        elif isinstance(maybedict, string_types):
            return dict(safe_eval(maybedict))
        elif default is not Unset:
            return default
        else:
            raise TypeError
    except (ValueError, TypeError):
        raise ValidationError(
            _("The format's field '%s' is incorrect because not have "
              "structure dictionary. "
              "Example: {'field1': value1, 'field2': value2}") % field_name)
Exemplo n.º 10
0
 def onchange_strategy_ids(self):
     ''' When the selected strategies change, it is validated that the
     field 'Other field' maintains the structure of a dictionary that its
     values ​​are valid.
     '''
     warning = False
     try:
         other_fields = safe_eval(self.other_fields or '{}')
     except (ValueError, SyntaxError, ):
         other_fields = {}
         warning = {
             'title': _('Warning!'),
             'message': _('Other fields must be a python dict.')
         }
     fields_name = self.strategy_ids.get_fields_name()
     other_fields.update({n: n
                          for n in fields_name - set(other_fields)})
     self.other_fields = str(other_fields)
     return {'warning': warning} if warning else None
Exemplo n.º 11
0
 def _check_other_fields(self):
     ''' Validates that the field names defined in the 'other_field'
     dictionary are among the names of the fields defined for the selected
     strategy. And that the defined fields are in some existing model.
     '''
     for model in self:
         fields_name = model.strategy_ids.get_fields_name()
         if fields_name:
             other_fields = safe_eval(model.other_fields or '{}')
             if not other_fields or not all(
                     other_fields.get(f, False) for f in fields_name):
                 raise ValidationError(
                     _('Other fields must define all fields used on '
                       'selected strategies.'))
             obj = self.env[model.model.model]
             for field in other_fields.itervalues():
                 if not obj or not obj._fields.get(field, False):
                     raise ValidationError(
                         _('Some Other fields defined not exist on '
                           'destination model'))
     return True
Exemplo n.º 12
0
 def _effort(self, dist_model, candidates, values, date_field=False,
             date_start=False, date_end=False):
     model = self.env[dist_model.model.model]
     min_value = None
     next_dist = False
     group_field_name = (dist_model.group_field.name
                         if dist_model.group_field else False)
     args = ([(group_field_name, '=', values[group_field_name])]
             if group_field_name else [])
     args.extend(safe_eval(dist_model.effort_domain)
                 if dist_model.effort_domain else [])
     if date_field:
         if date_start:
             args.append((date_field, '>=', date_start))
         if date_end:
             args.append((date_field, '<=', date_end))
     for x in candidates.ids:
         current_effort = model.search_count(
             args + [(dist_model.destination_field.name, '=', x)])
         if min_value is None or min_value > current_effort:
             min_value = current_effort
             next_dist = x
     return next_dist
Exemplo n.º 13
0
 def _get_result(self):
     return safe_eval(self.value) if self.value else self.value
Exemplo n.º 14
0
 def _get_result(self):
     return safe_eval(self.thing) if self.thing else self.thing
Exemplo n.º 15
0
    def evaluate_bool_expresion(self, definition_result):
        '''Evaluate the predicate's evidence as boolean expression.

        '''
        op_funct = OPERATORS[self.operator][1]
        return bool(op_funct(definition_result, safe_eval(self.operand)))