Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

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

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

Check if invoice has paid and change state on other module

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
invoiceinvoice_statestatepaidv14
2 Respostas
9507 Visualizações
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
Cancelar
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 Melhor resposta

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
Cancelar
Avatar
Niyas Raphy (Walnut Software Solutions)
Melhor resposta

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
Cancelar
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?

Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
Sales orders stay "in progress" after the invoice is paid
invoice state paid
Avatar
1
mar. 15
11049
AttributeError("The 'Customer' object does not have the 'create_message' attribute") Resolvido
invoice v14
Avatar
Avatar
1
abr. 24
2648
how to create customer invoice from code odoo 14 Resolvido
invoice v14
Avatar
Avatar
Avatar
Avatar
3
out. 23
9093
Manual Invoice Sequence Resolvido
invoice v14
Avatar
Avatar
1
set. 21
3997
How to validate the invoice invoice? Resolvido
invoice invoice_state
Avatar
Avatar
1
out. 17
4603
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة 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 é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

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