コード例 #1
0
ファイル: ir_actions.py プロジェクト: Elbagoury/metro-openerp
    def _action_email(self,cr,uid,user,action,cxt,context=None):
        email_from = config['email_from']
        if not email_from:
            _logger.debug('--email-from command line option is not specified, using a fallback value instead.')
            if user.email:
                email_from = user.email
            else:
                email_from = "%[email protected]%s" % (user.login, gethostname())

        try:
            address = eval(str(action.email), cxt)
        except Exception:
            address = str(action.email)
            
        try:
            address_cc = eval(str(action.email_cc), cxt)
        except Exception:
            address_cc = str(action.email_cc)
            
        try:
            address_bcc = eval(str(action.email_bcc), cxt)
        except Exception:
            address_bcc = str(action.email_bcc)
            
        try:
            address_reply_to = eval(str(action.email_reply_to), cxt)
        except Exception:
            address_reply_to = str(action.email_reply_to)                                          

        if not address:
            _logger.info('No to email address specified, not sending any email.')
            return

        # handle single and multiple recipient addresses
        addresses = address if isinstance(address, (tuple, list)) else [address]
        address_cces = None
        if address_cc:
            address_cces = address_cc if isinstance(address_cc, (tuple, list)) else [address_cc]
        addresses_bcces = None
        if address_bcc:
            address_bcc if isinstance(address_bcc, (tuple, list)) else [address_bcc]
        address_reply_toes = None
        if address_reply_to:
            address_reply_toes = address_reply_to if address_reply_to else None

        email_subtype = action.email_subtype or 'plain';
                
        subject = self.merge_message(cr, uid, action.subject, action, context)
        body = self.merge_message(cr, uid, action.message, action, context)

        ir_mail_server = self.pool.get('ir.mail_server')
        msg = ir_mail_server.build_email(email_from, addresses, subject, body,
                                         email_cc = address_cces, email_bcc = addresses_bcces, reply_to = address_reply_toes,
                                         subtype = email_subtype)
               
        res_email = ir_mail_server.send_email(cr, uid, msg)
        if res_email:
            _logger.info('Email successfully sent to: %s', addresses)
        else:
            _logger.warning('Failed to send email to: %s', addresses)        
コード例 #2
0
ファイル: document.py プロジェクト: cysnake4713/updis-erp
 def calc_privilege(self, cr, uid, ids, method, context):
     if isinstance(ids, (int, long)):
         ids = [ids]
     access = self.browse(cr, 1, ids[0], context)
     # If method need eval
     if method in ['perm_write', 'is_downloadable']:
         if access[method] is False:
             return False
         if access.code and access.code.strip():
             ctx = {
                 'self': self,
                 'object': access,
                 'obj': access,
                 'pool': self.pool,
                 'time': time,
                 'cr': cr,
                 'context': dict(context),  # copy context to prevent side-effects of eval
                 'uid': uid,
                 'user': self.pool.get('res.users').browse(cr, uid, uid),
                 'result': None,
             }
             ctx.update(context.get('ctx', {}))
             eval(access.code.strip(), ctx, mode="exec", nocopy=True)  # nocopy allows to return 'action'
             return True if ctx.get('result', None) else False
         else:
             return True
     else:
         return access[method]
コード例 #3
0
ファイル: google_drive.py プロジェクト: zbqf109/goodo
 def get_google_drive_config(self, cr, uid, res_model, res_id, context=None):
     '''
     Function called by the js, when no google doc are yet associated with a record, with the aim to create one. It
     will first seek for a google.docs.config associated with the model `res_model` to find out what's the template
     of google doc to copy (this is usefull if you want to start with a non-empty document, a type or a name
     different than the default values). If no config is associated with the `res_model`, then a blank text document
     with a default name is created.
       :param res_model: the object for which the google doc is created
       :param ids: the list of ids of the objects for which the google doc is created. This list is supposed to have
         a length of 1 element only (batch processing is not supported in the code, though nothing really prevent it)
       :return: the config id and config name
     '''
     if not res_id:
         raise UserError(_("Creating google drive may only be done by one at a time."))
     # check if a model is configured with a template
     config_ids = self.search(cr, uid, [('model_id', '=', res_model)], context=context)
     configs = []
     for config in self.browse(cr, uid, config_ids, context=context):
         if config.filter_id:
             if (config.filter_id.user_id and config.filter_id.user_id.id != uid):
                 #Private
                 continue
             domain = [('id', 'in', [res_id])] + eval(config.filter_id.domain)
             local_context = context and context.copy() or {}
             local_context.update(eval(config.filter_id.context))
             google_doc_configs = self.pool.get(config.filter_id.model_id).search(cr, uid, domain, context=local_context)
             if google_doc_configs:
                 configs.append({'id': config.id, 'name': config.name})
         else:
             configs.append({'id': config.id, 'name': config.name})
     return configs
コード例 #4
0
ファイル: field_mapping.py プロジェクト: VbossEkat/odoo-etl
 def run_expressions(self, cr, uid, ids, rec_id, source_connection=False, target_connection=False, context=None):
     if context is None:
         context = {}
     user = self.pool.get('res.users').browse(cr, uid, uid)
     result = []
     
     for field_mapping in self.browse(cr, uid, ids, context=context):
         expression_result = False
         if not source_connection or not target_connection:
             (source_connection, target_connection) = self.pool.get('etl.manager').open_connections(cr, uid, [field_mapping.action_id.manager_id.id], context=context)
         source_model_obj = source_connection.get_model(field_mapping.action_id.source_model_id.model)    
         target_model_obj = target_connection.get_model(field_mapping.action_id.target_model_id.model)    
         
         obj_pool = source_model_obj
         cxt = {
             'self': obj_pool, #to be replaced by target_obj
             'source_obj': source_model_obj,
             'source_connection': source_connection,
             'target_obj': target_model_obj,
             'target_connection': target_connection,
             'rec_id': rec_id,
             'pool': self.pool,
             'time': time,
             'cr': cr,
             'context': dict(context), # copy context to prevent side-effects of eval
             'uid': uid,
             'user': user,
         }
         if not field_mapping.expression:
             raise osv.except_osv(_('Warning!'),_('Type expression choosen buy not expression set'))
         eval(field_mapping.expression.strip(), cxt, mode="exec") # nocopy allows to return 'action'
         if 'result' in cxt['context']:
             expression_result = cxt['context'].get('result')
         result.append(expression_result)
     return result
コード例 #5
0
 def process(self, msg):
     match_context = {
         'self': self,
         'msg': msg,
         'result': False,
         'context': {},
         're': re,
     }
     if self.match:
         eval(self.match, match_context, mode="exec", nocopy=True)
     if match_context['result']:
         reply_context = {}
         action_context = {
             'self': self,
             'msg': msg,
             'reply': reply_context,
             'context': match_context['context'],
             'template': self.template
         }
         eval(self.action, action_context, mode="exec", nocopy=True)
         # build reply
         if self.reply_type != 'news':
             reply_context['message'] = msg
             reply = replies.REPLY_TYPES[self.reply_type](**reply_context)
         else:
             reply = replies.ArticlesReply(message=msg)
             for article in reply_context['articles']:
                 reply.add_article(article)
         return True, reply
     else:
         return False, None
コード例 #6
0
ファイル: utils.py プロジェクト: erplens/erplens
def _child_get(node, self=None, tagname=None):
    for n in node:
        if self and self.localcontext and n.get('rml_loop'):

            for ctx in eval(n.get('rml_loop'),{}, self.localcontext):
                self.localcontext.update(ctx)
                if (tagname is None) or (n.tag==tagname):
                    if n.get('rml_except', False):
                        try:
                            eval(n.get('rml_except'), {}, self.localcontext)
                        except GeneratorExit:
                            continue
                        except Exception, e:
                            _logger.warning('rml_except: "%s"', n.get('rml_except',''), exc_info=True)
                            continue
                    if n.get('rml_tag'):
                        try:
                            (tag,attr) = eval(n.get('rml_tag'),{}, self.localcontext)
                            n2 = copy.deepcopy(n)
                            n2.tag = tag
                            n2.attrib.update(attr)
                            yield n2
                        except GeneratorExit:
                            yield n
                        except Exception, e:
                            _logger.warning('rml_tag: "%s"', n.get('rml_tag',''), exc_info=True)
                            yield n
                    else:
                        yield n
            continue
コード例 #7
0
ファイル: base_ir_rule.py プロジェクト: KDVN/odoo-addons
 def _domain_force_get(self, cr, uid, ids, field_name, arg, context=None):
     res = {}
     eval_context = self._eval_context(cr, uid)
     for rule in self.browse(cr, uid, ids, context):
         tmp_domain=str(rule.domain_force)
         if tmp_domain.find("%s")>0:
                 tmp_domain=eval(rule.domain_force)                  
                 str_query=str(tmp_domain[0][2])
                 cr.execute(str_query % uid)
                 tmp_ids=cr.fetchall()
                 list_ids=[]
                 for i in tmp_ids:
                     list_ids.append(i[0])
                 res[rule.id] = eval("[('"+tmp_domain[0][0]+"','"+tmp_domain[0][1]+"',"+str(list_ids)+")]")
         elif tmp_domain.find('.sql.query')>0:
             tmp_domain=eval(rule.domain_force)                  
             str_query=str(tmp_domain[0][2])
             str_query=str_query.replace('.sql.query','')
             cr.execute(str_query)
             tmp_ids=cr.fetchall()
             list_ids=[]
             for i in tmp_ids:
                 list_ids.append(i[0])
             res[rule.id] = eval("[('"+tmp_domain[0][0]+"','"+tmp_domain[0][1]+"',"+str(list_ids)+")]")
         elif rule.domain_force:
             res[rule.id] = expression.normalize_domain(eval(rule.domain_force, eval_context))
         else:
             res[rule.id] = []
     return res
コード例 #8
0
ファイル: hr_payroll.py プロジェクト: aryakgupta/erp-edu
 def compute_rule(self, cr, uid, rule_id, localdict, context=None):
     """
     :param rule_id: id of rule to compute
     :param localdict: dictionary containing the environement in which to compute the rule
     :return: returns a tuple build as the base/amount computed, the quantity and the rate
     :rtype: (float, float, float)
     """
     rule = self.browse(cr, uid, rule_id, context=context)
     if rule.amount_select == 'fix':
         try:
             return rule.amount_fix, float(eval(rule.quantity, localdict)), 100.0
         except:
             raise UserError(_('Wrong quantity defined for salary rule %s (%s).') % (rule.name, rule.code))
     elif rule.amount_select == 'percentage':
         try:
             return (float(eval(rule.amount_percentage_base, localdict)),
                     float(eval(rule.quantity, localdict)),
                     rule.amount_percentage)
         except:
             raise UserError(_('Wrong percentage base or quantity defined for salary rule %s (%s).') % (rule.name, rule.code))
     else:
         try:
             eval(rule.amount_python_compute, localdict, mode='exec', nocopy=True)
             return float(localdict['result']), 'result_qty' in localdict and localdict['result_qty'] or 1.0, 'result_rate' in localdict and localdict['result_rate'] or 100.0
         except:
             raise UserError(_('Wrong python code defined for salary rule %s (%s).') % (rule.name, rule.code))
コード例 #9
0
ファイル: ir_ui_menu.py プロジェクト: BusinessAgile/OCB
    def get_needaction_data(self, cr, uid, ids, context=None):
        """ Return for each menu entry of ids :
            - if it uses the needaction mechanism (needaction_enabled)
            - the needaction counter of the related action, taking into account
              the action domain
        """
        if context is None:
            context = {}
        res = {}
        menu_ids = set()
        for menu in self.browse(cr, uid, ids, context=context):
            menu_ids.add(menu.id)
            ctx = None
            if menu.action and menu.action.type in ('ir.actions.act_window', 'ir.actions.client') and menu.action.context:
                try:
                    # use magical UnquoteEvalContext to ignore undefined client-side variables such as `active_id`
                    eval_ctx = tools.UnquoteEvalContext(**context)
                    ctx = eval(menu.action.context, locals_dict=eval_ctx, nocopy=True) or None
                except Exception:
                    # if the eval still fails for some reason, we'll simply skip this menu
                    pass
            menu_ref = ctx and ctx.get('needaction_menu_ref')
            if menu_ref:
                if not isinstance(menu_ref, list):
                    menu_ref = [menu_ref]
                model_data_obj = self.pool.get('ir.model.data')
                for menu_data in menu_ref:
                    try:
                        model, id = model_data_obj.get_object_reference(cr, uid, menu_data.split('.')[0], menu_data.split('.')[1])
                        if (model == 'ir.ui.menu'):
                            menu_ids.add(id)
                    except Exception:
                        pass

        menu_ids = list(menu_ids)

        for menu in self.browse(cr, uid, menu_ids, context=context):
            res[menu.id] = {
                'needaction_enabled': False,
                'needaction_counter': False,
            }
            if menu.action and menu.action.type in ('ir.actions.act_window', 'ir.actions.client') and menu.action.res_model:
                if menu.action.res_model in self.pool:
                    obj = self.pool[menu.action.res_model]
                    if obj._needaction:
                        if menu.action.type == 'ir.actions.act_window':
                            dom = menu.action.domain and eval(menu.action.domain, {'uid': uid}) or []
                        else:
                            dom = eval(menu.action.params_store or '{}', {'uid': uid}).get('domain')
                        res[menu.id]['needaction_enabled'] = obj._needaction
                        ctx = context
                        if menu.action.context:
                            try:
                                # use magical UnquoteEvalContext to ignore undefined client-side variables such as `active_id`
                                eval_ctx = tools.UnquoteEvalContext(**context)
                                ctx = eval(menu.action.context, locals_dict=eval_ctx, nocopy=True) or None
                            except Exception:
                                pass
                        res[menu.id]['needaction_counter'] = obj._needaction_count(cr, uid, dom, context=ctx)
        return res
コード例 #10
0
ファイル: custom.py プロジェクト: goldenboy/razvoj
 def _row_get(self, cr, uid, objs, fields, conditions, row_canvas=None, group_by=None):
     result = []
     tmp = []
     for obj in objs:
         tobreak = False
         for cond in conditions:
             if cond and cond[0]:
                 c = cond[0]
                 temp = c[0](eval('obj.'+c[1],{'obj': obj}))
                 if not eval('\''+temp+'\''+' '+c[2]+' '+'\''+str(c[3])+'\''):
                     tobreak = True
         if tobreak:
             break
         levels = {}
         row = []
         for i in range(len(fields)):
             if not fields[i]:
                 row.append(row_canvas and row_canvas[i])
                 if row_canvas[i]:
                     row_canvas[i]=False
             elif len(fields[i])==1:
                 if not isinstance(obj, browse_null):
                     row.append(str(eval('obj.'+fields[i][0],{'obj': obj})))
                 else:
                     row.append(None)
             else:
                 row.append(None)
                 levels[fields[i][0]]=True
         if not levels:
             result.append(row)
         else:
             # Process group_by data first
             key = []
             if group_by != None and fields[group_by] != None:
                 if fields[group_by][0] in levels.keys():
                     key.append(fields[group_by][0])
                 for l in levels.keys():
                     if l != fields[group_by][0]:
                         key.append(l)
             else:
                 key = levels.keys()
             for l in key:
                 objs = eval('obj.'+l,{'obj': obj})
                 if not isinstance(objs, browse_record_list) and type(objs) <> type([]):
                     objs = [objs]
                 field_new = []
                 cond_new = []
                 for f in range(len(fields)):
                     if (fields[f] and fields[f][0])==l:
                         field_new.append(fields[f][1:])
                         cond_new.append(conditions[f][1:])
                     else:
                         field_new.append(None)
                         cond_new.append(None)
                 if len(objs):
                     result += self._row_get(cr, uid, objs, field_new, cond_new, row, group_by)
                 else:
                     result.append(row)
     return result 
コード例 #11
0
ファイル: edi_route.py プロジェクト: vertelab/odoo-edi
 def run_action_code(self, values):
     try:
         eval_context = self._get_eval_context(values)
         eval(self.code.strip(), eval_context, mode="exec", nocopy=True)  # nocopy allows to return 'result'
         if 'result' in eval_context:
             return eval_context['result']
     except SyntaxError:
         _logger.error('code %s values %s' %(self.code.strip(), self._get_eval_context(values)))
コード例 #12
0
ファイル: custom.py プロジェクト: 0k/odoo
 def _row_get(self, cr, uid, objs, fields, conditions, row_canvas=None, group_by=None):
     result = []
     for obj in objs:
         tobreak = False
         for cond in conditions:
             if cond and cond[0]:
                 c = cond[0]
                 temp = c[0](eval("obj." + c[1], {"obj": obj}))
                 if not eval("'" + temp + "'" + " " + c[2] + " " + "'" + str(c[3]) + "'"):
                     tobreak = True
         if tobreak:
             break
         levels = {}
         row = []
         for i in range(len(fields)):
             if not fields[i]:
                 row.append(row_canvas and row_canvas[i])
                 if row_canvas[i]:
                     row_canvas[i] = False
             elif len(fields[i]) == 1:
                 if obj:
                     row.append(str(eval("obj." + fields[i][0], {"obj": obj})))
                 else:
                     row.append(None)
             else:
                 row.append(None)
                 levels[fields[i][0]] = True
         if not levels:
             result.append(row)
         else:
             # Process group_by data first
             key = []
             if group_by is not None and fields[group_by] is not None:
                 if fields[group_by][0] in levels.keys():
                     key.append(fields[group_by][0])
                 for l in levels.keys():
                     if l != fields[group_by][0]:
                         key.append(l)
             else:
                 key = levels.keys()
             for l in key:
                 objs = eval("obj." + l, {"obj": obj})
                 if not isinstance(objs, (BaseModel, list)):
                     objs = [objs]
                 field_new = []
                 cond_new = []
                 for f in range(len(fields)):
                     if (fields[f] and fields[f][0]) == l:
                         field_new.append(fields[f][1:])
                         cond_new.append(conditions[f][1:])
                     else:
                         field_new.append(None)
                         cond_new.append(None)
                 if len(objs):
                     result += self._row_get(cr, uid, objs, field_new, cond_new, row, group_by)
                 else:
                     result.append(row)
     return result
コード例 #13
0
ファイル: base_action_rule.py プロジェクト: 19317362/odoo
    def _check(self, cr, uid, automatic=False, use_new_cursor=False, context=None):
        """ This Function is called by scheduler. """
        context = context or {}
        if '__action_done' not in context:
            context = dict(context, __action_done={})
        # retrieve all the action rules to run based on a timed condition
        action_dom = [('kind', '=', 'on_time')]
        action_ids = self.search(cr, uid, action_dom, context=dict(context, active_test=True))
        eval_context = self._get_eval_context(cr, uid, context=context)
        for action in self.browse(cr, uid, action_ids, context=context):
            now = datetime.now()
            if action.last_run:
                last_run = get_datetime(action.last_run)
            else:
                last_run = datetime.utcfromtimestamp(0)
            # retrieve all the records that satisfy the action's condition
            model = self.pool[action.model_id.model]
            domain = []
            ctx = dict(context)
            if action.filter_domain is not False:
                domain = eval(action.filter_domain, eval_context)
            elif action.filter_id:
                domain = eval(action.filter_id.domain, eval_context)
                ctx.update(eval(action.filter_id.context))
                if 'lang' not in ctx:
                    # Filters might be language-sensitive, attempt to reuse creator lang
                    # as we are usually running this as super-user in background
                    [filter_meta] = action.filter_id.get_metadata()
                    user_id = filter_meta['write_uid'] and filter_meta['write_uid'][0] or \
                                    filter_meta['create_uid'][0]
                    ctx['lang'] = self.pool['res.users'].browse(cr, uid, user_id).lang
            record_ids = model.search(cr, uid, domain, context=ctx)

            # determine when action should occur for the records
            date_field = action.trg_date_id.name
            if date_field == 'date_action_last' and 'create_date' in model._fields:
                get_record_dt = lambda record: record[date_field] or record.create_date
            else:
                get_record_dt = lambda record: record[date_field]

            # process action on the records that should be executed
            for record in model.browse(cr, uid, record_ids, context=context):
                record_dt = get_record_dt(record)
                if not record_dt:
                    continue
                action_dt = self._check_delay(cr, uid, action, record, record_dt, context=context)
                if last_run <= action_dt < now:
                    try:
                        action._process(record)
                    except Exception:
                        import traceback
                        _logger.error(traceback.format_exc())

            action.write({'last_run': now.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})

            if automatic:
                # auto-commit for batch processing
                cr.commit()
コード例 #14
0
ファイル: report.py プロジェクト: Niboo/niboo-community
    def add_terms_and_conditions(self, ids, original_report_pdf,
                                 original_report):

        terms_and_conditions_decoded = False
        default_terms_and_conditions_decoded = False


        user = self.env['res.users'].browse(self._uid)

        # todo change user language to report language (client language)

        language_field = original_report.terms_conditions_language_field
        model = original_report.model

        object = self.env[model].browse(ids)
        localdict = {'o': object}
        eval('document_language = o.%s' % language_field, localdict,
             mode="exec", nocopy=True)
        document_language = localdict.get('document_language',
                                          self._context.get('lang'))

        company = object.company_id
        # todo check language
        terms_and_conditions_list = company.terms_and_conditions

        for terms_and_conditions in terms_and_conditions_list:
            if terms_and_conditions.language == document_language:
                terms_and_conditions_decoded =\
                    base64.decodestring(terms_and_conditions.datas)
            if terms_and_conditions.language == 'default':
                default_terms_and_conditions_decoded = \
                    base64.decodestring(terms_and_conditions.datas)

        if not terms_and_conditions_decoded:
            terms_and_conditions_decoded = \
                default_terms_and_conditions_decoded or False

        if terms_and_conditions_decoded:
            writer = PdfFileWriter()
            stream_original_report = StringIO(original_report_pdf)
            reader_original_report = PdfFileReader(stream_original_report)
            stream_terms_and_conditions = StringIO(terms_and_conditions_decoded)
            reader_terms_and_conditions = PdfFileReader(
                stream_terms_and_conditions)
            for page in range(0, reader_original_report.getNumPages()):
                writer.addPage(reader_original_report.getPage(page))

            for page in range(0, reader_terms_and_conditions.getNumPages()):
                writer.addPage(reader_terms_and_conditions.getPage(page))

            stream_to_write = StringIO()
            writer.write(stream_to_write)

            combined_pdf = stream_to_write.getvalue()

            return combined_pdf
        else:
            return original_report_pdf
コード例 #15
0
    def _check(self, cr, uid, automatic=False, use_new_cursor=False, context=None):
        """ This Function is called by scheduler. """
        context = context or {}
        # retrieve all the action rules that have a trg_date_id and no precondition
        action_dom = [('trg_date_id', '!=', False), ('filter_pre_id', '=', False)]
        action_ids = self.search(cr, uid, action_dom, context=context)
        for action in self.browse(cr, uid, action_ids, context=context):
            now = datetime.now()
            if action.last_run:
                last_run = get_datetime(action.last_run)
            else:
                last_run = datetime.utcfromtimestamp(0)

            # retrieve all the records that satisfy the action's condition
            model = self.pool.get(action.model_id.model)
            domain = []
            ctx = dict(context)
            if action.filter_id:
                domain = eval(action.filter_id.domain)
                ctx.update(eval(action.filter_id.context))
                if 'lang' not in ctx:
                    # Filters might be language-sensitive, attempt to reuse creator lang
                    # as we are usually running this as super-user in background
                    [filter_meta] = action.filter_id.perm_read()
                    user_id = filter_meta['write_uid'] and filter_meta['write_uid'][0] or \
                                    filter_meta['create_uid'][0]
                    ctx['lang'] = self.pool['res.users'].browse(cr, uid, user_id).lang
            record_ids = model.search(cr, uid, domain, context=ctx)

            # determine when action should occur for the records
            date_field = action.trg_date_id.name
            if date_field == 'date_action_last' and 'create_date' in model._all_columns:
                get_record_dt = lambda record: record[date_field] or record.create_date
            else:
                get_record_dt = lambda record: record[date_field]

            delay = DATE_RANGE_FUNCTION[action.trg_date_range_type](action.trg_date_range)

            # process action on the records that should be executed
            for record in model.browse(cr, uid, record_ids, context=context):
                record_dt = get_record_dt(record)
                if not record_dt:
                    continue
                action_dt = get_datetime(record_dt) + delay
                if last_run <= action_dt < now:
                    try:
                        context = dict(context or {}, action=True)
                        self._process(cr, uid, action, [record.id], context=context)
                    except Exception:
                        import traceback
                        _logger.error(traceback.format_exc())

            action.write({'last_run': now.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})

            if automatic:
                # auto-commit for batch processing
                cr.commit()
コード例 #16
0
 def _filter(self, cr, uid, action, action_filter, record_ids, context=None):
     """ filter the list record_ids that satisfy the action filter """
     if record_ids and action_filter:
         assert action.model == action_filter.model_id, "Filter model different from action rule model"
         model = self.pool.get(action_filter.model_id)
         domain = [('id', 'in', record_ids)] + eval(action_filter.domain)
         ctx = dict(context or {})
         ctx.update(eval(action_filter.context))
         record_ids = model.search(cr, uid, domain, context=ctx)
     return record_ids
コード例 #17
0
ファイル: base_action_rule.py プロジェクト: palankai/odoo
 def _filter(self, cr, uid, action, action_filter, record_ids, domain=False, context=None):
     """ Filter the list record_ids that satisfy the domain or the action filter. """
     if record_ids and (domain is not False or action_filter):
         if domain is not False:
             new_domain = [('id', 'in', record_ids)] + eval(domain)
             ctx = context
         elif action_filter:
             assert action.model == action_filter.model_id, "Filter model different from action rule model"
             new_domain = [('id', 'in', record_ids)] + eval(action_filter.domain)
             ctx = dict(context or {})
             ctx.update(eval(action_filter.context))
         record_ids = self.pool[action.model].search(cr, uid, new_domain, context=ctx)
     return record_ids
コード例 #18
0
 def run(self, image, **kwargs):   # return a image with specified recipe
     kwargs.update({p.name: p.value for p in self.param_ids})    #get parameters from recipe
     #TODO: Remove time import once caching is working
     import time
     kwargs.update({
         'time': time,
         'Image': Image,
         'image': image,
         '_logger': _logger,
         'user': self.env['res.users'].browse(self._uid),
         })
     eval(self.recipe, kwargs, mode='exec', nocopy=True)
     return image
コード例 #19
0
ファイル: base_action_rule.py プロジェクト: Padmahas/odoo
 def _filter_post(self, records):
     """ Filter the records that satisfy the postcondition of action ``self``. """
     if self.filter_id and records:
         eval_context = self._get_eval_context()
         domain = [('id', 'in', records.ids)] + eval(self.filter_id.domain, eval_context)
         ctx = eval(self.filter_id.context)
         return records.with_context(**ctx).search(domain).with_env(records.env)
     elif self.filter_domain and records:
         eval_context = self._get_eval_context()
         domain = [('id', 'in', records.ids)] + eval(self.filter_domain, eval_context)
         return records.search(domain)
     else:
         return records
コード例 #20
0
 def _post_import_operation(self, record, operations):
     """ Run python code after import """
     if not record or not operations:
         return
     try:
         if not isinstance(operations, list):
             operations = [operations]
         for operation in operations:
             if '${' in operation:
                 code = (operation.split('${'))[1].split('}')[0]
                 eval_context = {'object': record}
                 eval(code, eval_context)
     except Exception, e:
         raise except_orm(_('Post import operation error!'), e)
コード例 #21
0
ファイル: product.py プロジェクト: name1984/odoo
    def _search_product_quantity(self, cr, uid, obj, name, domain, context):
        prod = self.pool.get("product.product")
        res = []
        for field, operator, value in domain:
            # to prevent sql injections
            assert field in (
                "qty_available",
                "virtual_available",
                "incoming_qty",
                "outgoing_qty",
            ), "Invalid domain left operand"
            assert operator in ("<", ">", "=", "<=", ">="), "Invalid domain operator"
            assert isinstance(value, (float, int)), "Invalid domain right operand"

            if operator == "=":
                operator = "=="

            product_ids = prod.search(cr, uid, [], context=context)
            ids = []
            if product_ids:
                # TODO: use a query instead of this browse record which is probably making the too much requests, but don't forget
                # the context that can be set with a location, an owner...
                for element in prod.browse(cr, uid, product_ids, context=context):
                    if eval(str(element[field]) + operator + str(value)):
                        ids.append(element.id)
            res.append(("product_variant_ids", "in", ids))
        return res
コード例 #22
0
ファイル: product.py プロジェクト: huangbin2005/odoo
    def _search_product_quantity(self, cr, uid, obj, name, domain, context):
        res = []
        for field, operator, value in domain:
            # to prevent sql injections
            assert field in (
                "qty_available",
                "virtual_available",
                "incoming_qty",
                "outgoing_qty",
            ), "Invalid domain left operand"
            assert operator in ("<", ">", "=", "!=", "<=", ">="), "Invalid domain operator"
            assert isinstance(value, (float, int)), "Invalid domain right operand"

            if operator == "=":
                operator = "=="

            ids = []
            if name == "qty_available" and (value != 0.0 or operator not in ("==", ">=", "<=")):
                res.append(("id", "in", self._search_qty_available(cr, uid, operator, value, context)))
            else:
                product_ids = self.search(cr, uid, [], context=context)
                if product_ids:
                    # TODO: Still optimization possible when searching virtual quantities
                    for element in self.browse(cr, uid, product_ids, context=context):
                        if eval(str(element[field]) + operator + str(value)):
                            ids.append(element.id)
                    res.append(("id", "in", ids))
        return res
コード例 #23
0
ファイル: utils.py プロジェクト: erplens/erplens
def _process_text(self, txt):
        """Translate ``txt`` according to the language in the local context,
           replace dynamic ``[[expr]]`` with their real value, then escape
           the result for XML.

           :param str txt: original text to translate (must NOT be XML-escaped)
           :return: translated text, with dynamic expressions evaluated and
                    with special XML characters escaped (``&,<,>``).
        """
        if not self.localcontext:
            return str2xml(txt)
        if not txt:
            return ''
        result = ''
        sps = _regex.split(txt)
        while sps:
            # This is a simple text to translate
            to_translate = tools.ustr(sps.pop(0))
            result += tools.ustr(self.localcontext.get('translate', lambda x:x)(to_translate))
            if sps:
                txt = None
                try:
                    expr = sps.pop(0)
                    txt = eval(expr, self.localcontext)
                    if txt and isinstance(txt, basestring):
                        txt = tools.ustr(txt)
                except Exception:
                    _logger.error("Failed to evaluate expression [[ %s ]] with context %r while rendering report, ignored.", expr, self.localcontext)
                if isinstance(txt, basestring):
                    result += txt
                elif txt and (txt is not None) and (txt is not False):
                    result += ustr(txt)
        return str2xml(result)
コード例 #24
0
    def satisfy_condition(self, cr, uid, rule_id, localdict, context=None):
        """
        @param rule_id: id of hr.payslip.exception.rule to be tested
        @param contract_id: id of hr.contract to be tested
        @return: returns True if the given rule match the condition for the given contract. Return False otherwise.
        """
        rule = self.browse(cr, uid, rule_id, context=context)

        if rule.condition_select == 'none':
            return True
        else: #python code
            try:
                eval(rule.condition_python, localdict, mode='exec', nocopy=True)
                return 'result' in localdict and localdict['result'] or False
            except:
                raise osv.except_osv(_('Error!'), _('Wrong python condition defined for payroll exception rule %s (%s).')% (rule.name, rule.code))
コード例 #25
0
ファイル: mail_alias.py プロジェクト: aimas/TuniErp-8.0
 def _check_alias_defaults(self, cr, uid, ids, context=None):
     try:
         for record in self.browse(cr, uid, ids, context=context):
             dict(eval(record.alias_defaults))
     except Exception:
         return False
     return True
コード例 #26
0
ファイル: edi.py プロジェクト: aimas/TuniErp-8.0
 def _edi_generate_report_attachment(self, cr, uid, record, context=None):
     """Utility method to generate the first PDF-type report declared for the
        current model with ``usage`` attribute set to ``default``.
        This must be called explicitly by models that need it, usually
        at the beginning of ``edi_export``, before the call to ``super()``."""
     ir_actions_report = self.pool.get('ir.actions.report.xml')
     matching_reports = ir_actions_report.search(cr, uid, [('model','=',self._name),
                                                           ('report_type','=','pdf'),
                                                           ('usage','=','default')])
     if matching_reports:
         report = ir_actions_report.browse(cr, uid, matching_reports[0])
         result, format = openerp.report.render_report(cr, uid, [record.id], report.report_name, {'model': self._name}, context=context)
         eval_context = {'time': time, 'object': record}
         if not report.attachment or not eval(report.attachment, eval_context):
             # no auto-saving of report as attachment, need to do it manually
             result = base64.b64encode(result)
             file_name = record.name_get()[0][1]
             file_name = re.sub(r'[^a-zA-Z0-9_-]', '_', file_name)
             file_name += ".pdf"
             self.pool.get('ir.attachment').create(cr, uid,
                                                   {
                                                    'name': file_name,
                                                    'datas': result,
                                                    'datas_fname': file_name,
                                                    'res_model': self._name,
                                                    'res_id': record.id,
                                                    'type': 'binary'
                                                   },
                                                   context=context)
コード例 #27
0
ファイル: report.py プロジェクト: 3dfxmadscientist/odoo
    def _check_attachment_use(self, cr, uid, ids, report):
        """ Check attachment_use field. If set to true and an existing pdf is already saved, load
        this one now. Else, mark save it.
        """
        save_in_attachment = {}
        if report.attachment_use is True:
            save_in_attachment['model'] = report.model
            save_in_attachment['loaded_documents'] = {}

            for record_id in ids:
                obj = self.pool[report.model].browse(cr, uid, record_id)
                filename = eval(report.attachment, {'object': obj, 'time': time})

                if filename is False:  # May be false if, for instance, the record is in draft state
                    continue
                else:
                    alreadyindb = [('datas_fname', '=', filename),
                                   ('res_model', '=', report.model),
                                   ('res_id', '=', record_id)]

                    attach_ids = self.pool['ir.attachment'].search(cr, uid, alreadyindb)
                    if attach_ids:
                        # Add the loaded pdf in the loaded_documents list
                        pdf = self.pool['ir.attachment'].browse(cr, uid, attach_ids[0]).datas
                        pdf = base64.decodestring(pdf)
                        save_in_attachment['loaded_documents'][record_id] = pdf
                        _logger.info('The PDF document %s was loaded from the database' % filename)
                    else:
                        # Mark current document to be saved
                        save_in_attachment[record_id] = filename
        return save_in_attachment
コード例 #28
0
ファイル: ir_actions.py プロジェクト: evantan/oecode
    def action_launch(self, cr, uid, ids, context=None):
        """ Launch Action of Wizard"""
        wizard_id = ids and ids[0] or False
        wizard = self.browse(cr, uid, wizard_id, context=context)
        if wizard.type in ('automatic', 'once'):
            wizard.write({'state': 'done'})

        # Load action
        act_type = self.pool.get('ir.actions.actions').read(cr, uid, wizard.action_id.id, ['type'], context=context)

        res = self.pool.get(act_type['type']).read(cr, uid, wizard.action_id.id, [], context=context)
        if act_type<>'ir.actions.act_window':
            return res
        res.setdefault('context','{}')
        res['nodestroy'] = True

        # Open a specific record when res_id is provided in the context
        user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        ctx = eval(res['context'], {'user': user})
        if ctx.get('res_id'):
            res.update({'res_id': ctx.pop('res_id')})

        # disable log for automatic wizards
        if wizard.type == 'automatic':
            ctx.update({'disable_log': True})
        res.update({'context': ctx})

        return res
コード例 #29
0
ファイル: mail_alias.py プロジェクト: bleuubuntu/odoo
 def _check_alias_defaults(self):
     try:
         dict(eval(self.alias_defaults))
     except Exception:
         raise UserError(
             _("Invalid expression, it must be a literal python dictionary definition e.g. \"{'field': 'value'}\"")
         )
コード例 #30
0
    def format(self, cr, uid, ids, percent, value, grouping=False, monetary=False, context=None):
        """ Format() will return the language-specific output for float values"""

        if percent[0] != "%":
            raise ValueError("format() must be given exactly one %char format specifier")

        lang_grouping, thousands_sep, decimal_point = self._lang_data_get(cr, uid, ids[0], monetary)
        eval_lang_grouping = eval(lang_grouping)

        formatted = percent % value
        # floats and decimal ints need special action!
        if percent[-1] in "eEfFgG":
            seps = 0
            parts = formatted.split(".")

            if grouping:
                parts[0], seps = intersperse(parts[0], eval_lang_grouping, thousands_sep)

            formatted = decimal_point.join(parts)
            while seps:
                sp = formatted.find(" ")
                if sp == -1:
                    break
                formatted = formatted[:sp] + formatted[sp + 1 :]
                seps -= 1
        elif percent[-1] in "diu":
            if grouping:
                formatted = intersperse(formatted, eval_lang_grouping, thousands_sep)[0]

        return formatted