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
    • Información
    • 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

Check if invoice has paid and change state on other module

Suscribirse

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

Se marcó esta pregunta
invoiceinvoice_statestatepaidv14
2 Respuestas
9554 Vistas
Avatar
Tri Nanda

I use Odoo14 community version,

I have a custom module that can create an invoice for student course registration, here is the code to create student invoice:

def create_invoice(self):
invoice = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.student_id.partner_id.id,
'invoice_line_ids': (
{
'product_id': self.course_id.product_id,
'quantity': 1,
'price_unit': self.course_id.product_id.lst_price,
'tax_ids': False
},
{
'product_id': self.subject_ids.product_id,
'quantity': 1,
'price_unit': self.subject_ids.product_id.lst_price,
'tax_ids': False
}
)
})
and I also have state for the student status, here is the code:
state = fields.Selection(string="Student Status", selection=[
('waiting', 'Waiting List'),
('has_been_contacted', 'Has been Contacted'),
('payment_process', 'Payment Process'),
('registered_student', 'Registered'),
('active_student', 'Active Student'),
('unactive_student', 'Unactive Student'),
], default='waiting')
when we triggered the create_invoice method on a button, the state will move to payment_process.


Now, I want if the created invoice payment state is paid, wether my user is access the invoice from my custom module or directly from Invoice/Accounting module, I want the state on my module is move automatically to registered_student.


My question are, how to do that?

Any help, source or tutorial how to do that will be very appreciated,


Edit:


I also create a field to save the registration ID on my models:

class AqurStudentCourse(models.Model):
    _name = "aqur.student.course"
    registration_invoice_id = fields.Integer(string='Registration Invoice ID')

Then I insert value on the registration_invoice_id when I create invoice:


def create_invoice(self):
invoice = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.student_id.partner_id.id,
# 'invoice_date': date_invoice,
'invoice_line_ids': (
{
'product_id': self.course_id.product_id,
'quantity': 1,
'price_unit': self.course_id.product_id.lst_price,
'tax_ids': False
},
{
'product_id': self.subject_ids.product_id,
'quantity': 1,
'price_unit': self.subject_ids.product_id.lst_price,
'tax_ids': False
}
)
})
self.registration_invoice_id = invoice.id

Here is the screenshot how I create the invoice from button:

When I create the Registration Fee button, it will create an invoice, then the state will move to Payment Process. And here is the created invoice:

Now , I want if the field invoice_payment_state from the  account.move  model if the  status  has been paid:


I want the state from my custom module automatically change to registered_student:



I try to apply the overide function code that suggest by @Niyas, here is the code:


def write(self, vals):
invoice_payment_state = self.env['account.move'].search(
[('partner_id.id', '=', self.student_id.partner_id.id), ('id', '=', self.registration_invoice_id),
('payment_state', '=', 'paid')])
if 'state' in vals and vals['state']:
if invoice_payment_state.payment_state:
self.state = 'registered_student'
return super(AqurStudentCourse, self).write(vals)
I call the above function from my AqurStudentCourse model, and I got the result from  the    invoice_payment_state.


But, when I test the function how  it  works, nothings is happen on my student course state when I try to Register Payment on the  Invoice and get the Invoice status to Paid.


Even, I got this error message when I try to change the state manually:

Traceback (most recent call last):
  File "/opt/odoo/odoo14/odoo/http.py", line 640, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo14/odoo/http.py", line 316, in _handle_exception
    raise exception.with_traceback(None) from new_cause
RecursionError: maximum recursion depth exceeded while calling a Python object
So, what is wrong with my overide method?

Please, any help would be very appreciated.


Thank you,

Tri Nanda


EDIT 2:


I try to override the AccountMove models now with this code:


class AccountMove(models.Model):
_inherit = "account.move"

def write(self, vals):
student_course_registration_id = self.env['aqur.student.course'].search(
[('registration_invoice_id', '=', self.id)])

course_registration_status = self.env['account.move'].search(
[('id', '=', student_course_registration_id.registration_invoice_id)])

if course_registration_status.payment_state == 'paid':
self.env['aqur.student.course'].search(
[('registration_invoice_id', '=', course_registration_status.id)]).write(
{'state': 'registered_student'})

return super(AccountMove, self).write(vals)
but, nothing is happen when the invoice has paid, the student course state still not update anythings, is there anothers solutions?


Thanks,

Tri Nanda

0
Avatar
Descartar
Tri Nanda
Autor

Yes @Niyas, I try that logic, but doesnt affect anything, may you sugges me other way with other example code?, or source or tutorial how to do that?, thank you Niyas

Avatar
Tri Nanda
Autor Mejor respuesta

Finaly I solved this by this following code:

class AccountMove(models.Model):
_inherit = "account.move"

def write(self, vals):
# student_course_registration_id = self.env['aqur.student.course'].search(
# [('registration_invoice_id', '=', self.id) or ('tuition_fee_id', '=', self.id)])

invoice_course = self.env['account.move'].search(
[('name', '=', self.ref)])

if invoice_course.payment_state == 'paid' and self.env['aqur.student.course'].search(
[('registration_invoice_id', '=', invoice_course.id)]):
self.env['aqur.student.course'].search(
[('registration_invoice_id', '=', invoice_course.id)]).write(
{'state': 'registered_student'})

if invoice_course.payment_state == 'paid' and self.env['aqur.student.course'].search(
[('tuition_fee_id', '=', invoice_course.id)]):
self.env['aqur.student.course'].search(
[('tuition_fee_id', '=', invoice_course.id)]).write(
{'state': 'active_student'})

return super(AccountMove, self).write(vals)
Thank you @Niyas and who have help me, the Niyas answer in this thread really help and give  my  insight  to  face  this .


0
Avatar
Descartar
Avatar
Niyas Raphy (Walnut Software Solutions)
Mejor respuesta

Hi,
if you have kept some relation with your model and invoice it will be easy, you can override the write method of invoice, then check the status, whether it going to paid state, if yes, you can update the original source record to the required state.

Sample Code:

def write(self, vals):
if 'state' in vals and vals['state']:
if vals['state'] == 'paid':
if self.source_field:
#assuming source field is a many2one field
self.source_field.state = 'new_state'
return super(AccountMove, self).write()

Thanks

0
Avatar
Descartar
Tri Nanda
Autor

Hi Niyas, thank you for the respon,

I got this error Niyas:
`NameError: name 'AccountMove' is not defined`

then I add `@api.model` on the above of function, but getting the new error:
`TypeError: write() takes 2 positional arguments but 3 were given`

may you give suggestion how to handle the error Niyas?

Thanks,
Tri Nanda

Niyas Raphy (Walnut Software Solutions)

`NameError: name 'AccountMove' is not defined`, for this instead of AccountMove you have to specify your classname.

then return super(AccountMove, self).write()
to return super(AccountMove, self).write(vals)

Tri Nanda
Autor

Hi Niyas, am still new on Odoo development, may you specify more details how to do that NIyas?

I found `invoice_payment_state` on "account.move" models, that is the field that store the "paid" status if customer register they payment to paid total,

I want to change my state on my custom module that I have defined above.

I have try to approach your example code Niyas, but still confuse, may you help clarify more details Niyas, please?

Niyas Raphy (Walnut Software Solutions)

For overriding the write function in odoo, see: https://www.youtube.com/watch?v=v8sXFUi1SH4&t=1s

Tri Nanda
Autor

Hi @Niyas, I try to update my questions, may you help my to give solutions, please?

Niyas Raphy (Walnut Software Solutions)

instead of overiding write method of custom module, override the write method of invoice model and then update your record

Tri Nanda
Autor

Hi @Niyas, I override the AccountMove models now, but nothing is happen?, is there any solutions Niyas, Please?

Niyas Raphy (Walnut Software Solutions)

Did you applied the logic like if the newly writing state in account move is paid, then did you tried updating the other record ?

Tri Nanda
Autor

Yes @Niyas, I that logic, but doesnt affect anything, may you sugges me other way with other example code?, or source or tutorial how to do that?, thank you Niyas

Tri Nanda
Autor

Hello @Niyas, how is it going?, I hope you doing well,

after keep trying in this, finally I can change my state on my other module if my invoice is paid Niyas, but that just if my invoice amount/total of payment is 0 Niyas,

there can't update my state on my other module if the created invoice amount or total is there is a price.

may you help me Niyas, please?

¿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
Sales orders stay "in progress" after the invoice is paid
invoice state paid
Avatar
1
mar 15
11074
AttributeError("The 'Customer' object does not have the 'create_message' attribute") Resuelto
invoice v14
Avatar
Avatar
1
abr 24
2686
how to create customer invoice from code odoo 14 Resuelto
invoice v14
Avatar
Avatar
Avatar
Avatar
3
oct 23
9147
Manual Invoice Sequence Resuelto
invoice v14
Avatar
Avatar
1
sept 21
4020
How to validate the invoice invoice? Resuelto
invoice invoice_state
Avatar
Avatar
1
oct 17
4612
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