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
    • e-learning
    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
    • Conocimientos
    • 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 pub
    • 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
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • 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
    Explorar todos los sectores
  • 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
    • Servicios para 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

How to override def _amount_all(self, cr, uid, ids, field_name, arg, context=None): from Purchase order form odoo 8

Suscribirse

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

Se marcó esta pregunta
2 Respuestas
8479 Vistas
Avatar
ABU K

Hi all,

edited:16/2/2014

 I am facing some  issues in Purchase order customization module  ,issues are ..

1)     My custom Purchase order total amount is not reflected in the Accounting ,Supplier Invoices ...
2)    If I fill the Purchase order line first , after that I enter my extra cost(custom field) value then my Total in the Purchase order          line is not updated But If I enter my extra cost first ,then fill the purchase order line .It is working fine and Updated the Total

3)   If I add one more products into my purchase order line then  it automatically adds value from my previous  subtotal value( value of  price_subtotal from the previous line..)

4)  If I press Confirm order button then again update the amount_total  with previous price_subtotal value from Purchase Order 

How to solve these issuess...

Here is my code-----------

.py file---

from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp


class purchase_order(osv.osv):
    _name='purchase.order'
    _inherit = 'purchase.order'
    
    def _calculate_total_amount(self, cr, uid, ids, context=None):
        total=0.0
        for cost in self.browse(cr, uid, ids, context=context):
            total = 0.00
            for line in cost.freight_ids:
                total += line.cost                    
            return total


    def _total_amount(self, cr, uid, ids, name, args, context=None): 
        result={}        
        for cost in self.browse(cr, uid, ids, context=context):
            result[cost.id] =self._calculate_total_amount(cr, uid, ids, context)
        return result
        
    def _amount_all(self, cr, uid, ids, field_name, arg, context=None):  
        print "Test########################"
      
        res = {}
        cur_obj=self.pool.get('res.currency')
        for order in self.browse(cr, uid, ids, context=context):
            res[order.id] = {
                'amount_untaxed': 0.0,
                'amount_tax': 0.0,
                'amount_total': 0.0,
            }
            val = val1 = 0.0
            cur = order.pricelist_id.currency_id
            for line in order.order_line:
               val1 += line.price_subtotal
               for c in self.pool.get('account.tax').compute_all(cr, uid, line.taxes_id, line.price_unit, line.product_qty, line.product_id, order.partner_id)['taxes']:
                    val += c.get('amount', 0.0)
            res[order.id]['amount_tax']=cur_obj.round(cr, uid, cur, val)
            res[order.id]['amount_untaxed']=cur_obj.round(cr, uid, cur, val1)
        res = super(purchase_order, self)._amount_all(cr, uid, ids, field_name, arg, context)
        amount_subtotal=self._calculate_total_amount(cr, uid, ids, context)
        for order in self.browse(cr, uid, ids, context=context):
            
            res[order.id]['amount_total'] += amount_subtotal+order.amount_untaxed
        return res
    
    def _get_order(self, cr, uid, ids, context=None):
        result = {}
        for line in self.pool.get('purchase.order.line').browse(cr, uid, ids,
                                                                context):
            result[line.order_id.id] = True
        return result.keys()
    

 

    _columns={
              
            'freight_ids':fields.one2many('freight.cost','cost_id','Extra Cost Details'),
            'amount_subtotal': fields.function(_total_amount, type='float', string='Total',store=True),
            'amount_untaxed': fields.function(_amount_all, method=True,
            digits_compute=dp.get_precision('Account'),
            string='Untaxed Amount',
            store={
                'purchase.order.line': (_get_order, None, 10),
            }, multi="sums", help="The amount without tax"),
        'amount_tax': fields.function(_amount_all, method=True,
            digits_compute=dp.get_precision('Account'), string='Taxes',
            store={
                'purchase.order.line': (_get_order, None, 10),
            }, multi="sums", help="The tax amount"),
        'amount_total': fields.function(_amount_all, method=True,
                digits_compute=dp.get_precision('Account'), string='Total',
            store={
                'purchase.order.line': (_get_order, None, 10),
                }, multi="sums", help="The total amount"),
        'amount_untaxed': fields.function(_amount_all,
            digits_compute=dp.get_precision('Account'),
            string='Untaxed Amount',
            store={
                'purchase.order.line': (_get_order, None, 10),
            }, multi="sums", help="The amount without tax",
            track_visibility='always'),
        'amount_tax': fields.function(_amount_all,
            digits_compute=dp.get_precision('Account'), string='Taxes',
            store={
                'purchase.order.line': (_get_order, None, 10),
            }, multi="sums", help="The tax amount"),
        'amount_total': fields.function(_amount_all,
            digits_compute=dp.get_precision('Account'), string='Total',
            store={
                'purchase.order.line': (_get_order, None, 10),
            }, multi="sums", help="The total amount"),
    
                            }
    
    def dummy(self, cr, uid, ids, context=None):
        print "DDDDDDDDDDDDDDDD"
        return True
    


    
   
class freight_cost(osv.osv):
    
    _name='freight.cost'
    
    _columns={
              'cost_id':fields.many2one('purchase.order','name'),
              'name':fields.char('Name',size=64),
              'cost':fields.float('Price'),
              'description':fields.char('Description')
              }
    
    
    

.xml file--------

<record id="freight_tree_view" model="ir.ui.view">
                <field name="name">freight.cost.tree</field>
                <field name="model">freight.cost</field>
                <field name="arch" type="xml">
                    <tree string="Freight Cost tree">                                    
                        <field name="name"/>
                        <field name="cost"/>
                        <field name="description"/>
                        
                    </tree>
                </field>    
    </record>
    
        <record id="freight_form_view" model="ir.ui.view">
                        <field name="name">freight.cost.form</field>
                        <field name="model">freight.cost</field>
                        <field name="arch" type="xml">
                            <form string="Freight Cost form ">                                    
                                <group><field name="name"/>
                        <field name="cost"/>
                        <field name="description"/></group>
                            </form>
                        </field>    
        </record>
            
        <record model="ir.ui.view" id="purchase_freight_order_form">
         <field name="name">purchase.freight.order.form</field>
         <field name="model">purchase.order</field>
         <field name="type">form</field>
         <field name="inherit_id" ref="purchase.purchase_order_form"/>
         <field name="arch" type="xml">
              <xpath expr="/form/sheet/notebook/page[@string='Products']" position="after">
                  <page string="Freight Charges">
                <field name="freight_ids" colspan="4" />
            </page>
                 </xpath>
         </field>
     </record>

 

0
Avatar
Descartar
Avatar
Sea
Mejor respuesta

Hi,

The problem here looks like, you are trying to use a functional field which will be evaluated after the save along with other functional fields.

res[order.id]['amount_total'] += order.amount_subtotal+order.amount_untaxed --> for this line, you have to calculate the value for amount_subtotal field in  _amount_all method instead of taking it from order.amount_subtotal.

def _amount_all(self, cr, uid, ids, field_name, arg, context=None):   #This code is not working and ,is this calculation is crct?
        print "Test########################"
        res = super(purchase_order, self)._amount_all(cr, uid, ids, field_name, arg, context)
        for order in self.browse(cr, uid, ids, context=context):
            res[order.id]['amount_total'] += order.amount_subtotal+order.amount_untaxed --> calculate the value for amount_subtotal in this method. don't take from order. It does not have any value by this time
        return res

 

Hi , LIBU

Try this out:

 

    def _calculate_total_amount(self, cr, uid, ids, context=None): #This is My calculation for find the extra cost of a single #purchase
        total=0.0
        for cost in self.browse(cr, uid, ids, context=context):
            total = 0.00
            for line in cost.freight_ids:
                total += line.cost                    
            return total


    def _total_amount(self, cr, uid, ids, name, args, context=None): #This is My calculation for find the extra cost of a single #purchase
        result={}        
        for cost in self.browse(cr, uid, ids, context=context):
            result[cost.id] =self._calculate_total_amount(cr, uid, ids, context)
        return result
        
    def _amount_all(self, cr, uid, ids, field_name, arg, context=None):  
        print "Test########################"
        res = super(purchase_order, self)._amount_all(cr, uid, ids, field_name, arg, context)
        amount_subtotal=self._calculate_total_amount(cr, uid, ids, context)
        for order in self.browse(cr, uid, ids, context=context):
            
            res[order.id]['amount_total'] += amount_subtotal+order.amount_untaxed
        return res

0
Avatar
Descartar
ABU K
Autor

Hi I can get the idea But then How to change my code for calculate the value for amount_subtotal in this method ?

Sea

Hi , LIBU Try this out: def _calculate_total_amount(self, cr, uid, ids, context=None): #This is My calculation for find the extra cost of a single #purchase total=0.0 for cost in self.browse(cr, uid, ids, context=context): total = 0.00 for line in cost.freight_ids: total += line.cost return total def _total_amount(self, cr, uid, ids, name, args, context=None): #This is My calculation for find the extra cost of a single #purchase result={} for cost in self.browse(cr, uid, ids, context=context): result[cost.id] =self._calculate_total_amount(cr, uid, ids, context) return result def _amount_all(self, cr, uid, ids, field_name, arg, context=None): print "Test########################" res = super(purchase_order, self)._amount_all(cr, uid, ids, field_name, arg, context) amount_subtotal=self._calculate_total_amount(cr, uid, ids, context) for order in self.browse(cr, uid, ids, context=context): res[order.id]['amount_total'] += amount_subtotal+order.amount_untaxed return res

ABU K
Autor

Hi Sea,......first thanks for your answers..and your last answer is working fine.But Some issues in that code. I rewrite my question in the begining..can u please..check..thanks one more time...

ABU K
Autor

I have 3 issues , If I fill the Purchase order line first , after that I enter my extra cost(custom field) value then my Total in the Purchase order line is not updated But If I enter my extra cost first ,then fill the purchase order line .It is working fine and Updated the Total Second Problem is If I add one more products into my purchase order line then two time adds my subtotal value(douled the value of subtotal from the previous line..) Third problem is If I press Confirm order button then again update the Total from Purchase Order

ABU K
Autor

These are the issues..How to resolve this issues

Avatar
Atchuthan - Technical Consultant, Sodexis Inc
Mejor respuesta

calling super method works within a functional field definition
check code here: https://github.com/OCA/stock-logistics-warehouse/blob/7.0/stock_available_immediately/product.py#L52

The code changes you have made only affects for newly created Purchase order and does not affect old Purchase order.  The reason is that in the functional field, we have set it to only re-compute the field if Purchase order line is modified.

store={
      'purchase.order.line': (_get_order, None, 10),
}

NOTE:
If a computation is dependent on another functional field, then use multi to do the computation at once and not two independent functions

    def _amount_all(self, cursor, user, ids, field_name, arg, context = None):

        if context is None:
            context = {}
        res = {}
        res = super(SaleOrder, self)._amount_all(cursor, user, ids, field_name, arg, context)

        for order in self.browse(cursor, user, ids):
            total = 0.00
            for line in cost.freight_ids:
                total += line.cost
            res[order.id]['markup_rate'] = total
        return res

'amount_subtotal': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Sub Total',
            store={
                'purchase.order.line': (_get_order, None, 10),
            }, multi="sums"),

0
Avatar
Descartar
Atchuthan - Technical Consultant, Sodexis Inc

does your code work for new PO?

ABU K
Autor

no this amount_subtotal... is not in the purchase order line can you check my xml file ,then u can understand...please help,I want to calculate the untaxed amount with my custom field('amount_subtotal') ,thats my aim .when I click on the save or update button..

ABU K
Autor

that means,Untaxed Amount = Total of subtotal field+ amount_subtotal(my custom field)

ABU K
Autor

before the tax calculation

Atchuthan - Technical Consultant, Sodexis Inc

check now

ABU K
Autor

I Tried but no solution..

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
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 empresariales de código abierto que cubre 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.

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