Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

Copy lines from sale.order.template to invoice draft

Subscriure's

Get notified when there's activity on this post

This question has been flagged
developmentsale.order.lineaccount.move.linev17
1 Respondre
3386 Vistes
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 Best Answer

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
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Style Error: "Could not execute command 'sassc'
development v17
Avatar
Avatar
Avatar
Avatar
Avatar
7
de des. 24
9732
Xpath no odoo v17
development v17
Avatar
0
de jul. 24
1701
sale order attached file
attachment sale.order.line v17
Avatar
Avatar
Avatar
3
de juny 24
3408
Regarding template name
development templates v17
Avatar
0
de maig 24
2170
regarding a module library
development Cybrosys v17
Avatar
0
d’abr. 24
23
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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