def _customize_view(self, res, view_type):
     profile_group = self.env.ref('product_profile.group_product_profile')
     users_in_profile_group = [user.id for user in profile_group.users]
     if view_type == 'form':
         doc = etree.XML(res['arch'])
         fields = self._get_profile_fields()
         fields_def = self.fields_get(allfields=fields)
         if self.env.uid not in users_in_profile_group:
             attrs = {'invisible': [('profile_id', '!=', False)]}
         else:
             attrs = {'readonly': [('profile_id', '!=', False)]}
         paths = ["//field[@name='%s']",
                  "//label[@for='%s']"]
         for field in fields:
             for path in paths:
                 node = doc.xpath(path % field)
                 if node:
                     for current_node in node:
                         current_node.set('attrs', str(attrs))
                         orm.setup_modifiers(current_node,
                                             fields_def[field])
         res['arch'] = etree.tostring(doc, pretty_print=True)
     elif view_type == 'search':
         # Allow to dynamically create search filters for each profile
         filters_to_create = self._get_profiles_to_filter()
         doc = etree.XML(res['arch'])
         node = doc.xpath("//filter[1]")
         if not node:
             return res
         for my_filter in filters_to_create:
             elm = etree.Element(
                 'filter', **self._customize_profile_filters(my_filter))
             node[0].addprevious(elm)
         res['arch'] = etree.tostring(doc, pretty_print=True)
     return res
 def _build_attribute_field(self, cr, uid, page, attribute, context=None):
     parent = etree.SubElement(page, 'group', colspan="2", col="4")
     kwargs = {'name': "%s" % attribute.name}
     #conflict with change field type in web .
     #if attribute.ttype in ['many2many', 'text']:
     print attribute.attribute_id.name, attribute.attribute_id.attribute_type
     if attribute.attribute_id.attribute_type in ['many2many', 'text']:
         print "%s: %s"%(attribute.name, attribute.ttype)
         parent = etree.SubElement(parent, 'group', colspan="2", col="4")
         sep = etree.SubElement(parent,
                                'separator',
                                 string="%s" % attribute.field_description,
                                 colspan="4")  
     
         kwargs['nolabel'] = "1"
         print kwargs
     if attribute.ttype in ['many2one', 'many2many']:
         if attribute.relation_model_id:
             if attribute.domain:
                 kwargs['domain'] = attribute.domain
             else:
                 ids = [op.value_ref.id for op in attribute.option_ids]
                 kwargs['domain'] = "[('id', 'in', %s)]" % ids
         else:
             kwargs['domain'] = "[('attribute_id', '=', %s)]" % attribute.attribute_id.id
     field = etree.SubElement(parent, 'field', **kwargs)
     orm.setup_modifiers(field, self.fields_get(cr, uid, attribute.name, context))
     return parent
Пример #3
0
 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
     res = super(base_report_params, self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
     if res.get('type') != 'form':
         return res
     if context.get('cubicReport'):
         report = self.pool.get('ir.actions.report.xml').browse(cr, user, context['cubicReport'].get('id'), context=context)
         params = eval(report.custom_params_src)
         doc = etree.XML(res['arch'])
         group = doc.xpath("//group")[0]
         for p in params:
             node = etree.Element('field', {'name':p['name'], 'required':p.get('required','0'),
                                            'invisible':p.get('invisible','0'), 'attrs':p.get('attrs','{}')})
             group.append(node)
             res['fields'][p['name']] = {'selectable': True, 'views': {}, 'type': p.get('type','char'), 
                                         'string': p.get('string',p['name'])}
             if p.get('type') == 'selection':
                 res['fields'][p['name']]['selection'] = p.get('args')[0]
             elif p.get('type') == 'many2one':
                 res['fields'][p['name']]['relation'] = p.get('args')[0]
             elif p.get('type') == 'one2many':
                 res['fields'][p['name']]['relation'] = p.get('args')[0]
                 res['fields'][p['name']]['relation_field'] = p.get('args')[1]
                 
             if p.has_key('help'):
                 res['fields'][p['name']]['help'] = p.get('help')
             setup_modifiers(node, res['fields'][p['name']])
         res['arch'] = etree.tostring(doc)
     return res
 def fields_view_get(self, cr, uid, view_id=None, view_type='form',
                     context=None, toolbar=False, submenu=False):
     res = super(account_move_line, self).fields_view_get(
         cr, uid, view_id=view_id, view_type=view_type,
         context=context, toolbar=toolbar, submenu=submenu)
     if view_type == 'tree':
         aml_tree = etree.XML(res['arch'])
         pos = 0
         credit_pos = False
         done = False
         for el in aml_tree:
             pos += 1
             if el.tag == 'field':
                 if el.get('name') == 'credit':
                     credit_pos = pos
         if not done and credit_pos:
             absolute_balance_node = etree.Element(
                 'field', name='absolute_balance')
             aml_tree.insert(credit_pos, absolute_balance_node)
             absolute_balance_dict = self.fields_get(
                 cr, uid, ['absolute_balance'], context=context
                 )['absolute_balance']
             orm.setup_modifiers(
                 absolute_balance_node, absolute_balance_dict,
                 context=context, in_tree_view=True)
             res['fields']['absolute_balance'] = absolute_balance_dict
             done = True
         if done:
             res['arch'] = etree.tostring(aml_tree, pretty_print=True)
         # _logger.warn('arch=%s', res['arch'])
         # _logger.warn('fields=%s', res['fields'])
     return res
Пример #5
0
def _build_attribute_field(self, cr, uid, page, attribute, context=None):
    parent = etree.SubElement(page, 'group', colspan="2", col="4")
    kwargs = {'name': "%s" % attribute.name}
#    if attribute.ttype in ['many2many', 'text']:
    #only the many2many without many2many_tags then need display 'separator', by johnw 04/30/2014
    if (attribute.ttype == 'many2many' and not attribute.m2m_tags) or attribute.ttype == 'text':
        parent = etree.SubElement(parent, 'group', colspan="2", col="4")
        sep = etree.SubElement(parent,
                               'separator',
                                string="%s" % attribute.field_description,
                                colspan="4")

        kwargs['nolabel'] = "1"
    if attribute.ttype in ['many2one', 'many2many']:
        if attribute.relation_model_id:
            if attribute.domain:
                kwargs['domain'] = attribute.domain
            else:
                ids = [op.value_ref.id for op in attribute.option_ids]
                kwargs['domain'] = "[('id', 'in', %s)]" % ids
        else:
            kwargs['domain'] = "[('attribute_id', '=', %s)]" % attribute.attribute_id.id
    #set the 'many2many_tags' widget for the multiselect attribute, by johnw 04/30/2014
    if attribute.ttype == 'many2many' and attribute.m2m_tags:
        kwargs['widget'] = "many2many_tags"
    #Add the field's description as the field label
#    field = etree.SubElement(parent, 'field', **kwargs)    
    field = etree.SubElement(parent, 'field', string="%s" % attribute.field_description, **kwargs)
    orm.setup_modifiers(field, self.fields_get(cr, uid, attribute.name, context))
    return parent 
 def _build_attribute_field(self, cr, uid, page, attribute, context=None):
     parent = etree.SubElement(page, 'group', colspan="2", col="4")
     kwargs = {'name': "%s" % attribute.name}
     if attribute.ttype in ['many2many', 'text']:
         parent = etree.SubElement(parent, 'group', colspan="2", col="4")
         etree.SubElement(parent,
                                'separator',
                                 string="%s" % attribute.field_description,
                                 colspan="4")
         kwargs['nolabel'] = "1"
     if attribute.ttype in ['many2one', 'many2many']:
         if attribute.relation_model_id:
             # attribute.domain is a string, it may be an empty list
             try:
                 domain = ast.literal_eval(attribute.domain)
             except ValueError:
                 domain = None
             if domain:
                 kwargs['domain'] = attribute.domain
             else:
                 ids = [op.value_ref.id for op in attribute.option_ids]
                 kwargs['domain'] = "[('id', 'in', %s)]" % ids
         else:
             kwargs['domain'] = "[('attribute_id', '=', %s)]" % attribute.attribute_id.id
     kwargs['context'] = "{'default_attribute_id': %s}" % attribute.attribute_id.id
     kwargs['required'] = str(attribute.required or
                              attribute.required_on_views)
     field = etree.SubElement(parent, 'field', **kwargs)
     orm.setup_modifiers(field, self.fields_get(cr, uid, attribute.name,
                                                context))
     return parent
Пример #7
0
 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
     """
     Override the original field view get in order to insert dynamically the various fields need
     for the configuration of the referential
     """
     # use lxml to compose the arch XML
     result = super(external_referential, self).fields_view_get(cr, uid,
                                                                 view_id=view_id,
                                                                 view_type=view_type,
                                                                 context=context,
                                                                 toolbar=toolbar,
                                                                 submenu=submenu,
                                                             )
     if view_type == 'form':
         eview = etree.fromstring(result['arch'])
         toupdate_fields = []
         for field_name in REF_FIELDS:
             field = eview.xpath("//field[@name='%s']"%field_name)
             if field:
                 field = field[0]
                 referentials = []
                 for ref_type, visible_fields in REF_VISIBLE_FIELDS.items():
                     if field_name in visible_fields:
                         referentials.append(ref_type)
                 field.set('attrs', """{
                                 'invisible': [('type_name', 'not in', %s)],
                                 'required': [('type_name', 'in', %s)]
                                     }"""%(referentials, referentials))
                 orm.setup_modifiers(field, field=result['fields'][field_name], context=context)
                 result['arch'] = etree.tostring(eview, pretty_print=True)
     return result
 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
     res=super(employee_dashboard,self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
     corporate_ids = self.pool.get('attendance.attendance')._get_user_ids_group(cr,uid,'pls','telecom_corporate')
     if uid not in corporate_ids:
         doc = etree.XML(res['arch'])
         for node in doc.xpath("//field[@name='project_ids']"):
             node.set('domain',"[('project_manager.user_id','in',[uid])]")
             setup_modifiers(node, res['fields']['project_ids'])
             res['arch'] = etree.tostring(doc)
     return res
Пример #9
0
 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
     res=super(attendance_attendance,self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
     if view_type =="form":
         user_ids=self._get_user_ids_group(cr,SUPERUSER_ID,'pls','telecom_corporate')      
         if not(uid in user_ids):
             doc = etree.XML(res['arch'])
             for node in doc.xpath("//field[@name='date']"):
                 node.set('readonly','1')
                 setup_modifiers(node, res['fields']['date'])
                 res['arch'] = etree.tostring(doc)
     return res
Пример #10
0
 def render(self):
     # We allow the caller to supply "attrs" directly with a dict instead of a string repr of a
     # dict. It's more elegant this way and allows us easier inspection. But we have to convert
     # it to string before passing it out to lxml. 
     attrs = self.attrs
     if 'attrs' in self.attrs:
         attrs = attrs.copy()
         attrs['attrs'] = unicode(attrs['attrs'])
     node = E.field(name=self.name, **attrs)
     setup_modifiers(node)
     return node
Пример #11
0
 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
     if context is None:context = {}
     res = super(account_common_report, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
     if context.get('active_model', False) == 'account.account':
         doc = etree.XML(res['arch'])
         nodes = doc.xpath("//field[@name='chart_account_id']")
         for node in nodes:
             node.set('readonly', '1')
             node.set('help', 'If you print the report from Account list/form view it will not consider Charts of account')
             setup_modifiers(node, res['fields']['chart_account_id'])
         res['arch'] = etree.tostring(doc)
     return res
    def fields_view_get(self, cr, user, view_id=None, view_type='form',
                        context=None, toolbar=False, submenu=False):
        res = super(EndContractWizard, self).fields_view_get(
            cr, user, view_id, view_type, context, toolbar, submenu)
        # If there is no child in contract, hide field
        if view_type == 'form' and not self._get_child_id(cr, user, context):
            doc = etree.XML(res['arch'])
            for node in doc.xpath("//field[@name='child_id']"):
                node.set('invisible', "1")
                orm.setup_modifiers(node, res['fields']['child_id'])
            res['arch'] = etree.tostring(doc)

        return res
Пример #13
0
 def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
     result = super(AccountInvoice, self).fields_view_get(view_id, view_type, toolbar=toolbar, submenu=submenu)
     doc = etree.XML(result['arch'])
     dimensions = [(x.code, x.name) for x in
                   self.env['account.dimension'].search([])]
     for d in dimensions:
         nodes = doc.xpath("//field[@name='%s']" % d[0])
         if nodes:
             node = nodes[0]
             node.set('string', d[1])
             setup_modifiers(node, result['fields'][d[0]])
     result['arch'] = etree.tostring(doc)
     return result
Пример #14
0
 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
     if context is None:
         context = {}
     res = super(stock_location_product, self).fields_view_get(cr, user, view_id, view_type, context, toolbar,
                                                               submenu)
     if context.get('active_id', False):
         arch = res['arch']
         doc = etree.XML(res['arch'])
         nodes = doc.xpath("//field[@name='location_id']")
         for node in nodes:
             node.set('invisible', 'True')
             node.set('required', 'False')
             setup_modifiers(node, res['fields']['location_id'])
         res['arch'] = etree.tostring(doc)
     return res
 def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
     result = super(AssetModify, self).fields_view_get(view_id, view_type, toolbar=toolbar, submenu=submenu)
     asset_id = self.env.context.get('active_id')
     active_model = self.env.context.get('active_model')
     if active_model == 'account.asset.asset' and asset_id:
         asset = self.env['account.asset.asset'].browse(asset_id)
         doc = etree.XML(result['arch'])
         if asset.method_time == 'number' and doc.xpath("//field[@name='method_end']"):
             node = doc.xpath("//field[@name='method_end']")[0]
             node.set('invisible', '1')
             setup_modifiers(node, result['fields']['method_end'])
         elif asset.method_time == 'end' and doc.xpath("//field[@name='method_number']"):
             node = doc.xpath("//field[@name='method_number']")[0]
             node.set('invisible', '1')
             setup_modifiers(node, result['fields']['method_number'])
         result['arch'] = etree.tostring(doc)
     return result
	def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
		
		res = super(doctor_co_attentios, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
		doc = etree.XML(res['arch'])
		seleccionado = False
		for node in doc.xpath("//field[@name='remite_aux_enfermeria']"):

			modelo_buscar = self.pool.get('doctor.nursing.configuracion')
			record = modelo_buscar.search(cr, uid, [('name', '=', True)], context=context)
			if record:
				for datos in modelo_buscar.browse(cr, uid, record, context=context):
					seleccionado = datos.name
				node.set('invisible', repr(seleccionado))
				setup_modifiers(node, res['fields']['remite_aux_enfermeria'])
		
		res['arch'] = etree.tostring(doc)
				
		return res
 def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
     res = super(stock_picking_update_line, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type,
                                                                  context=context, toolbar=toolbar, submenu=submenu)
     _picking_id = context and context.get('picking_id', False)
     if _picking_id:
         _invisible = '0'
         _picking = self.pool.get('stock.picking').browse(cr, uid, _picking_id, None)
         for _move in _picking.move_lines:
             if _move.location_id.usage != 'supplier' and _move.location_dest_id.usage != 'supplier':
                 _invisible = '1'
         doc = etree.XML(res['arch'])
         for node in doc.xpath("//field[@name='price_unit']"):
             node.set('invisible', _invisible)
             setup_modifiers(node, res['fields']['price_unit'], None, True)
         for node in doc.xpath("//field[@name='price_unit_new']"):
             node.set('invisible', _invisible)
             setup_modifiers(node, res['fields']['price_unit_new'], None, True)
         res['arch'] = etree.tostring(doc)    
     return res
Пример #18
0
 def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
     res = super(edi_choose_m2o, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
     if view_type == 'form':
         doc = etree.XML(res['arch'])
         context = self.env.context
         group = doc.xpath("//group[@name='fields']")
         if group:
             f_display = {'string': _('Value'), 
                          'name': 'value', 
                          'required': '1', 
                          'type': 'many2one', 
                          'selectable': '1', 
                          'relation': context.get('edi_comodel_name'), 
                          'comodel_name': context.get('edi_comodel_name')}
             f = etree.Element('field', f_display)
             res['fields']['value'] = f_display
             group[0].append(f)
             setup_modifiers(f, f_display)
             res['arch'] = etree.tostring(doc)
             
     return res
Пример #19
0
    def fields_view_get(self,
                        cr,
                        uid,
                        view_id=None,
                        view_type='form',
                        context=None,
                        toolbar=False,
                        submenu=False):
        if context is None:
            context = {}

        res = super(ResUsers, self).fields_view_get(cr,
                                                    uid,
                                                    view_id=view_id,
                                                    view_type=view_type,
                                                    context=context,
                                                    toolbar=toolbar,
                                                    submenu=submenu)

        model_data_obj = self.pool['ir.model.data']
        admin_settings_id = model_data_obj.xmlid_to_res_id(
            cr, openerp.SUPERUSER_ID, 'base.group_system')
        admin_settings_fname = name_boolean_group(admin_settings_id)

        admin_access_rights_id = model_data_obj.xmlid_to_res_id(
            cr, openerp.SUPERUSER_ID, 'base.group_erp_manager')
        admin_rights_fname = name_boolean_group(admin_access_rights_id)

        # Hide some admin rights field to avoid granting these groups to user
        admin_fields = (admin_settings_fname, admin_rights_fname)
        doc = etree.fromstring(res['arch'])
        if view_type == 'form':
            for node in doc.xpath("//field"):
                node_name = node.get('name')
                if node.get('name') in admin_fields:
                    node.set('invisible', '1')
                setup_modifiers(node)
        res['arch'] = etree.tostring(doc)

        return res
 def fields_view_get(self,
                     view_id=None,
                     view_type=False,
                     toolbar=False,
                     submenu=False):
     Expense = self.env['hr.expense.expense']
     expense = Expense.browse(self._context.get('active_id'))
     no_multi_supplier = (expense.pay_to != 'supplier'
                          or len(expense.line_ids) != 1
                          or expense.is_employee_advance
                          or expense.is_advance_clearing) or False
     result = super(ExpenseCreateSupplierInvoice, self).\
         fields_view_get(view_id=view_id, view_type=view_type,
                         toolbar=toolbar, submenu=submenu)
     if no_multi_supplier:
         doc = etree.XML(result['arch'])
         nodes = doc.xpath("//field[@name='use_attendee_list']")
         for node in nodes:
             node.set('invisible', '1')
             setup_modifiers(node, result['fields'][node.attrib['name']])
         result['arch'] = etree.tostring(doc)
     return result
Пример #21
0
 def fields_view_get(
         self, cr, uid, view_id=None, view_type='form', context=None,
         toolbar=False, submenu=False):
     """Set 'fiscal_classification_id' as required by fields_view_get:
     We don't set it by fields declaration in python file, to avoid
     incompatibility with other modules that could have demo data
     without fiscal_classification_id (the bugs will occur depending
     of the order in which the modules are loaded);
     We don't set it by view inheritance in xml file to impact all views
     (form / tree) that could define the model 'product.template';"""
     res = super(ProductTemplate, self).fields_view_get(
         cr, uid, view_id=view_id, view_type=view_type, context=context,
         toolbar=toolbar, submenu=submenu)
     if view_type == 'form':
         doc = etree.XML(res['arch'])
         nodes = doc.xpath("//field[@name='fiscal_classification_id']")
         if nodes:
             nodes[0].set('required', '1')
             setup_modifiers(
                 nodes[0], res['fields']['fiscal_classification_id'])
             res['arch'] = etree.tostring(doc)
     return res
Пример #22
0
    def add_qty_fields(self, wiz, xml_view, fields):
        """Add quantity fields to view after each dynamic field"""
        attr_qty_prefix = self._prefixes.get('attr_qty_prefix')
        field_prefix = self._prefixes.get('field_prefix')
        qty_fields = [f for f in fields if f.startswith(attr_qty_prefix)]
        for qty_field in qty_fields:
            # If the matching attribute field is found in the view add after
            attr_id = int(qty_field.replace(attr_qty_prefix, ''))
            dynamic_field_name = field_prefix + str(attr_id)
            dynamic_field = xml_view.xpath(
                "//field[@name='%s']" % dynamic_field_name)
            if not dynamic_field:
                continue

            active_step = wiz.get_active_step()

            available_attr_ids = active_step.attribute_line_ids.mapped(
                'attribute_id').ids

            if attr_id not in available_attr_ids:
                continue

            qty_field = etree.Element(
                'field',
                name=qty_field,
                attrs=str({
                    'invisible': [
                        '|',
                        (dynamic_field_name, '=', False)],

                })
            )
            orm.setup_modifiers(qty_field)
            dynamic_form = dynamic_field[0].getparent()
            dynamic_form.insert(
                dynamic_form.index(dynamic_field[0]) + 1, qty_field
            )
        return xml_view
Пример #23
0
def _build_attribute_field(self, cr, uid, page, attribute, context=None):
    parent = etree.SubElement(page, 'group', colspan="2", col="4")
    kwargs = {'name': "%s" % attribute.name}
    #    if attribute.ttype in ['many2many', 'text']:
    #only the many2many without many2many_tags then need display 'separator', by johnw 04/30/2014
    if (attribute.ttype == 'many2many'
            and not attribute.m2m_tags) or attribute.ttype == 'text':
        parent = etree.SubElement(parent, 'group', colspan="2", col="4")
        sep = etree.SubElement(parent,
                               'separator',
                               string="%s" % attribute.field_description,
                               colspan="4")

        kwargs['nolabel'] = "1"
    if attribute.ttype in ['many2one', 'many2many']:
        if attribute.relation_model_id:
            if attribute.domain:
                kwargs['domain'] = attribute.domain
            else:
                ids = [op.value_ref.id for op in attribute.option_ids]
                kwargs['domain'] = "[('id', 'in', %s)]" % ids
        else:
            kwargs[
                'domain'] = "[('attribute_id', '=', %s)]" % attribute.attribute_id.id
    #set the 'many2many_tags' widget for the multiselect attribute, by johnw 04/30/2014
    if attribute.ttype == 'many2many' and attribute.m2m_tags:
        kwargs['widget'] = "many2many_tags"
    #Add the field's description as the field label


#    field = etree.SubElement(parent, 'field', **kwargs)
    field = etree.SubElement(parent,
                             'field',
                             string="%s" % attribute.field_description,
                             **kwargs)
    orm.setup_modifiers(field, self.fields_get(cr, uid, attribute.name,
                                               context))
    return parent
    def _build_attribute_field(self, cr, uid, page, attribute, context=None):
        parent = etree.SubElement(page, 'group', colspan="2", col="4")
        kwargs = {'name': "%s" % attribute.name}
        if attribute.ttype in ['many2many', 'text']:
            parent = etree.SubElement(parent, 'group', colspan="2", col="4")
            sep = etree.SubElement(parent,
                                   'separator',
                                    string="%s" % attribute.field_description,
                                    colspan="4")

            kwargs['nolabel'] = "1"
        if attribute.ttype in ['many2one', 'many2many']:
            if attribute.relation_model_id:
                if attribute.domain:
                    kwargs['domain'] = attribute.domain
                else:
                    ids = [op.value_ref.id for op in attribute.option_ids]
                    kwargs['domain'] = "[('id', 'in', %s)]" % ids
            else:
                kwargs['domain'] = "[('attribute_id', '=', %s)]" % attribute.attribute_id.id
        field = etree.SubElement(parent, 'field', **kwargs)
        orm.setup_modifiers(field, self.fields_get(cr, uid, attribute.name, context))
        return parent
Пример #25
0
 def fields_view_get(self,
                     view_id=None,
                     view_type=False,
                     toolbar=False,
                     submenu=False):
     res = super(HrEquipmentRequest,
                 self).fields_view_get(view_id=view_id,
                                       view_type=view_type,
                                       toolbar=toolbar,
                                       submenu=submenu)
     if not self.env['res.users'].has_group('base.group_hr_manager'):
         if view_type in {'tree', 'form'}:
             doc = etree.XML(res['arch'])
             if res['type'] == 'form':
                 nodes = doc.xpath("//field")
                 for node in nodes:
                     node.set(
                         'attrs',
                         "{'readonly': [('state', 'in', ['purchased', 'cancel'])]}"
                     )
                     setup_modifiers(node, None)
             res['arch'] = etree.tostring(doc)
     return res
Пример #26
0
    def fields_view_get(self,
                        view_id=None,
                        view_type=False,
                        toolbar=False,
                        submenu=False):
        context = self._context

        res = super(account_invoice, self).fields_view_get(view_id=view_id,
                                                           view_type=view_type,
                                                           toolbar=toolbar,
                                                           submenu=submenu)

        if view_type == 'tree':
            doc = etree.XML(res['arch'])
            if context.get('type') in ('out_invoice', 'out_refund'):
                for node in doc.xpath("//field[@name='invoice_per_email']"):
                    node.set('invisible', '0')
                    setup_modifiers(node,
                                    context=self._context,
                                    in_tree_view=True)  #

            res['arch'] = etree.tostring(doc)

        return res
Пример #27
0
    def fields_view_get(self,
                        cr,
                        uid,
                        view_id=None,
                        view_type='form',
                        context=None,
                        toolbar=False,
                        submenu=False):
        if context is None:
            context = {}

        res = super(AccountInvoice, self).fields_view_get(cr,
                                                          uid,
                                                          view_id=view_id,
                                                          view_type=view_type,
                                                          context=context,
                                                          toolbar=toolbar,
                                                          submenu=submenu)

        # Read only field contact base specific groups
        account_advise = self.user_has_groups(cr, uid,
                                              'account.group_account_manager')
        doc = etree.fromstring(res['arch'])
        if not account_advise:
            if view_type == 'form':
                list_readonly_field = [
                    'journal_id', 'account_id', 'user_id', 'payment_term_id',
                    'fiscal_position_id', 'move_id', 'date', 'company_id'
                ]
                for node in doc.xpath("//field"):
                    if node.get('name') in list_readonly_field:
                        node.set('readonly', '1')
                        setup_modifiers(node)
            res['arch'] = etree.tostring(doc)

        return res
    def fields_view_get(self,
                        cr,
                        uid,
                        view_id=None,
                        view_type='form',
                        context=None,
                        toolbar=False,
                        submenu=False):

        user = self.pool.get('res.users').browse(cr, uid, uid)

        if context is None:
            context = {}
        res = super(purchase_order, self).fields_view_get(cr,
                                                          uid,
                                                          view_id=view_id,
                                                          view_type=view_type,
                                                          context=context,
                                                          toolbar=toolbar,
                                                          submenu=False)
        doc = etree.XML(res['arch'])

        cr.execute("""select uid from res_groups_users_rel where gid in
                      (select id  from res_groups where category_id in 
                      ( select id from ir_module_category where name = 'Supplier Portal' ) ) and uid = """
                   + str(uid))
        sup_portal = cr.fetchone()
        if sup_portal:
            if view_type == 'form':
                for node in doc.xpath("//field[@name='partner_id']"):
                    node.set('options', '{"no_open":True}')
                    node.set('readonly', '1')
                    setup_modifiers(node, res['fields']['partner_id'])
                    res['arch'] = etree.tostring(doc)

        return res
Пример #29
0
    def fields_view_get(self,
                        view_id=None,
                        view_type=False,
                        toolbar=False,
                        submenu=False):
        """
        If we came from sale order, we send in context 'force_product_edit'
        and we change tree view to make editable and also field qty
        """
        res = super(product_product, self).fields_view_get(view_id=view_id,
                                                           view_type=view_type,
                                                           toolbar=toolbar,
                                                           submenu=submenu)
        force_product_edit = self._context.get('force_product_edit')
        if force_product_edit:
            doc = etree.XML(res['arch'])
            for node in doc.xpath("/tree"):
                node.set('edit', 'true')
            for node in doc.xpath("//field[@name='qty']"):
                node.set('readonly', '0')
                setup_modifiers(node, res['fields']['qty'])
            res['arch'] = etree.tostring(doc)

        return res
Пример #30
0
 def fields_view_get(self,
                     cr,
                     uid,
                     view_id=None,
                     view_type='form',
                     context=None,
                     toolbar=False,
                     submenu=False):
     res = super(trobz_crm_event, self).fields_view_get(cr,
                                                        uid,
                                                        view_id=view_id,
                                                        view_type=view_type,
                                                        context=context,
                                                        toolbar=toolbar,
                                                        submenu=submenu)
     if view_type in {'tree', 'form'}:
         doc = etree.XML(res['arch'])
         if context.get('hide_lead_id', False) and res['type'] == 'form':
             nodes = doc.xpath("//field[@name='lead_id']")
             for node in nodes:
                 node.set('invisible', '1')
                 setup_modifiers(node, None)
         res['arch'] = etree.tostring(doc)
     return res
Пример #31
0
 def _customize_view(self, res, view_type):
     profile_group = self.env.ref('product_profile.group_product_profile')
     users_in_profile_group = [user.id for user in profile_group.users]
     default_fields = self._get_default_profile_fields()
     if view_type == 'form':
         doc = etree.XML(res['arch'])
         fields = self._get_profile_fields()
         fields_def = self.fields_get(allfields=fields)
         if self.env.uid not in users_in_profile_group:
             attrs = {'invisible': [('profile_id', '!=', False)]}
         else:
             attrs = {'readonly': [('profile_id', '!=', False)]}
         paths = ["//field[@name='%s']", "//label[@for='%s']"]
         for field in fields:
             if field not in default_fields:
                 # default fields shouldn't be modified
                 for path in paths:
                     node = doc.xpath(path % field)
                     if node:
                         for current_node in node:
                             current_node.set('attrs', str(attrs))
                             orm.setup_modifiers(current_node,
                                                 fields_def[field])
         res['arch'] = etree.tostring(doc, pretty_print=True)
     elif view_type == 'search':
         # Allow to dynamically create search filters for each profile
         filters_to_create = self._get_profiles_to_filter()
         doc = etree.XML(res['arch'])
         node = doc.xpath("//filter[1]")
         if node:
             for my_filter in filters_to_create:
                 elm = etree.Element(
                     'filter', **self._customize_profile_filters(my_filter))
                 node[0].addprevious(elm)
             res['arch'] = etree.tostring(doc, pretty_print=True)
     return res
    def fields_view_get(self,
                        cr,
                        uid,
                        view_id=None,
                        view_type='form',
                        context=None,
                        toolbar=False,
                        submenu=False):

        if context is None:
            context = {}
        res = super(account_invoice, self).fields_view_get(cr,
                                                           uid,
                                                           view_id=view_id,
                                                           view_type=view_type,
                                                           context=context,
                                                           toolbar=toolbar,
                                                           submenu=False)
        doc = etree.XML(res['arch'])
        cr.execute("""select uid from res_groups_users_rel where gid=
          (select id  from res_groups where category_id in 
          ( select id from ir_module_category where name = 'Customer Portal' ) and name = 'Manager') and uid = """
                   + str(uid))
        portal_user = cr.fetchone()
        portal_group = portal_user and portal_user[0]

        if uid == portal_group:
            for node in doc.xpath("//field[@name='partner_id']"):
                node.set('options', "{'no_open' : true}")
                setup_modifiers(node, res['fields']['partner_id'])
                res['arch'] = etree.tostring(doc)

            for node in doc.xpath("//field[@name='contact_id']"):
                node.set('options', "{'no_open' : true}")
                setup_modifiers(node, res['fields']['contact_id'])
                res['arch'] = etree.tostring(doc)

        cr.execute("""select uid from res_groups_users_rel where gid=
          (select id  from res_groups where category_id in 
          ( select id from ir_module_category where name = 'Supplier Portal' ) ) and uid = """
                   + str(uid))
        sup_portal = cr.fetchone()
        supportal_group = sup_portal and sup_portal[0]

        if uid == supportal_group:
            for node in doc.xpath("//field[@name='partner_id']"):
                node.set('options', "{'no_open' : true}")
                setup_modifiers(node, res['fields']['partner_id'])
                res['arch'] = etree.tostring(doc)
        return res
Пример #33
0
    def fields_view_get(self,
                        view_id=None,
                        view_type='form',
                        toolbar=False,
                        submenu=False):
        """
        If we came from invoice, we send in context 'force_line_edit'
        and we change tree view to make editable and also field qty
        """
        res = super(PurchaseOrderLine,
                    self).fields_view_get(view_id=view_id,
                                          view_type=view_type,
                                          toolbar=toolbar,
                                          submenu=submenu)
        force_line_edit = self._context.get('force_line_edit')
        if force_line_edit and view_type == 'tree':
            doc = etree.XML(res['arch'])
            # add to invoice qty field (before setupmodifis because if not
            # it remains editable)
            placeholder = doc.xpath("//field[1]")[0]
            placeholder.addprevious(
                etree.Element('field', {
                    'name': 'qty_to_invoice',
                    'readonly': '1',
                }))

            # make all fields not editable
            for node in doc.xpath("//field"):
                node.set('readonly', '1')
                setup_modifiers(node, res['fields'], in_tree_view=True)

            # add qty field
            placeholder.addprevious(
                etree.Element(
                    'field',
                    {
                        'name': 'invoice_qty',
                        # we force editable no matter user rights
                        'readonly': '0',
                    }))
            res['fields'].update(
                self.fields_get(['invoice_qty', 'qty_to_invoice']))

            # add button to add all
            placeholder.addprevious(
                etree.Element(
                    'button', {
                        'name': 'action_add_all_to_invoice',
                        'type': 'object',
                        'icon': 'fa-plus-square',
                        'string': _('Add all to invoice'),
                    }))

            # add button tu open form
            placeholder = doc.xpath("//tree")[0]
            placeholder.append(
                etree.Element(
                    'button', {
                        'name': 'action_line_form',
                        'type': 'object',
                        'icon': 'fa-external-link',
                        'string': _('Open Purchase Line Form View'),
                    }))

            # make tree view editable
            for node in doc.xpath("/tree"):
                node.set('edit', 'true')
                node.set('create', 'false')
                node.set('editable', 'top')
            res['arch'] = etree.tostring(doc)
        return res
Пример #34
0
    def add_dynamic_fields(self, res, dynamic_fields, wiz):
        subattr_prefix = self._prefixes.get('subattr_prefix')
        xml_view = super(ProductConfigurator, self).add_dynamic_fields(
            res=res, dynamic_fields=dynamic_fields, wiz=wiz)

        active_step = wiz.config_session_id.get_active_step()

        cfg_steps = wiz.product_tmpl_id.config_step_line_ids
        # Continue only if product.template has substeps defined
        subproducts = any(step.config_subproduct_line_id for step in cfg_steps)

        # TODO: Find a better method for both instances of this method
        # to have all the fields passed beforehand
        fields = self.fields_get()
        dynamic_form = xml_view.xpath("//group[@name='dynamic_form']")[0]

        if not subproducts and not wiz.child_ids or not active_step:
            return xml_view

        subproduct_notebook = etree.Element(
            'notebook',
            colspan='4',
            name='subproduct_notebook',
        )
        dynamic_form.getparent().insert(0, subproduct_notebook)

        # Get the active subproduct
        subproduct_line = active_step.config_subproduct_line_id
        subproduct = subproduct_line.subproduct_id
        cfg_subproducts = wiz.child_ids.mapped('product_tmpl_id')

        active_subproduct = (subproduct and subproduct
                             not in cfg_subproducts or subproduct_line.multi)

        if active_subproduct:
            subproduct_config_page = etree.Element(
                'page',
                name='subproduct_form',
                string='Subproduct Configuration',
            )
            subproduct_config_group = etree.Element(
                'group',
                name='subproduct_config_group',
            )
            subproduct_config_page.append(subproduct_config_group)
            subproduct_notebook.append(subproduct_config_page)

        subproducts_page = etree.Element(
            'page',
            name='subproducts',
            string='Subproducts',
        )
        subproduct_notebook.append(subproducts_page)

        subproduct_group = etree.Element(
            'group',
            name='subproduct_group',
        )
        subproducts_page.append(subproduct_group)

        subsessions_field = etree.Element(
            'field',
            name='child_ids',
            widget='one2many',
            context=str({
                'tree_view_ref': '%s.%s' % (
                    'product_configurator_mrp',
                    'product_config_session_subproducts_tree_view'
                )
            }),
            colspan='4',
            nolabel='1',
        )
        orm.setup_modifiers(subsessions_field)
        subproduct_group.append(subsessions_field)

        if not active_subproduct:
            return xml_view

        if subproduct.config_ok:
            pass
            # TODO: Implement functionality for subconfigurable products here
        else:
            attr_lines = subproduct.attribute_line_ids
            if not attr_lines:
                # Go to checkout as we have only one variant
                return xml_view
            attrs = {
                'readonly': ['|'],
                'required': [],
                'invisible': ['|']
            }
            for attr_line in attr_lines:
                attribute_id = attr_line.attribute_id.id
                field_name = subattr_prefix + str(attribute_id)

                # Check if the attribute line has been added to the db fields
                if field_name not in fields:
                    continue

                onchange_str = "onchange_subattr_value(%s, context)"
                node = etree.Element(
                    "field",
                    name=field_name,
                    on_change=onchange_str % field_name,
                    required='True' if subproduct_line.required else '',
                    default_focus="1" if attr_line == attr_lines[0] else "0",
                    attrs=str(attrs),
                    context="{'show_attribute': False}",
                    options=str({
                        'no_create': True,
                        'no_create_edit': True,
                        'no_open': True
                    })
                )
                orm.setup_modifiers(node)
                subproduct_config_group.append(node)

        return xml_view
    def add_dynamic_fields(self, res, dynamic_fields, wiz):
        """ Create the configuration view using the dynamically generated
            fields in fields_get()
        """
        field_prefix = self._prefixes.get('field_prefix')
        custom_field_prefix = self._prefixes.get('custom_field_prefix')

        try:
            # Search for view container hook and add dynamic view and fields
            xml_view = etree.fromstring(res['arch'])
            xml_static_form = xml_view.xpath("//group[@name='static_form']")[0]
            xml_dynamic_form = etree.Element('group',
                                             colspan='3',
                                             name='dynamic_form')
            xml_parent = xml_static_form.getparent()
            xml_parent.insert(
                xml_parent.index(xml_static_form) + 1, xml_dynamic_form)
            xml_dynamic_form = xml_view.xpath(
                "//group[@name='dynamic_form']")[0]
        except Exception:
            raise Warning(
                _('There was a problem rendering the view '
                  '(dynamic_form not found)'))

        # Get all dynamic fields inserted via fields_get method
        attr_lines = wiz.product_tmpl_id.attribute_line_ids.sorted()

        # Loop over the dynamic fields and add them to the view one by one
        for attr_line in attr_lines:

            attribute_id = attr_line.attribute_id.id
            field_name = field_prefix + str(attribute_id)
            custom_field = custom_field_prefix + str(attribute_id)

            # Check if the attribute line has been added to the db fields
            if field_name not in dynamic_fields:
                continue

            config_steps = wiz.product_tmpl_id.config_step_line_ids.filtered(
                lambda x: attr_line in x.attribute_line_ids)

            # attrs property for dynamic fields
            attrs = {'readonly': ['|'], 'required': [], 'invisible': ['|']}

            if config_steps:
                cfg_step_ids = [str(id) for id in config_steps.ids]
                attrs['invisible'].append(('state', 'not in', cfg_step_ids))
                attrs['readonly'].append(('state', 'not in', cfg_step_ids))

                # If attribute is required make it so only in the proper step
                if attr_line.required:
                    attrs['required'].append(('state', 'in', cfg_step_ids))

            if attr_line.custom:
                pass
                # TODO: Implement restrictions for ranges

            config_lines = wiz.product_tmpl_id.config_line_ids
            dependencies = config_lines.filtered(
                lambda cl: cl.attribute_line_id == attr_line)

            # If an attribute field depends on another field from the same
            # configuration step then we must use attrs to enable/disable the
            # required and readonly depending on the value entered in the
            # dependee

            if attr_line.value_ids <= dependencies.mapped('value_ids'):
                attr_depends = {}
                domain_lines = dependencies.mapped('domain_id.domain_line_ids')
                for domain_line in domain_lines:
                    attr_id = domain_line.attribute_id.id
                    attr_field = field_prefix + str(attr_id)
                    attr_lines = wiz.product_tmpl_id.attribute_line_ids
                    # If the fields it depends on are not in the config step
                    if config_steps and str(attr_line.id) != wiz.state:
                        continue
                    if attr_field not in attr_depends:
                        attr_depends[attr_field] = set()
                    if domain_line.condition == 'in':
                        attr_depends[attr_field] |= set(
                            domain_line.value_ids.ids)
                    elif domain_line.condition == 'not in':
                        val_ids = attr_lines.filtered(
                            lambda l: l.attribute_id.id == attr_id).value_ids
                        val_ids = val_ids - domain_line.value_ids
                        attr_depends[attr_field] |= set(val_ids.ids)

                for dependee_field, val_ids in attr_depends.iteritems():
                    if not val_ids:
                        continue
                    attrs['readonly'].append(
                        (dependee_field, 'not in', list(val_ids)))
                    attrs['required'].append(
                        (dependee_field, 'in', list(val_ids)))

            # Create the new field in the view
            node = etree.Element(
                "field",
                name=field_name,
                on_change="onchange_attribute_value(%s, context)" % field_name,
                default_focus="1" if attr_line == attr_lines[0] else "0",
                attrs=str(attrs),
                context="{'show_attribute': False}",
                options=str({
                    'no_create': True,
                    'no_create_edit': True,
                    'no_open': True
                }))

            if attr_line.required and not config_steps:
                node.attrib['required'] = '1'

            field_type = dynamic_fields[field_name].get('type')
            if field_type == 'many2many':
                node.attrib['widget'] = 'many2many_tags'

            # Apply the modifiers (attrs) on the newly inserted field in the
            # arch and add it to the view
            orm.setup_modifiers(node)
            xml_dynamic_form.append(node)

            if attr_line.custom and custom_field in dynamic_fields:
                widget = ''
                custom_ext_id = 'product_configurator.custom_attribute_value'
                custom_option_id = self.env.ref(custom_ext_id).id

                if field_type == 'many2many':
                    field_val = [(6, False, [custom_option_id])]
                else:
                    field_val = custom_option_id

                attrs['readonly'] += [(field_name, '!=', field_val)]
                attrs['invisible'] += [(field_name, '!=', field_val)]
                attrs['required'] += [(field_name, '=', field_val)]

                if config_steps:
                    attrs['required'] += [('state', 'in', cfg_step_ids)]

                # TODO: Add a field2widget mapper
                if attr_line.attribute_id.custom_type == 'color':
                    widget = 'color'
                node = etree.Element("field",
                                     name=custom_field,
                                     attrs=str(attrs),
                                     widget=widget)
                orm.setup_modifiers(node)
                xml_dynamic_form.append(node)

        return xml_view
Пример #36
0
    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        result = super(product_product, self).fields_view_get(cr, uid, view_id,view_type,context,toolbar=toolbar, submenu=submenu)
        if view_type=='form' and result.get('model') == 'product.product' and '<field name="list_price" modifiers="{}"/>' in result['arch']:
            product_price_fields_obj = self.pool.get('product.price.fields')
            product_price_fields_ids = product_price_fields_obj.search(cr, uid, [], context=context)
            price_fields = []
            tax_inc = False
            tax_ex = False
#            arch_1 = u"""<group colspan="2" col="10">\n<separator string="Tax exclude prices" colspan="10"/>\n"""
#            arch_2 = u"""</group>\n"""
#            arch_3 = u"""<group colspan="2" col="10">\n<separator string="Tax include prices" colspan="10"/>\n"""
#            arch_4 = u"""<separator colspan="10"/>\n</group>"""
#            for field in product_price_fields_obj.browse(cr, uid, product_price_fields_ids, context=context):
#                price_fields += [field.field_name, field.basedon_field_id.name, field.product_coef_field_id.name]
#                fields_arch = u"""<label string="%s :" colspan="3"/>\n<field name="%s" colspan="4" nolabel="1"/>\n<field name="%s" string="Coef" colspan="1" attrs="{'readonly':[('%s','!=','product_coef')]}" modifiers="{&quot;readonly&quot;:[[&quot;%s&quot;,&quot;!=&quot;,&quot;product_coef&quot;]]}"/>\n<field name="%s" colspan="1" nolabel="1" attrs="{'readonly':[('%s','!=','manual')]}" modifiers="{&quot;readonly&quot;:[[&quot;%s&quot;,&quot;!=&quot;,&quot;manual&quot;]]}"/>\n""" % (field.name, field.basedon_field_id.name, field.product_coef_field_id.name, field.basedon_field_id.name, field.basedon_field_id.name, field.field_name, field.basedon_field_id.name, field.basedon_field_id.name)
#                if field.tax_included:
#                    arch_3 +=  fields_arch
#                    tax_inc = True
#                else:
#                    arch_1 += fields_arch
#                    tax_ex = True
#                print price_fields
#            #remove group tax include or tax exclude if no price in it
#            if not tax_inc:
#                arch = arch_1 + arch_4
#            elif not tax_ex:
#                arch = arch_3 + arch_4
#            else:
#                arch = arch_1 + arch_2 + arch_3 + arch_4
#            import pdb;pdb.set_trace()
#            result['fields'].update(self.fields_get(cr, uid, price_fields, context))
#            result['arch'] = result['arch'].decode('utf8').replace('<field name="list_price" modifiers="{}"/>', arch)
##            print result
            eview = etree.fromstring(result['arch'])
            #select separator just before field : list_price in order to remove it
            main_sep = eview.xpath("//field[@name='list_price']/preceding-sibling::*[1]")
            main_sep = main_sep[0]
            main_sep.getparent().remove(main_sep)
            btn = eview.xpath("//field[@name='list_price']")
            if btn:
                btn = btn[0]
                group_ex = etree.Element('group', colspan="2", col="11")
                _separator_ex = etree.SubElement(
                                group_ex,
                                'separator',
                                colspan="10",
                                string="Tax exclude prices")
                group_inc = etree.Element('group', colspan="2", col="11")
                _separator_inc = etree.SubElement(
                                group_inc,
                                'separator',
                                colspan="10",
                                string="Tax include prices")
                group_sep = etree.Element('group', colspan="2", col="11")
                _separator_end = etree.SubElement(
                                group_sep,
                                'separator',
                                colspan="11")
                inc_price = self.pool.get('product.price.fields').search(cr, uid, [
                                                                        ('tax_included', '=', True)
                                                                        ], context=context)
                if inc_price:
                    button_parent = group_inc
                else:
                    button_parent = group_ex
                _button = etree.SubElement(
                                button_parent,
                                'button',
                                colspan="1",
                                name="refresh_prices",
                                string="Refresh Prices",
                                type="object")
                for field in product_price_fields_obj.browse(cr, uid, product_price_fields_ids, context=context):
                    price_fields = [field.field_name, field.basedon_field_id.name, field.product_coef_field_id.name, field.inc_price_field_id.name]
                    result['fields'].update(self.fields_get(cr, uid, price_fields, context))
                    if field.tax_included:
                        parent =  group_inc
                        tax_inc = True
                        inc_readonly = "0"
                        ex_readonly = "1"
                    else:
                        parent = group_ex
                        tax_ex = True
                        inc_readonly = "1"
                        ex_readonly = "0"
                    _label = etree.SubElement(
                                parent,
                                'label',
                                colspan="3",
                                string="%s" % field.name)
                    _basedon = etree.SubElement(
                                parent,
                                'field',
                                name="%s" % field.basedon_field_id.name,
                                colspan="4",
                                nolabel="1")
                    setup_modifiers(
                        _basedon, field=result['fields'][field.basedon_field_id.name], context=context)
                    coef = etree.SubElement(
                                parent,
                                'field',
                                digits="(18, 6)",
                                name="%s" % field.product_coef_field_id.name,
                                string="Coef",
                                colspan="1",
                                attrs="{'readonly':[('%s','!=','product_coef')]}" % field.basedon_field_id.name)
                    setup_modifiers(coef,
                                    field=result['fields'][field.product_coef_field_id.name],
                                    context=context)
                    price = etree.SubElement(
                                parent,
                                'field',
                                digits ="(12, %s)" % (self.pool.get('decimal.precision').precision_get(cr, uid, 'Sale Price')),
                                name="%s" % field.field_name,
                                colspan="1",
                                nolabel="1",
                                readonly = ex_readonly,
                                attrs="{'readonly':[('%s','!=','manual')]}" % field.basedon_field_id.name)
                    setup_modifiers(price,
                                    field=result['fields'][field.field_name],
                                    context=context)
                    inc_price = etree.SubElement(
                                parent,
                                'field',
                                digits ="(12, %s)" % (self.pool.get('decimal.precision').precision_get(cr, uid, 'Sale Price')),
                                name="%s" % field.inc_price_field_id.name,
                                colspan="1",
                                nolabel="1",
                                readonly = inc_readonly,
                                attrs="{'readonly':[('%s','!=','manual')]}" % field.basedon_field_id.name)
                    setup_modifiers(inc_price,
                                    field=result['fields'][field.inc_price_field_id.name],
                                    context=context)
                arch = etree.Element('group', colspan="2", col="11")
                if tax_inc:
                    arch.extend(group_inc)
                if tax_ex:
                    arch.extend(group_ex)
                arch.extend(group_sep)
                btn.getparent().replace(btn, arch)
            result['arch'] = etree.tostring(eview, pretty_print=True)
        return result
Пример #37
0
 def fields_view_get(self,
                     cr,
                     uid,
                     view_id=None,
                     view_type='form',
                     context=None,
                     toolbar=False,
                     submenu=False):
     result = super(product_product, self).fields_view_get(cr,
                                                           uid,
                                                           view_id,
                                                           view_type,
                                                           context,
                                                           toolbar=toolbar,
                                                           submenu=submenu)
     if view_type == 'form' and result.get(
             'model'
     ) == 'product.product' and '<field name="list_price" modifiers="{}"/>' in result[
             'arch']:
         product_price_fields_obj = self.pool.get('product.price.fields')
         product_price_fields_ids = product_price_fields_obj.search(
             cr, uid, [], context=context)
         price_fields = []
         tax_inc = False
         tax_ex = False
         #            arch_1 = u"""<group colspan="2" col="10">\n<separator string="Tax exclude prices" colspan="10"/>\n"""
         #            arch_2 = u"""</group>\n"""
         #            arch_3 = u"""<group colspan="2" col="10">\n<separator string="Tax include prices" colspan="10"/>\n"""
         #            arch_4 = u"""<separator colspan="10"/>\n</group>"""
         #            for field in product_price_fields_obj.browse(cr, uid, product_price_fields_ids, context=context):
         #                price_fields += [field.field_name, field.basedon_field_id.name, field.product_coef_field_id.name]
         #                fields_arch = u"""<label string="%s :" colspan="3"/>\n<field name="%s" colspan="4" nolabel="1"/>\n<field name="%s" string="Coef" colspan="1" attrs="{'readonly':[('%s','!=','product_coef')]}" modifiers="{&quot;readonly&quot;:[[&quot;%s&quot;,&quot;!=&quot;,&quot;product_coef&quot;]]}"/>\n<field name="%s" colspan="1" nolabel="1" attrs="{'readonly':[('%s','!=','manual')]}" modifiers="{&quot;readonly&quot;:[[&quot;%s&quot;,&quot;!=&quot;,&quot;manual&quot;]]}"/>\n""" % (field.name, field.basedon_field_id.name, field.product_coef_field_id.name, field.basedon_field_id.name, field.basedon_field_id.name, field.field_name, field.basedon_field_id.name, field.basedon_field_id.name)
         #                if field.tax_included:
         #                    arch_3 +=  fields_arch
         #                    tax_inc = True
         #                else:
         #                    arch_1 += fields_arch
         #                    tax_ex = True
         #                print price_fields
         #            #remove group tax include or tax exclude if no price in it
         #            if not tax_inc:
         #                arch = arch_1 + arch_4
         #            elif not tax_ex:
         #                arch = arch_3 + arch_4
         #            else:
         #                arch = arch_1 + arch_2 + arch_3 + arch_4
         #            import pdb;pdb.set_trace()
         #            result['fields'].update(self.fields_get(cr, uid, price_fields, context))
         #            result['arch'] = result['arch'].decode('utf8').replace('<field name="list_price" modifiers="{}"/>', arch)
         ##            print result
         eview = etree.fromstring(result['arch'])
         #select separator just before field : list_price in order to remove it
         main_sep = eview.xpath(
             "//field[@name='list_price']/preceding-sibling::*[1]")
         main_sep = main_sep[0]
         main_sep.getparent().remove(main_sep)
         btn = eview.xpath("//field[@name='list_price']")
         if btn:
             btn = btn[0]
             group_ex = etree.Element('group', colspan="2", col="11")
             _separator_ex = etree.SubElement(group_ex,
                                              'separator',
                                              colspan="10",
                                              string="Tax exclude prices")
             group_inc = etree.Element('group', colspan="2", col="11")
             _separator_inc = etree.SubElement(group_inc,
                                               'separator',
                                               colspan="10",
                                               string="Tax include prices")
             group_sep = etree.Element('group', colspan="2", col="11")
             _separator_end = etree.SubElement(group_sep,
                                               'separator',
                                               colspan="11")
             inc_price = self.pool.get('product.price.fields').search(
                 cr, uid, [('tax_included', '=', True)], context=context)
             if inc_price:
                 button_parent = group_inc
             else:
                 button_parent = group_ex
             _button = etree.SubElement(button_parent,
                                        'button',
                                        colspan="1",
                                        name="refresh_prices",
                                        string="Refresh Prices",
                                        type="object")
             for field in product_price_fields_obj.browse(
                     cr, uid, product_price_fields_ids, context=context):
                 price_fields = [
                     field.field_name, field.basedon_field_id.name,
                     field.product_coef_field_id.name,
                     field.inc_price_field_id.name
                 ]
                 result['fields'].update(
                     self.fields_get(cr, uid, price_fields, context))
                 if field.tax_included:
                     parent = group_inc
                     tax_inc = True
                     inc_readonly = "0"
                     ex_readonly = "1"
                 else:
                     parent = group_ex
                     tax_ex = True
                     inc_readonly = "1"
                     ex_readonly = "0"
                 _label = etree.SubElement(parent,
                                           'label',
                                           colspan="3",
                                           string="%s" % field.name)
                 _basedon = etree.SubElement(parent,
                                             'field',
                                             name="%s" %
                                             field.basedon_field_id.name,
                                             colspan="4",
                                             nolabel="1")
                 setup_modifiers(
                     _basedon,
                     field=result['fields'][field.basedon_field_id.name],
                     context=context)
                 coef = etree.SubElement(
                     parent,
                     'field',
                     digits="(18, 6)",
                     name="%s" % field.product_coef_field_id.name,
                     string="Coef",
                     colspan="1",
                     attrs="{'readonly':[('%s','!=','product_coef')]}" %
                     field.basedon_field_id.name)
                 setup_modifiers(coef,
                                 field=result['fields'][
                                     field.product_coef_field_id.name],
                                 context=context)
                 price = etree.SubElement(
                     parent,
                     'field',
                     digits="(12, %s)" %
                     (self.pool.get('decimal.precision').precision_get(
                         cr, uid, 'Sale Price')),
                     name="%s" % field.field_name,
                     colspan="1",
                     nolabel="1",
                     readonly=ex_readonly,
                     attrs="{'readonly':[('%s','!=','manual')]}" %
                     field.basedon_field_id.name)
                 setup_modifiers(price,
                                 field=result['fields'][field.field_name],
                                 context=context)
                 inc_price = etree.SubElement(
                     parent,
                     'field',
                     digits="(12, %s)" %
                     (self.pool.get('decimal.precision').precision_get(
                         cr, uid, 'Sale Price')),
                     name="%s" % field.inc_price_field_id.name,
                     colspan="1",
                     nolabel="1",
                     readonly=inc_readonly,
                     attrs="{'readonly':[('%s','!=','manual')]}" %
                     field.basedon_field_id.name)
                 setup_modifiers(
                     inc_price,
                     field=result['fields'][field.inc_price_field_id.name],
                     context=context)
             arch = etree.Element('group', colspan="2", col="11")
             if tax_inc:
                 arch.extend(group_inc)
             if tax_ex:
                 arch.extend(group_ex)
             arch.extend(group_sep)
             btn.getparent().replace(btn, arch)
         result['arch'] = etree.tostring(eview, pretty_print=True)
     return result
Пример #38
0
 def modifiers_and_append(elem):
     orm.setup_modifiers(elem, context=context)
     group.append(elem)
Пример #39
0
 def modifiers_and_append(elem):
     orm.setup_modifiers(elem)
     group.append(elem)
Пример #40
0
    def fields_view_get(self, cr, uid, view_id=None, view_type='form',
                        context=None, toolbar=False, submenu=False):
        if context is None:
            context = {}

        res = super(ResPartner, self).fields_view_get(
            cr, uid,
            view_id=view_id,
            view_type=view_type,
            context=context,
            toolbar=toolbar,
            submenu=submenu)
        # Read only field contact base specific groups
        doc = etree.fromstring(res['arch'])
        if uid != SUPERUSER_ID:
            lecture_group = self.user_has_groups(
                cr, uid,
                'coop_membership.group_membership_bdm_lecture')
            writer_group = self.user_has_groups(
                cr, uid,
                'coop_membership.group_membership_access_edit')
            if view_type == 'form':
                if lecture_group and not writer_group:
                    model_data_obj = self.pool['ir.model.data']
                    shift_ext_from_partner_id = model_data_obj. \
                        get_object_reference(
                        cr, uid,
                        'coop_shift',
                        'act_shift_registration_from_partner')[1]
                    shift_ext_from_partner_tree_id = model_data_obj. \
                        get_object_reference(
                        cr, uid,
                        'coop_shift',
                        'act_shift_registration_from_partner_tree_mode')[1]

                    tpl_reg_line_fr_partner_id = model_data_obj. \
                        get_object_reference(
                        cr, uid,
                        'coop_shift',
                        'act_template_registration_line_from_partner')[1]
                    tpl_reg_line_fr_partner_tree_id = model_data_obj. \
                        get_object_reference(
                        cr, uid,
                        'coop_shift',
                        'act_template_registration_line_from_partner_tree_mode')[1]

                    for node in doc.xpath("//button"):
                        if node.get('name') == str(shift_ext_from_partner_id):
                            node.set(
                                'name',
                                str(shift_ext_from_partner_tree_id))
                        if node.get('name') == str(tpl_reg_line_fr_partner_id):
                            node.set(
                                'name',
                                str(tpl_reg_line_fr_partner_tree_id))
        access_inform = self.user_has_groups(
            cr, uid,
            'coop_membership.coop_group_access_res_partner_inform'
        )
        if not access_inform:
            node = doc.xpath("//field[@name='inform_id']")
            options = {
                'no_create': True,
                'no_quick_create': True,
                'no_create_edit': True
            }
            if node:
                node[0].set("options", repr(options))
                setup_modifiers(node[0], res['fields']['inform_id'])
        res['arch'] = etree.tostring(doc)
        return res
Пример #41
0
    def fields_view_get(self,
                        view_id=None,
                        view_type='form',
                        toolbar=False,
                        submenu=False):
        """
        If we came from sale order, we send in context 'force_product_edit'
        and we change tree view to make editable and also field qty
        """
        res = super(ProductProduct, self).fields_view_get(view_id=view_id,
                                                          view_type=view_type,
                                                          toolbar=toolbar,
                                                          submenu=submenu)
        purchase_quotation_products = self._context.get(
            'purchase_quotation_products')
        if purchase_quotation_products and view_type == 'tree':
            doc = etree.XML(res['arch'])

            # replace uom_id to uom_po_id field
            node = doc.xpath("//field[@name='uom_id']")[0]
            replacement_xml = """
                <field name="uom_po_id"/>
                """
            uom_po_id_node = etree.fromstring(replacement_xml)
            node.getparent().replace(node, uom_po_id_node)
            res['fields'].update(self.fields_get(['uom_po_id']))

            # make all fields not editable
            for node in doc.xpath("//field"):
                node.set('readonly', '1')
                setup_modifiers(node, res['fields'], in_tree_view=True)

            # add qty field
            placeholder = doc.xpath("//field[1]")[0]
            placeholder.addprevious(
                etree.Element(
                    'field',
                    {
                        'name': 'qty_purchase',
                        # we force editable no matter user rights
                        'readonly': '0',
                    }))
            res['fields'].update(self.fields_get(['qty_purchase']))

            # add button tu open form
            placeholder = doc.xpath("//tree")[0]
            placeholder.append(
                etree.Element(
                    'button', {
                        'name': 'action_product_form',
                        'type': 'object',
                        'icon': 'fa-external-link',
                        'string': _('Open Product Form View'),
                    }))

            # make tree view editable
            for node in doc.xpath("/tree"):
                node.set('edit', 'true')
                node.set('create', 'false')
                node.set('editable', 'top')
            res['arch'] = etree.tostring(doc)
        return res
Пример #42
0
 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
      
     user = self.pool.get('res.users').browse(cr,uid,uid)
      
     if context is None:
         context = {}
     res = super(sale_order, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
     doc = etree.XML(res['arch'])
     cr.execute("""select uid from res_groups_users_rel where gid in
                   (select id  from res_groups where category_id in 
                   ( select id from ir_module_category where name = 'Customer Portal' ) and name in ('User','Manager')) and uid = """+str(uid))
     portal_user = cr.fetchone()
     if portal_user: 
     
         if ('fields' in res) and (res['fields'].get('order_line'))\
                 and (res['fields']['order_line'].get('views'))\
                 and (res['fields']['order_line']['views'].get('tree'))\
                 and (res['fields']['order_line']['views']['tree'].get('arch')):
 #             doc = etree.XML(res['fields']['order_line']['views']['tree']['arch']) 
 #             print 'doc',res['fields']['order_line']['views']['tree']['arch']
             
 
                 doc1 = etree.XML(res['fields']['order_line']['views']['tree']['arch'])
                 for node in doc1.xpath("//field[@name='price_unit']"):
                     node.set('readonly', '1')
                     setup_modifiers(node, res['fields']['order_line'])
                     res['fields']['order_line']['views']['tree']['arch'] = etree.tostring(doc1)
                 
                 for node in doc1.xpath("//field[@name='tax_id']"):
                     node.set('readonly', '1')
                     setup_modifiers(node, res['fields']['order_line'])
                     res['fields']['order_line']['views']['tree']['arch'] = etree.tostring(doc1)
                 
 #                 
 #         if portal_user:
         if view_type == 'form':
             domain  = "[('id','child_of',"+str(user.partner_id.id)+")]"
             for node in doc.xpath("//field[@name='pricelist_id']"):
                 node.set('options', '{"no_open":True}')
                 node.set('readonly','1')
                 setup_modifiers(node,res['fields']['pricelist_id'])
                 res['arch'] = etree.tostring(doc)
                   
             for node in doc.xpath("//field[@name='partner_id']"):
                 node.set('options', "{'no_open' : true}")
                 node.set('options', "{'no_create' : true}")
                 node.set('domain', domain )
                 setup_modifiers(node, res['fields']['partner_id'])
                 res['arch'] = etree.tostring(doc)
                   
             for node in doc.xpath("//field[@name='contact_id']"):
                 node.set('options', "{'no_open' : true}")
                 setup_modifiers(node, res['fields']['contact_id'])
                 res['arch'] = etree.tostring(doc)
                                       
                    
             for node in doc.xpath("//field[@name='partner_invoice_id']"):
                 node.set('options', "{'no_open' : true}")
                 node.set('domain', domain )
                 setup_modifiers(node, res['fields']['partner_invoice_id'])
                 res['arch'] = etree.tostring(doc)
                    
             for node in doc.xpath("//field[@name='partner_shipping_id']"):
                 node.set('options', "{'no_open' : true}")
                 node.set('domain', domain )
                 setup_modifiers(node, res['fields']['partner_shipping_id'])
                 res['arch'] = etree.tostring(doc)
                
             for node in doc.xpath("//field[@name='warehouse_id']"):
                 node.set('options', "{'no_open' : true}")
                 setup_modifiers(node, res['fields']['warehouse_id'])
                 res['arch'] = etree.tostring(doc)
                   
             for node in doc.xpath("//field[@name='payment_term']"):
                 node.set('options', "{'no_open' : true}")
                 setup_modifiers(node, res['fields']['payment_term'])
                 res['arch'] = etree.tostring(doc)
               
             for node in doc.xpath("//field[@name='date_order']"):
                 node.set('readonly', "1")
                 setup_modifiers(node, res['fields']['date_order'])
                 res['arch'] = etree.tostring(doc)
                     
     return res
 def modifiers_and_append(elem):
     setup_modifiers(elem)
     group.append(elem)
Пример #44
0
    def fields_view_get(self, view_id=None, view_type=False, toolbar=False, submenu=False):
        res = super(workflow_base, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
        if view_type in ('tree', 'form') and hasattr(self, 'wkf_id'):
            if self.env.context.get('active_id', False):
                self.env.cr.execute('SELECT wkf_id FROM %s WHERE id=%s LIMIT 1'%(self._table, self.env.context['active_id']))
                wkf_id = self.env.cr.dictfetchone()
                wkf_id = wkf_id and wkf_id['wkf_id']
            else:
                wkf_id = False
            
            if not wkf_id:
                self.env.cr.execute('SELECT id FROM wkf WHERE osv=%s AND is_active LIMIT 1', (self._name, ))
                wkf_id = self.env.cr.dictfetchone()
                wkf_id = wkf_id and wkf_id['id']
                
            if wkf_id:
                self.env.cr.execute('SELECT attrs_buttons, display_state_visible from wkf WHERE id=%s LIMIT 1', (wkf_id, ))
                wkf = self.env.cr.dictfetchone()
                if wkf and wkf['attrs_buttons']:
                    doc = etree.XML(res['arch'])

                    # Gestion du display state
                    selection = []
                    for display_state in self.env['workflow.display.state'].search([('wkf_id', '=', self.wkf_id and self.wkf_id.id or wkf_id)]).read(['name', 'label']):
                        selection.append((display_state['name'], display_state['label']))
                    
                    if selection:
                        res['fields']['display_state'] = {'type': 'selection', 'string': _('State'), 'selection': selection}
                        f_display = {'string': 'State', 'name': 'display_state', 'widget': 'statusbar'}
#                         A décommenter si on gère statusbar_colors
#                         if wkf['display_state_colors']:
#                             if wkf['display_state_colors']:
#                                 f_display['statusbar_colors'] = wkf['display_state_colors']
    
                        if wkf['display_state_visible']:
                            f_display['statusbar_visible'] = wkf['display_state_visible']
                            
                    if view_type == 'tree':
                        if selection:
                            # Remplacement du state par le display state
                            sn = doc.xpath("//field[@name='state']")
                            if sn:
                                sn[0].attrib['invisible'] = '1'
                                setup_modifiers(sn[0], in_tree_view=True)
                                sn_parent = sn[0].getparent()
                                sn_parent.insert(sn_parent.index(sn[0]) + 1, etree.Element('field', f_display))
                                
                    else:
                        notebook = doc.xpath("//notebook")
                        if notebook:
                            page = etree.Element('page', {'string': _('Workflow')})
                            # wkf_id pour l'admin
                            res['fields']['wkf_id'] = {'name': 'wkf_id', 'type': 'many2one', 'relation': 'workflow'}
                            workflow_id = etree.Element('field', {'name': 'wkf_id', 'groups': 'base.group_erp_manager', 'string': _('Workflow')})
                            page.append(workflow_id)
                            setup_modifiers(workflow_id)
                            # Bouton de réinitialisation du WKF pour l'admin
                            b_display = {'string': _('Reset workflow'), 'groups': 'base.group_erp_manager', 'name': 'reset_workflow', 'type': 'object', 'confirm': _('Are you sure to want to reset workflow?')}
                            b = etree.Element('button', b_display)
                            page.append(b)
                            setup_modifiers(b, b_display)
                            # Champ d'état du workflow
                            res['fields']['wkf_progress_instance'] = {'name': 'wkf_progress_instance', 'type': 'char', 'size': 128, 'compute': '_compute_wkf_progress_instance'}
                            wkf_progress_instance = etree.Element('field', {'name': 'wkf_progress_instance', 'invisible': '1'})
                            setup_modifiers(wkf_progress_instance)
                            page.append(wkf_progress_instance)
                            # Liste des activités du workflow
                            res['fields']['wkf_instance_ids'] = {'store': False, 'name': 'wkf_instance_ids', 'type': 'one2many', 'compute': '_compute_wkf_instance', 'inverse': '_write_wkf_instance', 'comodel_name': 'workflow.instance', 'relation': 'workflow.instance', 'model': self._name}
                            wkf_instance_ids = etree.Element('field', {'name': 'wkf_instance_ids', 'nolabel': '1', 'colspan': '4'})
                            setup_modifiers(wkf_instance_ids)
                            page.append(wkf_instance_ids)
                            notebook[0].append(page)
                        
                        nodes = doc.xpath("//header")
                        if not nodes:
                            nodes = doc.xpath("//form")
                            if nodes:
                                nodes[0].append(etree.Element('header'))
                                nodes = doc.xpath("//header")
                            else:
                                nodes = False

                        if nodes:
                            attrs_buttons = eval(wkf['attrs_buttons'])
                            transition_obj = self.env['workflow.transition']
                            b_list = []
                            # Champ pour les attrs des boutons et boutons
                            for b_name, b_attrs in attrs_buttons.iteritems():
                                b_vals = transition_obj.browse(b_attrs[1]).read(['button_specific_sequence', 'sequence', 'button_label', 'with_mail', 'mail_template_id', 'button_group_id', 'button_context', 'button_confirm', 'button_class', 'with_custom_wizard', 'custom_wizard_method'], load='_classic_write')[0]
                                b_list.append((b_vals['button_specific_sequence'] or b_vals['sequence'], b_name, b_vals, b_attrs))
                              
                            for dummy, b_name, b_vals, b_attrs in sorted(b_list, key=itemgetter(0), reverse=True):
                                if not b_vals['button_group_id'] or self.env.user.user_has_group(b_vals['button_group_id']):
                                    mail_context = ''
                                    wizard_context = ''
                                    if b_vals['with_custom_wizard']:
                                        wizard_context = '"custom_wizard_wkf_signal": "%s", '%(b_name)
                                        b_display = {'string': b_vals['button_label'],
                                                     'attrs': str(b_attrs[0]), 
                                                     'name': b_vals['custom_wizard_method'], 
                                                     'type': 'object'}
                                        b = etree.Element('button', b_display)
                                        if b_vals['with_mail']:
                                            mail_context = '"send_mail_wkf_signal": "%s", "send_mail_wkf_mail_template": %s,'%(b_name, b_vals['mail_template_id'])
                                            
                                    elif b_vals['with_mail']:
                                        mail_context = '"send_mail_wkf_signal": "%s", "send_mail_wkf_mail_template": %s,'%(b_name, b_vals['mail_template_id'])
                                        b_display = {'string': b_vals['button_label'],
                                                     'attrs': str(b_attrs[0]), 
                                                     'name': 'send_mail_workflow', 
                                                     'type': 'object'}
                                        b = etree.Element('button', b_display)
                                    else:
                                        b_display = {'string': b_vals['button_label'], 
                                                     'attrs': str(b_attrs[0]), 
                                                     'name': b_name}
                                    
                                    if b_vals['button_class']:
                                        b_display['class'] = b_vals['button_class']
                                        
                                    if b_vals['button_group_id']:
                                        b_display['groups'] = str(b_vals['button_group_id'])
                                        
                                    if b_vals['button_confirm']:
                                        b_display['confirm'] = b_vals['button_confirm']
                                    
                                    if mail_context or wizard_context or b_vals['button_context']:
                                        button_context = '{%s %s %s}'%(mail_context or '', wizard_context or '', b_vals['button_context'] or '')
                                        b_display['context'] = button_context
                                        
                                    b = etree.Element('button', b_display)
                                    nodes[0].insert(0, b)
                                    setup_modifiers(b, b_display)
        
                            # Remplacement du state par le display state
                            if selection:
                                state_nodes = doc.xpath("//header/field[@name='state']")
                                if state_nodes:
                                    state_nodes[0].attrib['invisible'] = '1'
                                    setup_modifiers(state_nodes[0])
                                    
                                nodes[0].insert(-1, etree.Element('field', f_display))
                            
                    res['arch'] = etree.tostring(doc)
                    
        return res
    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        
        if context is None:
            context = {}
        pick_type_obj = self.pool.get("stock.picking.type")
        res = super(stock_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
        doc = etree.XML(res['arch'])
        if context.get('default_picking_type_id',False):
            pick_type = pick_type_obj.browse(cr, uid,[context.get('default_picking_type_id')])
            if pick_type:
                if pick_type.code == 'internal':
                    if view_type == 'form':
                        for node in doc.xpath("//field[@name='partner_id']"):
                            node.set('invisible', '1')
                            setup_modifiers(node, res['fields']['partner_id'])
                            res['arch'] = etree.tostring(doc)
        else:
            cr.execute("""select uid from res_groups_users_rel where gid=
              (select id  from res_groups where category_id in 
              ( select id from ir_module_category where name = 'Customer Portal' ) and name = 'Manager') and uid = """+str(uid))
            portal_user = cr.fetchone() 
            portal_group = portal_user and portal_user[0]
            if uid == portal_group:
                for node in doc.xpath("//notebook/page[@string='Products']/field[@name='move_lines']"):
                    node.set('readonly','1')
                    setup_modifiers(node, res['fields']['move_lines'])
                    res['arch'] = etree.tostring(doc)
                    
                for node in doc.xpath("//field[@name='partner_id']"):
                    node.set('readonly','1')
                    setup_modifiers(node, res['fields']['partner_id'])
                    res['arch'] = etree.tostring(doc)
                    
                for node in doc.xpath("//field[@name='date']"):
                    node.set('readonly','1')
                    setup_modifiers(node, res['fields']['date'])
                    res['arch'] = etree.tostring(doc)
                    
                for node in doc.xpath("//field[@name='min_date']"):
                    node.set('readonly','1')
                    setup_modifiers(node, res['fields']['min_date'])
                    res['arch'] = etree.tostring(doc)

                for node in doc.xpath("//field[@name='origin']"):
                    node.set('readonly','1')
                    setup_modifiers(node, res['fields']['origin'])
                    res['arch'] = etree.tostring(doc)
               
                for node in doc.xpath("//field[@name='cust_po_ref']"):
                    node.set('readonly','1')
                    setup_modifiers(node, res['fields']['cust_po_ref'])
                    res['arch'] = etree.tostring(doc)     

                for node in doc.xpath("//field[@name='vehicle']"):
                    node.set('readonly','1')
                    setup_modifiers(node, res['fields']['vehicle'])
                    res['arch'] = etree.tostring(doc)     
                
                for node in doc.xpath("//field[@name='partner_id']"):
                    node.set('options', "{'no_open' : true}")
                    setup_modifiers(node, res['fields']['partner_id'])
                    res['arch'] = etree.tostring(doc)
                
        return res
    def fields_view_get(self, view_id=None, view_type=False,
                        toolbar=False, submenu=False):
        res = super(StockPicking, self).fields_view_get(
            view_id=view_id, view_type=view_type,
            toolbar=toolbar, submenu=submenu)

        doc = etree.XML(res["arch"])

        picking_type_id = self.env.context.get(
            "default_picking_type_id", False)

        if view_type == "tree":
            view_element = doc.xpath("/tree")[0]
        elif view_type == "form":
            view_element = doc.xpath("/form")[0]

        if not picking_type_id:
            if view_type in ["tree", "form"]:
                view_element.attrib["create"] = "false"
                view_element.attrib["edit"] = "false"
                view_element.attrib["delete"] = "false"
        else:
            pick_type = self.env["stock.picking.type"].\
                browse(picking_type_id)[0]
            if view_type in ["tree", "form"]:
                view_element.attrib[
                    "create"] = pick_type.create_ok and "true" or "false"
                view_element.attrib[
                    "edit"] = pick_type.edit_ok and "true" or "false"
                view_element.attrib[
                    "delete"] = pick_type.unlink_ok and "true" or "false"
            if view_type == "tree":
                obj_field = self.env["ir.model.fields"]
                criteria = [
                    ("model", "=", "stock.picking.type"),
                    ("name", "ilike", "tree_show_"),
                ]
                for field in obj_field.search(criteria):
                    field_name = field.name[10:]
                    path = "//field[@name='%s']" % (field_name)
                    el = doc.xpath(path)[0]
                    if not getattr(pick_type, field.name):
                        el.set("invisible", "1")
                    else:
                        el.set("invisible", "0")
                    setup_modifiers(el, res["fields"][
                                    field_name], in_tree_view=True)
            elif view_type == "form":
                obj_field = self.env["ir.model.fields"]
                criteria = [
                    ("model", "=", "stock.picking.type"),
                    ("name", "ilike", "form_show_"),
                ]
                for field in obj_field.search(criteria):
                    field_name = field.name[10:]
                    path = "//field[@name='%s']" % (field_name)
                    el = doc.xpath(path)[0]
                    if not getattr(pick_type, field.name):
                        el.set("invisible", "1")
                    else:
                        el.set("invisible", "0")
                    setup_modifiers(el, res["fields"][field_name])
                criteria = [
                    ("model", "=", "stock.picking.type"),
                    ("name", "ilike", "form_required_"),
                ]
                for field in obj_field.search(criteria):
                    field_name = field.name[14:]
                    path = "//field[@name='%s']" % (field_name)
                    el = doc.xpath(path)[0]
                    if getattr(pick_type, field.name):
                        el.set("required", "1")
                    else:
                        el.set("required", "0")
                    setup_modifiers(el, res["fields"][field_name])

        res["arch"] = etree.tostring(doc)

        return res