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 can I override the default_get method in account.payment?

Suscribirse

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

Se marcó esta pregunta
accountingpaymentinvoicingdefault_getodoo13
4 Respuestas
9996 Vistas
Avatar
Stephen

Hi,

I  need to override the default_get(self, default_fields) method in order to include a newly created state in the following warning in that function. How can I do that? Thanks in advance

if not invoices or any(invoice.state != 'posted' for invoice in invoices):
raise UserError(_("You can only register payments for open invoices"))

0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,

Try the following

from odoo import models, fields, api, _
from odoo.addons.account.models.account_payment import account_payment


class AccountPayment(models.Model):
_inherit = 'account.payment'


@api.model
def default_get(self, default_fields):
# You can write your modified lines of code here
rec = super(account_payment, self).default_get(default_fields)
return rec


account_payment.default_get = default_get

Regards

4
Avatar
Descartar
Avatar
limon SR
Mejor respuesta

Hello, I had the same problem yet this solution is not working 

here is my code 

I can't get to the print inside the if active_model == 'sale.order' 


class AccountPaymentNumidoo(models.Model):
_inherit = "account.payment"
# order_line_ids = fields.One2many('sale.order.line', 'payment_id', readonly=True, copy=False, ondelete='restrict')
order_ids = fields.Many2many('sale.order', 'account_order_payment_rel', 'payment_id', 'order_id',
string="Invoices", copy=False, readonly=True,
help="""Technical field containing the invoice for which the payment has been generated.
This does not especially correspond to the invoices reconciled with the payment,
as it can have been generated first, and reconciled later""")
mode_payment = fields.Selection([('especes', 'Espèces'),
('par_cheque', 'Par chèque'),
('virement_bancaire', 'Virement Bancaire'),
('versement', 'Versement Bancaire'),
('traite', 'Traite')])
@api.model
def default_get(self, default_fields):
rec = super(account_payment, self).default_get(default_fields)
active_ids = self._context.get('active_ids') or self._context.get('active_id')
active_model = self._context.get('active_model')
print(active_model)
# Check for selected invoices ids
if not active_ids or active_model != 'account.move' or active_model != 'sale.order':
return rec
if active_model == 'account.move':
invoices = self.env['account.move'].browse(active_ids).filtered(lambda move: move.is_invoice(include_receipts=True))
# Check all invoices are open
if not invoices or any(invoice.state != 'posted' for invoice in invoices):
raise UserError(_("You can only register payments for open invoices"))
# Check if, in batch payments, there are not negative invoices and positive invoices
dtype = invoices[0].type
for inv in invoices[1:]:
if inv.type != dtype:
if ((dtype == 'in_refund' and inv.type == 'in_invoice') or
(dtype == 'in_invoice' and inv.type == 'in_refund')):
raise UserError(
_("You cannot register payments for vendor bills and supplier refunds at the same time."))
if ((dtype == 'out_refund' and inv.type == 'out_invoice') or
(dtype == 'out_invoice' and inv.type == 'out_refund')):
raise UserError(
_("You cannot register payments for customer invoices and credit notes at the same time."))

amount = self._compute_payment_amount(invoices, invoices[0].currency_id, invoices[0].journal_id,
rec.get('payment_date') or fields.Date.today())
rec.update({
'currency_id': invoices[0].currency_id.id,
'amount': abs(amount),
'payment_type': 'inbound' if amount > 0 else 'outbound',
'partner_id': invoices[0].commercial_partner_id.id,
'partner_type': MAP_INVOICE_TYPE_PARTNER_TYPE[invoices[0].type],
'communication': invoices[0].invoice_payment_ref or invoices[0].ref or invoices[0].name,
'invoice_ids': [(6, 0, invoices.ids)],
})
else:
if active_model == 'sale.order':
print("i aaaaaaaaaaaa ma sale order")
orders = self.env['sale.order'].browse(active_ids).filtered(lambda move: move.is_sale_document(include_receipts=True))
amount=0
rec.update({
'currency_id': orders[0].currency_id.id,
'amount': abs(amount),
'payment_type': 'inbound',
'partner_id': orders[0].commercial_partner_id.id,
#'partner_type': MAP_INVOICE_TYPE_PARTNER_TYPE[invoices[0].type],
'communication': orders[0].order_payment_ref or orders[0].ref or orders[0].name,
'order_ids': [(6, 0, order.ids)],
})
return rec
account_payment.default_get = default_get
0
Avatar
Descartar
Avatar
Nikul Chaudhary
Mejor respuesta

Hello Stephen
Please check below example, I think it's helpful for you.

Ex.
@api.model
    def default_get(self, default_fields):
        rec = super(Order, self).default_get(default_fields)
        active_model = self.env.context.get('active_model', False)
        active_id = self.env.context.get('active_id', False)
        if active_model and active_id and active_model == 'sale.order':
            invoices = self.env['sale.order'].browse(active_id).invoice_ids
            if not invoices or any(invoice.state != 'posted' for invoice in invoices):
                raise UserError(_("You can only register payments for open invoices"))

0
Avatar
Descartar
Avatar
Pankaj Goyani
Mejor respuesta

@api.model
def default_get(self, default_fields):
    res = super(AccountPayment, self).default_get(default_fields)
    active_ids = self._context.get('active_ids')
    invoices = self.env['account.invoice'].browse(active_ids)
    communication = ' '.join([ref for ref in invoices.mapped('reference') if ref]),
    res.update({
       'communication': communication,
    })
    return res

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
Transfer Debit Between Customers
accounting payment invoicing debit
Avatar
0
mar 21
2662
Analytic Accounting in v17 Resuelto
accounting invoicing
Avatar
Avatar
Avatar
Avatar
3
jul 25
3989
Journal Entry PB-Tab/2025/00007 is not valid. In order to proceed, the journal items must include one and only one outstanding payments/receipts account.
accounting invoicing
Avatar
Avatar
1
mar 25
2426
Cannot post invoice with any invoice date set in January 2024 Resuelto
accounting invoicing
Avatar
Avatar
1
sept 25
2473
Comment savoir qu'une commande est entièrement facturée ? Resuelto
accounting invoicing
Avatar
Avatar
1
feb 25
2105
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