Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • eLearning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Browse all Industries
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Services for Partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar 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
  • Proyecto
  • 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

Copy lines from sale.order.template to invoice draft

Suscribirse

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

Se marcó esta pregunta
developmentsale.order.lineaccount.move.linev17
1 Responder
3348 Vistas
Avatar
Marco Stalder

For invoice drafts, we created a field called x_studio_saleorder_template (Many2One) in Odoo 17. When this field change (chooses a sale.order.template), we just want to add all lines one by one to the new invoice draft by automation trigger onchange. Here is the code:



def add_template_lines(record):
    template_id = record.x_studio_saleorder_template.id
    if not template_id:
        return
    
    template = env['sale.order.template'].browse(template_id)
    if not template.exists():
        return
    
    if record.state != 'draft':
        return
    
    for line in template.sale_order_template_line_ids:
        if line.display_type == 'line_section':
            new_line_vals = {
                'move_id': record.id,
                'display_type': 'line_section',
                'name': line.name,
            }
            record.write({
                'invoice_line_ids': [(0, 0, new_line_vals)],
            })
            continue
            
        if line.display_type == 'line_note':
            new_line_vals = {
                'move_id': record.id,
                'display_type': 'line_note',
                'name': line.name,
            }
            record.write({
                'invoice_line_ids': [(0, 0, new_line_vals)],
            })
            continue
        
        if not line.product_id:
            continue
        
        new_line_vals = {
            'move_id': record.id,
            'product_id': line.product_id.id,
            'name': line.display_name or line.product_id.name,
            'quantity': line.product_uom_qty or 1.0,
            'product_uom_id': line.product_uom_id.id,
            'price_unit': 0.0,
        }
        record.write({
            'invoice_line_ids': [(0, 0, new_line_vals)],
        })
        
    record.write({
        'x_studio_saleorder_template': False,
    })
    
    action = {
        'type': 'ir.actions.act_window',
        'res_model': 'account.move',
        'view_mode': 'form',
        'res_id': record.id,
        'target': 'current',
    }
    return action
            
add_template_lines(record)

But there are some problems i can't find any solution:

  • Actually all lines will be added to the invoice draft, with following problems:
    • product_id and product_uom_id are always False after record.write() inside the line (checked with log). Checking the line.product_id.id and line.product_uom_id.id are correct!
      • Fun fact: invoice line add the right account number of the product, but not the product_id itself (why ever).
    • quantity is always 1 after record.write(); line.product_uom_qty is correct number.
    • name is always perfect!
      • line_section and line_note too.
  • After adding the lines, i try to reload the page, but the lines are not visible until i force a reload with F5.
  • Because the invoice is at draft, the record.id is called "NewId9999" not 9999.
    • Because of this i can't use record.id for move_id in combination with record.create() instead of record.write()
    • I tried some other solutions with save to db etc. but didn't worked out well.

I wanted to use automation instead of creating the own module, but it's possible too for sure, because it's self hosted.

Thanks for any help!

0
Avatar
Descartar
Avatar
Marco Stalder
Autor Mejor respuesta

Update on my site: This new code works except one thing i can't fix: After the reload i still don't see the list until i click on manual save, or refresh browser with F5!?

# Available variables:
#  - env: environment on which the action is triggered
#  - model: model of the record on which the action is triggered; is a void recordset
#  - record: record on which the action is triggered; may be void
#  - records: recordset of all records on which the action is triggered in multi-mode; may be void
#  - time, datetime, dateutil, timezone: useful Python libraries
#  - float_compare: utility function to compare floats based on specific precision
#  - log: log(message, level='info'): logging function to record debug information in ir.logging table
#  - _logger: _logger.info(message): logger to emit messages in server logs
#  - UserError: exception class for raising user-facing warning messages
#  - Command: x2many commands namespace
# To return an action, assign: action = {...}

def add_template_lines(record):
    template_id = record.x_studio_saleorder_template.id
    if not template_id or record.state != 'draft':
        return
   
    template = env['sale.order.template'].browse(template_id)
    if not template.exists():
        return
   
    new_lines = []

    for line in template.sale_order_template_line_ids:
        if line.display_type in ('line_section', 'line_note'):
            new_line_vals = {
                'move_id': record._origin.id,
                'display_type': line.display_type,
                'name': line.name,
            }
        else:
            if not line.product_id:
                continue
            new_line_vals = {
                'move_id': record._origin.id,
                'product_id': line.product_id.id,
                'name': line.display_name or line.product_id.name,
                'quantity': line.product_uom_qty or 1.0,
                'product_uom_id': line.product_uom_id.id,
                'price_unit': line.product_id.list_price or 0.0,
            }
        new_lines.append(new_line_vals)

    if new_lines:
        env['account.move.line'].create(new_lines)
       
    record.write({'x_studio_saleorder_template': False})

    #action = {
    #    'type': 'ir.actions.client',
    #    'tag': 'pxa_account_move_save_reload_view',
    #    'params': {
    #        'record_id': record.id,
    #    },
    #}
    action = {
        'type': 'ir.actions.client',
        'tag': 'reload',
    }
    return action

add_template_lines(record)


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

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

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Style Error: "Could not execute command 'sassc'
development v17
Avatar
Avatar
Avatar
Avatar
Avatar
7
dic 24
9654
Xpath no odoo v17
development v17
Avatar
0
jul 24
1659
sale order attached file
attachment sale.order.line v17
Avatar
Avatar
Avatar
3
jun 24
3363
Regarding template name
development templates v17
Avatar
0
may 24
2148
regarding a module library
development Cybrosys v17
Avatar
0
abr 24
23
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información 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 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