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 create a custom sequence with the format 'company_register-code_reference'?

Suscribirse

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

Se marcó esta pregunta
salesequencecompanyOdoo17
1 Responder
1996 Vistas
Avatar
Aprilia Zahratunnisa

I want to create a custom sequence. I've tried it but it doesn't work in the 'company_register' section.


This is "company.xml":

            BODEBEK        1           
            Bogor        1           
            Depok        1   
            Bekasi        1   
            Company 2        2                Company 3        3                Company 4        4                Company 5        5                Company 6        6                Company 7        7                Company 8        8                Company 9        9                Company 10        10                Company 11        11                Company 12        12                Company 13        13                Company 14        14                Company 15        15                Company 16        16                Company 17        17       


This is the Company model, so there are 17 companies:

class Company(models.Model)
​_inherit = 'res.company'

​parent_id = fields.Many2one('res.company', string="Parent Company")
​child_ids = fields.One2many('res.company', 'parent_id', string="Branch Companies") 
​company_registry = fields.Char(string="Company Registry", required=True)

​ @api.model
​def create_branch_companies(self):
​ ​parent_company = self.env['res.company'].search([('name', '=', 'BODEBEK')], limit=1)       
​ ​if not parent_company:
​ ​ ​raise ValueError("Parent company 'BODEBEK' not found")
        branch_names = ['Bogor', 'Depok', 'Bekasi']
        for branch_name in branch_names:
​ ​ ​self.env['res.company'].create({
​ ​ ​ ​'name': branch_name,
​ ​ ​ ​'parent_id': parent_company.id,
​ ​ ​ ​'company_registry': '1',
​ ​ ​})
        return True


and this is the Sale Order model where 'reference_code' field resides:

class SaleOrder(models.Model):
​_inherit = 'sale.order'

​reference_code = fields.Char(string="Order Reference", readonly=True, copy=False) 
​company_id = fields.Many2one('res.company', string="Company", required=True)
   
​@api.model   
​def _get_sequence(self, company_id):       
​ ​company = self.env['res.company'].browse(company_id)       
​ ​sequence_code = 'sale.order'       
​ ​sequence = self.env['ir.sequence'].search([
​ ​ ​('code', '=', sequence_code),
​ ​ ​('company_id', '=', company_id)
​ ​])       
​ ​if not sequence:           
​ ​ ​sequence = self.env['ir.sequence'].create({               
​ ​ ​ ​'name': f'Sale Order Reference {company.company_registry}',     
​ ​ ​ ​'code': sequence_code,               
​ ​ ​ ​'company_id': company_id,               
​ ​ ​ ​'prefix': f'{company.company_registry}-',               
​ ​ ​ ​'padding': 5,               
​ ​ ​ ​'number_next': 1,               
​ ​ ​ ​'number_increment': 1,           
​ ​ ​})       
​ ​ ​return sequence

    @api.model   
​def create(self, vals):       
​ ​if vals.get('company_id'):           
​ ​ ​sequence = self._get_sequence(vals['company_id'])
​ ​ ​vals['reference_code'] = f"{sequence.prefix{sequence.next_by_id(sequence.id)}"       
​ ​return super(SaleOrder, self).create(vals)
0
Avatar
Descartar
Faris Fathurrahman

can you explain better? especially with the 'company.xml' file

Avatar
Kanak Infosystems LLP
Mejor respuesta

Greetings, please find the answer to your query below:
 
@api.model    

def create(self, vals):        

    if vals.get('company_id'):            

        sequence = self._get_sequence(vals['company_id'])

        # Generate the next sequence number and update the reference code

        next_sequence_number = sequence.next_by_id( sequence.id )

        vals['reference_code'] = f"{sequence.prefix}{next_sequence_number}"

        # Update the sequence to increment the next number

        sequence.write({'number_next': next_sequence_number + 1})

    return super(SaleOrder, self).create(vals)


 

correct:

vals['reference_code'] = f"{sequence.prefix}{sequence.next_by_id( sequence.id )}"


  • The fix here was to properly concatenate sequence.prefix with the next_by_id( sequence.id ) value, which is the actual next number in the sequence.


  • In your code, the next_by_id() function was being used to generate the reference code, but you weren't updating the number_next field in the sequence record. This would result in the sequence number always remaining the same after the first order.


Your code:

vals['reference_code'] = f"{sequence.prefix}{sequence.next_by_id( sequence.id )}"


The above line just generates the reference code, but does not increment the sequence for the next sale order.


correct:

sequence.write({'number_next': next_sequence_number + 1})


After the reference_code is generated, we need to increment the sequence number. The line above ensures that the number_next field is updated to the next number in the sequence (ie, incremented by 1). This ensures that the sequence number progresses as expected.

We hope this helps! In case you need further assistance- you can reach out to us!

0
Avatar
Descartar
¿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
SO new section
sale sequence sale.order.line section V12
Avatar
0
sept 20
4291
How to detect if sale order is created from admin or from website? Resuelto
sale sequence order backend frontend
Avatar
1
oct 15
5502
Displaying Many2one field on mobile devices identical to desktop view in Odoo 17
Odoo17
Avatar
Avatar
1
jul 25
1779
Issue After Migration: Unable to Save Sales Order in v18 Resuelto
sale
Avatar
Avatar
1
may 25
2054
How to set serial numbers for the sale order line
sale
Avatar
Avatar
Avatar
2
feb 25
11052
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.

Sitio web hecho con

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