• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python safe_eval.safe_eval函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tools.safe_eval.safe_eval函数的典型用法代码示例。如果您正苦于以下问题:Python safe_eval函数的具体用法?Python safe_eval怎么用?Python safe_eval使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了safe_eval函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: retry

    def retry(self, cr, uid, ids, context=None):
        if isinstance(ids, int):
            ids = [ids]

        for log in self.browse(cr, uid, ids, context=context):
            origin_context = safe_eval(log.origin_context)
            origin_defaults = safe_eval(log.origin_defaults)

            # keep the id of the line to update it with the result
            origin_context['retry_report_line_id'] = log.id
            # force export of the resource
            origin_context['force_export'] = True
            origin_context['force'] = True
            
            ##TODO remove : not needed since magento 6.1 ########
            origin_context['do_not_update_date'] = True         #
            #####################################################
            
            mapping = self.pool.get(log.res_model).\
            report_action_mapping(cr, uid, context=context)

            method = mapping.get(log.action, False)
            if not method:
                raise Exception("No python method defined for action %s" %
                                (log.action,))
            method(cr, uid,
                   log.res_id,
                   log.external_id,
                   log.external_report_id.external_referential_id.id,
                   origin_defaults,
                   origin_context)

        return True
开发者ID:3dfxmadscientist,项目名称:odoo-extra-1,代码行数:33,代码来源:report.py


示例2: _check_evalexpr

 def _check_evalexpr(self, cr, uid, ids, context=None):
     action = self.browse(cr, uid, ids[0], context=context)
     if action.trg_evalexpr:
         #Test if expression is valid, against an empty dict
         #Newlines are tolerated
         safe_eval(action.trg_evalexpr.replace('\n', ' '),
             {}, DEFAULT_EVALDICT)
     return True
开发者ID:Cywaithaka,项目名称:LibrERP,代码行数:8,代码来源:base_action_rule.py


示例3: build_product_field

    def build_product_field(self, cr, uid, ids, field, context=None):
        def get_description_sale(product):
            description_sale = product.product_tmpl_id.description_sale
            return self.parse(cr, uid, product, description_sale, context=context)

        def get_name(product):
            if context.get('variants_values', False):
                return ((product.product_tmpl_id.name or '')
                        + ' '
                        + (context['variants_values'][product.id] or ''))
            return (product.product_tmpl_id.name or '') + ' ' + (product.variants or '')

        if not context:
            context = {}
        context['is_multi_variants'] = True
        obj_lang = self.pool.get('res.lang')
        lang_ids = obj_lang.search(cr, uid, [('translatable', '=', True)], context=context)
        langs = obj_lang.read(cr, uid, lang_ids, ['code'], context=context)
        lang_code = [x['code'] for x in langs]
        for code in lang_code:
            context['lang'] = code
            for product in self.browse(cr, uid, ids, context=context):
                new_field_value = eval("get_" + field + "(product)")  # TODO convert to safe_eval
                cur_field_value = safe_eval("product." + field, {'product': product})
                if new_field_value != cur_field_value:
                    self.write(cr, uid, product.id, {field: new_field_value}, context=context)
        return True
开发者ID:3dfxsoftware,项目名称:customaddons,代码行数:27,代码来源:product.py


示例4: _cleanup_action_context

    def _cleanup_action_context(self, context_str, user_id):
        """Returns a dict representing the context_str evaluated (safe_eval) as
           a dict where items that are not useful for shared actions
           have been removed. If the evaluation of context_str as a
           dict fails, context_str is returned unaltered.

           :param user_id: the integer uid to be passed as 'uid' in the
                           evaluation context
           """
        result = False
        if context_str:
            try:
                context = safe_eval(context_str, tools.UnquoteEvalContext(), nocopy=True)
                result = dict(context)
                for key in context:
                    # Remove all context keys that seem to toggle default
                    # filters based on the current user, as it makes no sense
                    # for shared users, who would not see any data by default.
                    if key and key.startswith('search_default_') and 'user_id' in key:
                        result.pop(key)
            except Exception:
                # Note: must catch all exceptions, as UnquoteEvalContext may cause many
                #       different exceptions, as it shadows builtins.
                self._logger.debug("Failed to cleanup action context as it does not parse server-side", exc_info=True)
                result = context_str
        return result
开发者ID:goldenboy,项目名称:razvoj,代码行数:26,代码来源:share_wizard.py


示例5: get_sys_logs

def get_sys_logs(cr, uid):
    """
    Utility method to send a publisher warranty get logs messages.
    """
    pool = pooler.get_pool(cr.dbname)

    dbuuid = pool.get("ir.config_parameter").get_param(cr, uid, "database.uuid")
    db_create_date = pool.get("ir.config_parameter").get_param(cr, uid, "database.create_date")
    nbr_users = pool.get("res.users").search(cr, uid, [], count=True)
    contractosv = pool.get("publisher_warranty.contract")
    contracts = contractosv.browse(cr, uid, contractosv.search(cr, uid, []))
    user = pool.get("res.users").browse(cr, uid, uid)
    msg = {
        "dbuuid": dbuuid,
        "nbr_users": nbr_users,
        "dbname": cr.dbname,
        "db_create_date": db_create_date,
        "version": release.version,
        "contracts": [c.name for c in contracts],
        "language": user.context_lang,
    }

    add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
    arguments = {"arg0": msg, "action": "update"}
    arguments_raw = urllib.urlencode(arguments)
    url = config.get("publisher_warranty_url")
    uo = urllib2.urlopen(url, arguments_raw, **add_arg)
    try:
        submit_result = uo.read()
    finally:
        uo.close()

    result = safe_eval(submit_result) if submit_result else {}

    return result
开发者ID:goldenboy,项目名称:razvoj,代码行数:35,代码来源:publisher_warranty.py


示例6: create_returns

    def create_returns(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        move_obj = self.pool.get('stock.move')
        pick_obj = self.pool.get('stock.picking')
        mem_obj  = self.pool.get('stock.return.picking.memory')
        wf_service = netsvc.LocalService("workflow")

        return_context = context.copy()
        return_context['confirm_return'] = False
        ret = super(stock_return_picking, self).create_returns(cr, uid, ids, context=return_context)

        prm_datas = self.read(cr, uid, ids, ['product_return_moves'], context=context)
        for prm_data in prm_datas:
            mem_ids = prm_data['product_return_moves']
            mem_data = mem_obj.read(cr, uid, mem_ids, ['move_id', 'location_dest_id'], context=context)
            move_to_dest = {}
            for data in mem_data:
                move_to_dest.update({data['move_id'][0] : data['location_dest_id'][0]})
            move_ids = [mem['move_id'][0] for mem in mem_data]
            move_datas = move_obj.read(cr, uid, move_ids, ['location_dest_id','move_history_ids2'], context=context)
            for move_data in move_datas:
                new_move_ids = move_data['move_history_ids2']
                for new_move_id in new_move_ids:
                    move_id = move_data['id']
                    move_obj.write(cr, uid, new_move_id, {'location_dest_id' : move_to_dest[move_id]}, context=context)

            new_picking = pick_obj.search(cr, uid, safe_eval(ret['domain']), context=context).pop()
            wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
            pick_obj.force_assign(cr, uid, [new_picking], context)
        return ret
开发者ID:SportPursuit,项目名称:credativ-addons,代码行数:32,代码来源:stock_return_picking.py


示例7: update_menu

    def update_menu(self, cr, uid, action_report, context=None):

        if action_report.created_menu_id and not action_report.linked_menu_id:
            self.delete_menu(cr, uid, action_report.created_menu_id.id, context=context)

        if action_report.linked_menu_id:
            groups_id = [(6, 0, map(lambda x: x.id, action_report.groups_id))]
            if not action_report.created_menu_id:
                result = self.create_menu(cr, uid, {'name' : action_report.name,
                                                    'linked_menu_id': action_report.linked_menu_id.id,
                                                    'report_name' : action_report.report_name,
                                                    'groups_id' : groups_id,
                                                    }, context=context)
            else:
                action = action_report.created_menu_id.action
                if action and action._model._name == 'ir.actions.act_window':
                    existing_context = safe_eval(self.pool.get('ir.actions.act_window').browse(cr, uid, action.id, context=context).context)
                    new_context = existing_context if type(existing_context) == dict else {}
                    new_context['service_name'] = action_report.report_name or ''
                    self.pool.get('ir.actions.act_window').write(cr, uid, [action.id], {'name' : action_report.name or 'Pentaho Report',
                                                                                        'context' : str(new_context),
                                                                                        }, context=context)

                self.pool.get('ir.ui.menu').write(cr, uid, [action_report.created_menu_id.id], {'name' : action_report.name or 'Pentaho Report',
                                                                                                'parent_id' : action_report.linked_menu_id.id,
                                                                                                'groups_id' : groups_id,
                                                                                                }, context=context)
                result = action_report.created_menu_id.id
        else:
            result = 0

        return result
开发者ID:anasmaach,项目名称:ao-openerp,代码行数:32,代码来源:ui.py


示例8: do_check

 def do_check(self, cr, uid, action, obj, context={}):
     ok = super(base_action_rule, self).do_check(cr, uid, action, obj, context=context)
     if action.trg_evalexpr:
         old = None
         #Find in the list this obj's old 
         for x in context.get('_action_old', []):
             old = x.get('id') == obj.id and x
         #Convert tuples (id, name) into id only
         for x in old or []:
             if type(old[x]) == tuple:
                 old[x] = old[x][0]
         #Build dict with new and old and eval the expression
         eval_dict = {
             'old': old,
             'new': context.get('_action_new')}
         try:
             ok = safe_eval(action.trg_evalexpr, {}, eval_dict)
         except (ValueError, KeyError, TypeError):
             ok = False
         #Debug Log
         if ok: 
             _logger.debug('Activated rule %s on record id %d.' % (action.name, obj.id) )
             #print '********************************************************************'
             #print '\n==== Rule:', action.name, action.trg_evalexpr, '===='  '\n---- old:: ', eval_dict['old'], '\n---- new::', eval_dict['new'] 
     return ok
开发者ID:Mwatchorn26,项目名称:odoo-addons,代码行数:25,代码来源:reis_base_action_rule.py


示例9: retry

    def retry(self, cr, uid, ids, context=None):
        if isinstance(ids, (int, long)):
            ids = [ids]

        for log in self.browse(cr, uid, ids, context=context):
            mapping = self.pool.get(log.res_model).\
            report_action_mapping(cr, uid, context=context)

            method = mapping.get(log.action, False)
            if not method:
                raise Exception("No python method defined for action %s" %
                                (log.action,))

            kwargs = {}
            for field, value in method['fields'].items():
                kwargs[field] = safe_eval(value, {'log': log, 'self': self})

            if not kwargs.get('context', False):
                kwargs['context'] = {}

            # keep the id of the line to update it with the result
            kwargs['context']['retry_report_line_id'] = log.id
            # force export of the resource
            kwargs['context']['force_export'] = True
            kwargs['context']['force'] = True

            method['method'](cr, uid, **kwargs)
        return True
开发者ID:ashishoist91,项目名称:Amazon,代码行数:28,代码来源:report.py


示例10: send

    def send(self, cr, uid, tb, explanations, remarks=None, issue_name=None):
        """ Method called by the client to send a problem to the publisher warranty server. """

        if not remarks:
            remarks = ""

        valid_contracts = self._get_valid_contracts(cr, uid)
        valid_contract = valid_contracts[0]

        try:
            origin = "client"
            dbuuid = self.pool.get("ir.config_parameter").get_param(cr, uid, "database.uuid")
            db_create_date = self.pool.get("ir.config_parameter").get_param(cr, uid, "database.create_date")
            user = self.pool.get("res.users").browse(cr, uid, uid)
            user_name = user.name
            email = user.email

            msg = {
                "contract_name": valid_contract.name,
                "tb": tb,
                "explanations": explanations,
                "remarks": remarks,
                "origin": origin,
                "dbname": cr.dbname,
                "dbuuid": dbuuid,
                "db_create_date": db_create_date,
                "issue_name": issue_name,
                "email": email,
                "user_name": user_name,
            }

            add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
            uo = urllib2.urlopen(
                config.get("publisher_warranty_url"), urllib.urlencode({"arg0": msg, "action": "send"}), **add_arg
            )
            try:
                submit_result = uo.read()
            finally:
                uo.close()

            result = safe_eval(submit_result)

            crm_case_id = result

            if not crm_case_id:
                return False

        except osv.except_osv:
            raise
        except Exception:
            _logger.warning("Error sending problem report", exc_info=1)
            raise osv.except_osv(_("Error"), _("Error during communication with the publisher warranty server."))

        return True
开发者ID:goldenboy,项目名称:razvoj,代码行数:54,代码来源:publisher_warranty.py


示例11: compute_product_dimension_extra_price

    def compute_product_dimension_extra_price(self, cr, uid, product_id, product_price_extra=False, dim_price_margin=False, dim_price_extra=False, context=None):
        if context is None:
            context = {}
        dimension_extra = 0.0
        product = self.browse(cr, uid, product_id, context=context)
        for dim in product.dimension_value_ids:
            if product_price_extra and dim_price_margin and dim_price_extra:
                dimension_extra += safe_eval('product.' + product_price_extra, {'product': product}) * safe_eval('dim.' + dim_price_margin, {'dim': dim}) + safe_eval('dim.' + dim_price_extra, {'dim': dim})
            elif not product_price_extra and not dim_price_margin and dim_price_extra:
                dimension_extra += safe_eval('dim.' + dim_price_extra, {'dim': dim})
            elif product_price_extra and dim_price_margin and not dim_price_extra:
                dimension_extra += safe_eval('product.' + product_price_extra, {'product': product}) * safe_eval('dim.' + dim_price_margin, {'dim': dim})
            elif product_price_extra and not dim_price_margin and dim_price_extra:
                dimension_extra += safe_eval('product.' + product_price_extra, {'product': product}) + safe_eval('dim.' + dim_price_extra, {'dim': dim})

        if 'uom' in context:
            product_uom_obj = self.pool.get('product.uom')
            uom = product.uos_id or product.uom_id
            dimension_extra = product_uom_obj._compute_price(cr, uid,
                uom.id, dimension_extra, context['uom'])
        return dimension_extra
开发者ID:Arsalan88,项目名称:openerp-extra-6.1,代码行数:21,代码来源:product_variant.py


示例12: parse

 def parse(self, cr, uid, o, text, context=None):
     if not text:
         return ''
     vals = text.split('[_')
     description = ''
     for val in vals:
         if '_]' in val:
             sub_val = val.split('_]')
             description += (safe_eval(sub_val[0], {'o' :o, 'context':context}) or '' ) + sub_val[1]
         else:
             description += val
     return description
开发者ID:eoconsulting,项目名称:product_variant_multi,代码行数:12,代码来源:product_variant.py


示例13: eval

    def eval(self, record, expr):
#TODO: support remote variables (eg address.title) in expr
# how to do that: parse the string, find dots, replace those dotted variables by temporary
# "simple ones", fetch the value of those variables and add them (temporarily) to the _data
# dictionary passed to eval

#FIXME: it wont work if the data hasn't been fetched yet... this could
# happen if the eval node is the first one using this browse_record
# the next line is a workaround for the problem: it causes the resource to be loaded
#Pinky: Why not this ? eval(expr, browser) ?
#       name = browser.name
#       data_dict = browser._data[self.get_value(browser, 'id')]
        return safe_eval(expr, {}, {'obj': record})
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:13,代码来源:print_xml.py


示例14: parse

 def parse(self, cr, uid, o, text, context=None):
     if not text:
         return ''
     vals = text.split('[_')
     description = ''
     for val in vals:
         if '_]' in val:
             sub_val = val.split('_]')
             try:
                 description += (safe_eval(sub_val[0], {'o' :o, 'context':context}) or '' ) + sub_val[1]
             except:
                 LOGGER.notifyChannel('product_variant_multi', netsvc.LOG_ERROR, "%s can't eval. Description is blank" % (sub_val[0]))
                 description += ''
         else:
             description += val
     return description
开发者ID:Arsalan88,项目名称:openerp-extra-6.1,代码行数:16,代码来源:product_variant.py


示例15: _action_calc_formula

    def _action_calc_formula(self, cr, uid, ids, field_names, args, context):
        result = {}.fromkeys(ids, 0)
        for test in self.browse(cr, uid, ids, context):
            vals = {}
            for line in test.test_line_ids:
                if line.name and line.proof_type == 'quantitative':
                    vals[line.name] = line.actual_value_qt

            if not test.formula:
                result[test.id] = 0
                continue

            try:
                value = safe_eval(test.formula, vals)
                result[test.id] = value
            except NameError:
                pass
                #raise osv.except_osv( _('Error:'), msg )
        return result
开发者ID:jeffery9,项目名称:nan_quality_control,代码行数:19,代码来源:quality_control.py


示例16: get_price_from_picking

    def get_price_from_picking(self, cr, uid, id, total, weight, volume, context={}):
        grid = self.browse(cr, uid, id, context)

        price = 0.0
        ok = False

        for line in grid.line_ids:
            price_dict = {'price': total, 'volume':volume, 'weight': weight, 'wv':volume*weight}
            test = safe_eval(line.type+line.operator+str(line.max_value), price_dict)
            if test:
                if line.price_type=='variable':
                    price = line.list_price * price_dict[line.variable_factor]
                else:
                    price = line.list_price
                ok = True
                break
        if not ok:
            raise osv.except_osv(_('No price available !'), _('No line matched this order in the choosed delivery grids !'))

        return price
开发者ID:MarkNorgate,项目名称:addons-EAD,代码行数:20,代码来源:delivery.py


示例17: search

 def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
     if context is None:
         context = {}
     
     # if the user belongs to a portal, we have to rewrite any search on the
     # top menus to be under the portal's parent menu
     if not context.get('ir.ui.menu.full_list') and uid != 1 and \
             args == [('parent_id', '=', False)]:
         portal_obj = self.pool.get('res.portal')
         portal_ids = portal_obj.search(cr, uid, [('users', 'in', uid)])
         if portal_ids:
             if len(portal_ids) > 1:
                 log = logging.getLogger('ir.ui.menu')
                 log.warning('User %s belongs to several portals', str(uid))
             p = portal_obj.browse(cr, uid, portal_ids[0])
             # if the portal overrides the menu, use its domain
             if p.menu_action_id:
                 args = safe_eval(p.menu_action_id.domain)
     
     return super(portal_menu, self).search(cr, uid, args, offset=offset,
                 limit=limit, order=order, context=context, count=count)
开发者ID:goldenboy,项目名称:razvoj,代码行数:21,代码来源:ir_ui_menu.py


示例18: _create_indirect_sharing_rules

 def _create_indirect_sharing_rules(self, cr, current_user, wizard_data, group_id, fields_relations, context=None):
     rule_name = _('Indirect sharing filter created by user %s (%s) for group %s') % \
                         (current_user.name, current_user.login, group_id)
     try:
         domain = safe_eval(wizard_data.domain)
         if domain:
             for rel_field, model in fields_relations:
                 related_domain = []
                 if not rel_field: continue
                 for element in domain:
                     if expression.is_leaf(element):
                         left, operator, right = element
                         left = '%s.%s'%(rel_field, left)
                         element = left, operator, right
                     related_domain.append(element)
                 self._create_or_combine_sharing_rule(cr, current_user, wizard_data,
                      group_id, model_id=model.id, domain=str(related_domain),
                      rule_name=rule_name, restrict=True, context=context)
     except Exception:
         self._logger.exception('Failed to create share access')
         raise osv.except_osv(_('Sharing access could not be created'),
                              _('Sorry, the current screen and filter you are trying to share are not supported at the moment.\nYou may want to try a simpler filter.'))
开发者ID:CloudWareChile,项目名称:OpenChile,代码行数:22,代码来源:share_wizard.py


示例19: extractProperties

    def extractProperties(self):
        # The function will read all relevant information from the jrxml file

        doc = etree.parse(self._reportPath)

        # Define namespaces
        ns = "http://jasperreports.sourceforge.net/jasperreports"
        nss = {"jr": ns}

        # Language

        # Note that if either queryString or language do not exist the default (from the constructor)
        # is XPath.
        langTags = doc.xpath("/jr:jasperReport/jr:queryString", namespaces=nss)
        if langTags:
            if langTags[0].get("language"):
                self._language = langTags[0].get("language").lower()

        # Relations
        relationTags = doc.xpath('/jr:jasperReport/jr:property[@name="OPENERP_RELATIONS"]', namespaces=nss)
        if relationTags and "value" in relationTags[0].keys():
            relation = relationTags[0].get("value").strip()
            if relation.startswith("["):
                self._relations = safe_eval(relationTags[0].get("value"), {})
            else:
                self._relations = [x.strip() for x in relation.split(",")]
            self._relations = [self._pathPrefix + x for x in self._relations]
        if not self._relations and self._pathPrefix:
            self._relations = [self._pathPrefix[:-1]]

        # Repeat field
        copiesFieldTags = doc.xpath('/jr:jasperReport/jr:property[@name="OPENERP_COPIES_FIELD"]', namespaces=nss)
        if copiesFieldTags and "value" in copiesFieldTags[0].keys():
            self._copiesField = self._pathPrefix + copiesFieldTags[0].get("value")

        # Repeat
        copiesTags = doc.xpath('/jr:jasperReport/jr:property[@name="OPENERP_COPIES"]', namespaces=nss)
        if copiesTags and "value" in copiesTags[0].keys():
            self._copies = int(copiesTags[0].get("value"))

        self._isHeader = False
        headerTags = doc.xpath('/jr:jasperReport/jr:property[@name="OPENERP_HEADER"]', namespaces=nss)
        if headerTags and "value" in headerTags[0].keys():
            self._isHeader = True

        fieldTags = doc.xpath("/jr:jasperReport/jr:field", namespaces=nss)
        self._fields, self._fieldNames = self.extractFields(fieldTags, ns)

        # Subreports
        # Here we expect the following structure in the .jrxml file:
        # <subreport>
        #  <dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression>
        #  <subreportExpression class="java.lang.String"><![CDATA[$P{STANDARD_DIR} + "report_header.jasper"]]></subreportExpression>
        # </subreport>
        subreportTags = doc.xpath("//jr:subreport", namespaces=nss)
        for tag in subreportTags:
            dataSourceExpression = tag.findtext("{%s}dataSourceExpression" % ns, "")
            if not dataSourceExpression:
                continue
            dataSourceExpression = dataSourceExpression.strip()
            m = dataSourceExpressionRegExp.match(dataSourceExpression)
            if not m:
                continue
            dataSourceExpression = m.group(1)
            if dataSourceExpression == "REPORT_DATA_SOURCE":
                continue

            subreportExpression = tag.findtext("{%s}subreportExpression" % ns, "")
            if not subreportExpression:
                continue
            subreportExpression = subreportExpression.strip()
            subreportExpression = subreportExpression.replace("$P{STANDARD_DIR}", '"%s"' % self.standardDirectory())
            subreportExpression = subreportExpression.replace("$P{SUBREPORT_DIR}", '"%s"' % self.subreportDirectory())
            try:
                subreportExpression = safe_eval(subreportExpression, {})
            except:
                print "COULD NOT EVALUATE EXPRESSION: '%s'" % subreportExpression
                # If we're not able to evaluate the expression go to next subreport
                continue
            if subreportExpression.endswith(".jasper"):
                subreportExpression = subreportExpression[:-6] + "jrxml"

            # Model
            model = ""
            modelTags = tag.xpath('//jr:reportElement/jr:property[@name="OPENERP_MODEL"]', namespaces=nss)
            if modelTags and "value" in modelTags[0].keys():
                model = modelTags[0].get("value")

            pathPrefix = ""
            pathPrefixTags = tag.xpath('//jr:reportElement/jr:property[@name="OPENERP_PATH_PREFIX"]', namespaces=nss)
            if pathPrefixTags and "value" in pathPrefixTags[0].keys():
                pathPrefix = pathPrefixTags[0].get("value")

            isHeader = False
            headerTags = tag.xpath('//jr:reportElement/jr:property[@name="OPENERP_HEADER"]', namespaces=nss)
            if headerTags and "value" in headerTags[0].keys():
                isHeader = True

            # Add our own pathPrefix to subreport's pathPrefix
            subPrefix = []
#.........这里部分代码省略.........
开发者ID:KDVN,项目名称:odoo-addons,代码行数:101,代码来源:JasperReport.py


示例20: action_number

    def action_number(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        res = super(account_invoice, self).action_number(cr, uid, ids, context)
        if res:
            _invoice_ids = self.search(cr, uid, [('id','in',ids)], context)
            if len(_invoice_ids) > 0:
                ctx = {}
                _costs_installed = self.pool.get('stock.picking.in').fields_get(cr, uid, ['landing_costs_line_ids'], context) != {}
                _picking_ids = []
                for _invoice in self.browse(cr, uid, _invoice_ids, context):
                    _src_usage = False
                    _dst_usage = False
                    
                    if _invoice.type == 'in_invoice':
                        _src_usage = 'supplier'
                        _dst_usage = 'internal'
                    elif _invoice.type == 'in_refund':
                        _src_usage = 'internal'
                        _dst_usage = 'supplier'
                    elif _invoice.type == 'out_invoice':
                        _src_usage = 'internal'
                        _dst_usage = 'customer'
                    elif _invoice.type == 'out_refund':
                        _src_usage = 'customer'
                        _dst_usage = 'internal'

                    if not _src_usage and not _dst_usage:
                        continue

                    for _line in _invoice.invoice_line:
                        _quantity = 0.0
                        _uom_id = False
                        
                        _order_line_ids = []
                        _stock_move_ids = []
                        if _src_usage == 'supplier' or _dst_usage == 'supplier':
                            _order_line_ids = self.pool.get('purchase.order.line').search(cr, uid, [('invoice_lines','=',_line.id)])                        
                            _stock_move_ids = self.pool.get('stock.move').search(cr, uid, [('purchase_line_id','in',_order_line_ids),
                                                                                           ('state','=','done'),
                                                                                           ('location_id.usage','=',_src_usage),
                                                                                           ('location_dest_id.usage','=',_dst_usage)])
                        else:
                            _order_line_ids = self.pool.get('sale.order.line').search(cr, uid, [('invoice_lines','=',_line.id)])                        
                            _stock_move_ids = self.pool.get('stock.move').search(cr, uid, [('sale_line_id','in',_order_line_ids),
                                                                                           ('state','=','done'),
                                                                                           ('location_id.usage','=',_src_usage),
                                                                                           ('location_dest_id.usage','=',_dst_usage)])

                        if len(_stock_move_ids) > 0:
                            _stock_moves = self.pool.get('stock.move').browse(cr, uid, _stock_move_ids, context)
                            if safe_eval(self.pool.get('ir.config_parameter').get_param(cr, uid, 'account.check_quantity_on_invoices', 'False')):
                                for _stock_move in _stock_moves:
                                    _quantity = _quantity + _stock_move.product_qty
                                    _uom_id = _stock_move.product_uom.id

                                if _line.uos_id.id == _uom_id and _quantity != _line.quantity:
                                    _text = _line.invoice_id.origin + ' - ' + _line.name
                                    raise osv.except_osv(_('Error!'), _('Invoiced quantity is different than received quantity.\n' + _text))
                            
                            if _line.uos_id.id == _uom_id and (_src_usage == 'supplier' or _dst_usage == 'supplier'):
                                for _stock_move in _stock_moves:
                                    _updated = False
                                    if _costs_installed:
                                        _has_costs = len(_stock_move.landing_costs_line_ids) <> 0 or len(_stock_move.picking_id.landing_costs_line_ids) <> 0
                                        if (_has_costs and _stock_move.price_unit_without_costs != _line.price_unit) \
                                            or (not _has_costs and _stock_move.price_unit != _line.price_unit):
                                            ctx['move%s' % (_stock_move.id)] = {'price_unit': _line.price_unit,
                                                                                'price_unit_without_costs': False,
                                                                                'quantity': False}
                                            _updated = True
                                    else:
                                        if _stock_move.price_unit != _line.price_unit:
                                            ctx['move%s' % (_stock_move.id)] = {'price_unit': _line.price_unit,
                                                                                'quantity': False}
                                            _updated = True
                                    if _updated:
                                        _picking_ids.append(_stock_move.picking_id.id)
                    if _picking_ids:
                        self.pool.get('stock.picking')._picking_update(cr, uid, _picking_ids, ctx)
        return res
开发者ID:OpenBusinessSolutions,项目名称:odoo-karina,代码行数:82,代码来源:account_invoice.py



注:本文中的tools.safe_eval.safe_eval函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sql.drop_view_if_exists函数代码示例发布时间:2022-05-27
下一篇:
Python safe_eval.eval函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap