Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

how to modify on change sale order?

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
viewsale.order
2 Respuestas
10358 Vistas
Avatar
wendy christine

Hi everybody,

I'm trying to modify the form view of sale order to add two columns automaticaly filled when the product is selected with the informations of two fields i've added in the product creation. I've identified into the sale.order.form view that there is an on change option linked with the product_id_change function but i want to know where is the python file containing this function. Thanks for youre help.

0
Avatar
Descartar
Avatar
Gopakumar N G
Mejor respuesta

Hi,

The onchange method product_id_change is defined in sale module in sale.py file's sale.order.line model.

def product_id_change(self, cr, uid, ids, pricelist, product, qty=0,
            uom=False, qty_uos=0, uos=False, name='', partner_id=False,
            lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False):
        if not  partner_id:
            raise osv.except_osv(_('No Customer Defined !'), _('You have to select a customer in the sales form !\nPlease set one customer before choosing a product.'))
        warning = {}
        product_uom_obj = self.pool.get('product.uom')
        partner_obj = self.pool.get('res.partner')
        product_obj = self.pool.get('product.product')
        if partner_id:
            lang = partner_obj.browse(cr, uid, partner_id).lang
        context = {'lang': lang, 'partner_id': partner_id}

        if not product:
            return {'value': {'th_weight': 0, 'product_packaging': False,
                'product_uos_qty': qty, 'tax_id':[]}, 'domain': {'product_uom': [],
                   'product_uos': []}}
        if not date_order:
            date_order = time.strftime('%Y-%m-%d')

        result = {}
        product_obj = product_obj.browse(cr, uid, product, context=context)
        if not packaging and product_obj.packaging:
            packaging = product_obj.packaging[0].id
            result['product_packaging'] = packaging

        if packaging:
            default_uom = product_obj.uom_id and product_obj.uom_id.id
            pack = self.pool.get('product.packaging').browse(cr, uid, packaging, context=context)
            q = product_uom_obj._compute_qty(cr, uid, uom, pack.qty, default_uom)
#            qty = qty - qty % q + q
            if qty and (q and not (qty % q) == 0):
                ean = pack.ean or _('(n/a)')
                qty_pack = pack.qty
                type_ul = pack.ul
                warn_msg = _("You selected a quantity of %d Units.\n"
                            "But it's not compatible with the selected packaging.\n"
                            "Here is a proposition of quantities according to the packaging:\n\n"
                            "EAN: %s Quantity: %s Type of ul: %s") % \
                                (qty, ean, qty_pack, type_ul.name)
                warning = {
                    'title': _('Picking Information !'),
                    'message': warn_msg
                    }
            result['product_uom_qty'] = qty

        uom2 = False
        if uom:
            uom2 = product_uom_obj.browse(cr, uid, uom)
            if product_obj.uom_id.category_id.id != uom2.category_id.id:
                uom = False
        if uos:
            if product_obj.uos_id:
                uos2 = product_uom_obj.browse(cr, uid, uos)
                if product_obj.uos_id.category_id.id != uos2.category_id.id:
                    uos = False
            else:
                uos = False
        if product_obj.description_sale:
            result['notes'] = product_obj.description_sale
        fpos = fiscal_position and self.pool.get('account.fiscal.position').browse(cr, uid, fiscal_position) or False
        if update_tax: #The quantity only have changed
            result['delay'] = (product_obj.sale_delay or 0.0)
            result['tax_id'] = self.pool.get('account.fiscal.position').map_tax(cr, uid, fpos, product_obj.taxes_id)
            result.update({'type': product_obj.procure_method})

        if not flag:
            result['name'] = self.pool.get('product.product').name_get(cr, uid, [product_obj.id], context=context)[0][1]
        domain = {}
        if (not uom) and (not uos):
            result['product_uom'] = product_obj.uom_id.id
            if product_obj.uos_id:
                result['product_uos'] = product_obj.uos_id.id
                result['product_uos_qty'] = qty * product_obj.uos_coeff
                uos_category_id = product_obj.uos_id.category_id.id
            else:
                result['product_uos'] = False
                result['product_uos_qty'] = qty
                uos_category_id = False
            result['th_weight'] = qty * product_obj.weight
            domain = {'product_uom':
                        [('category_id', '=', product_obj.uom_id.category_id.id)],
                        'product_uos':
                        [('category_id', '=', uos_category_id)]}

        elif uos and not uom: # only happens if uom is False
            result['product_uom'] = product_obj.uom_id and product_obj.uom_id.id
            result['product_uom_qty'] = qty_uos / product_obj.uos_coeff
            result['th_weight'] = result['product_uom_qty'] * product_obj.weight
        elif uom: # whether uos is set or not
            default_uom = product_obj.uom_id and product_obj.uom_id.id
            q = product_uom_obj._compute_qty(cr, uid, uom, qty, default_uom)
            if product_obj.uos_id:
                result['product_uos'] = product_obj.uos_id.id
                result['product_uos_qty'] = qty * product_obj.uos_coeff
            else:
                result['product_uos'] = False
                result['product_uos_qty'] = qty
            result['th_weight'] = q * product_obj.weight        # Round the quantity up

        if not uom2:
            uom2 = product_obj.uom_id
        if (product_obj.type=='product') and (product_obj.virtual_available * uom2.factor < qty * product_obj.uom_id.factor) \
          and (product_obj.procure_method=='make_to_stock'):
            warning = {
                'title': _('Not enough stock !'),
                'message': _('You plan to sell %.2f %s but you only have %.2f %s available !\nThe real stock is %.2f %s. (without reservations)') %
                    (qty, uom2 and uom2.name or product_obj.uom_id.name,
                     max(0,product_obj.virtual_available), product_obj.uom_id.name,
                     max(0,product_obj.qty_available), product_obj.uom_id.name)
            }
        # get unit price
        if not pricelist:
            warning = {
                'title': 'No Pricelist !',
                'message':
                    'You have to select a pricelist or a customer in the sales form !\n'
                    'Please set one before choosing a product.'
                }
        else:
            price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist],
                    product, qty or 1.0, partner_id, {
                        'uom': uom,
                        'date': date_order,
                        })[pricelist]
            if price is False:
                warning = {
                    'title': 'No valid pricelist line found !',
                    'message':
                        "Couldn't find a pricelist line matching this product and quantity.\n"
                        "You have to change either the product, the quantity or the pricelist."
                    }
            else:
                result.update({'price_unit': price})
        return {'value': result, 'domain': domain, 'warning': warning}
1
Avatar
Descartar
Avatar
wendy christine
Autor Mejor respuesta

Yes i know i've already find this method, the problem is that i want to add into this method the two parameters i've added into the product.product model to return them into the result of the product_id_change method and permit to fill automatically two colums i've added to the sale.order.line.

0
Avatar
Descartar
Gopakumar N G

Which are the fields and what are their types? You can add them to the result dictionary in the above method.

wendy christine
Autor

this is two fields i've created named x_departement and x_support, the type of the two fields is Many2one and they are each related with two models (x_departement_model and x_support_model) that i've created. Each of the two models are containing one char field.

Gopakumar N G

Did you inherit the sale.order model. If yes write the product_id_change function in your inherited model and in the product_id_change function's result dictionary add the two new fields and their value.

wendy christine
Autor

Why do i have to inherit the sale.order model? If i only modify the sale.order.view adding two columns at the sale order line and addind my two new product fields as parameters of the product_id_change function and into the result dictionnary, this isn't good?

wendy christine
Autor

i write you the steps i think i had to make: -create two new fields into the sale.order.line model with type many2one linked with the two fields i've created into the product.product model -add these two new fields as columns into the sale order view xml and into the onchange of the field product_id -add the two fields as parameters of the product_id_change function of the sale.py and retrieve their value to return it into the result dictionnary

Gopakumar N G

You have two models x_departement_model and x_support_model and you have added two fields in sale order model named x_departement and x_support. You can directly add the fields to the product_id_change method in sale.order model without inheriting. But it is not recommended because if you need to migrate to a new openerp version it will cause problems.

wendy christine
Autor

oki i have understood the problem, i'm going to try what you've said and will come later to share the result. Thanks for your help

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Invoice_ids field in the view of Sale Order
view sale.order invoice.ids
Avatar
1
feb 16
4881
Display field only for one company on list view Resuelto
sale.order
Avatar
Avatar
1
may 25
1766
Sale order Balance
sale.order
Avatar
Avatar
Avatar
2
nov 24
2822
Mark a sales order as fully invoiced despite Order amount and invoiced amount do not match () Resuelto
sale.order
Avatar
Avatar
Avatar
Avatar
Avatar
4
feb 24
13455
sale / delivery Resuelto
sale.order
Avatar
Avatar
1
ene 24
2224
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now