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

Field sales_count

Suscribirse

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

Se marcó esta pregunta
salesproductenterprisev15
2 Respuestas
3739 Vistas
Avatar
Kamran Lalehparvar

Hi

How can i have a filed like sales_count on product.product that showing sales on last 180 days and 90 days ago instead of 365 days ago ?

thank you in advance

0
Avatar
Descartar
Avatar
Alexandre Sousa
Mejor respuesta

Hi Kamran,

You can start by creating a new smart button in the product, for that, I suggest you extend the xml of the product. 

Here is the standard xml that creates the standard button (365 days) you can use it as a base to create your own button:


model="ir.ui.view" id="product_form_view_sale_order_button">
name="name">product.product.sale.order
name="model">product.product
name="inherit_id" ref="product.product_normal_form_view"/>
name="groups_id" eval="[(4, ref('sales_team.group_sale_salesman'))]"/>
name="arch" type="xml">
name="button_box" position="inside">


name="description" position="after">
string="Warning when Selling this Product" groups="sale.group_warning_sale">
name="sale_line_warn" nolabel="1"/>
name="sale_line_warn_msg" colspan="3" nolabel="1"
attrs="{'required':[('sale_line_warn','!=','no-message')],'readonly':[('sale_line_warn','=','no-message')]}"/>





** of course you must create also your own custom field  sales_count and calculate it using a compute function

Then you just need to create a new action in the product by extending the py of the product.

Here is the standard action to open the sales of the last 365 days:


def action_view_sales(self):
action = self.env.ref('sale.report_all_channels_sales_action').read()[0]
action['domain'] = [('product_id', 'in', self.ids)]
action['context'] = {
'pivot_measures': ['product_uom_qty'],
'active_id'
: self._context.get('active_id'),
'search_default_Sales'
: 1,
'active_model'
: 'sale.report',
'time_ranges'
: {'field': 'date', 'range': 'last_365_days'},
}
return action


Here is the tricky part: if you don't calculate the domain in python you must create a new filter in the search portion of the xml, so then you can call this new filter in the action by passing its name by context.

Hope it helps you to get started.

1
Avatar
Descartar
Kamran Lalehparvar
Autor

Hi Alexander
Thank you for your reply unfortunately I’m not that much technical i was wondering if you make it a little more clear

Alexandre Sousa

Hi Kamran, I've included more details in the answer, hope that helps in giving you a better direction.

Kamran Lalehparvar
Autor

Alexander
Thank you 🙏
Can i have the code for compute custom filed ? And one more thing can i use server action instead of extend py code ? If yes please kindly describe it a little more
Thank you in advance

Alexandre Sousa

Hi Kamran,
Here is the code for the field:
sales_count = fields.Float(compute='_compute_sales_count', string='Sold')
def _compute_sales_count(self):
r = {}
self.sales_count = 0
if not self.user_has_groups('sales_team.group_sale_salesman'):
return r
date_from = fields.Datetime.to_string(fields.datetime.combine(fields.datetime.now() - timedelta(days=365),
time.min))

done_states = self.env['sale.report']._get_done_states()

domain = [
('state', 'in', done_states),
('product_id', 'in', self.ids),
('date', '>=', date_from),
]
for group in self.env['sale.report'].read_group(domain, ['product_id', 'product_uom_qty'], ['product_id']):
r[group['product_id'][0]] = group['product_uom_qty']
for product in self:
if not product.id:
product.sales_count = 0.0
continue
product.sales_count = float_round(r.get(product.id, 0), precision_rounding=product.uom_id.rounding)
return r

If you are still having problems modifying this I suggest you get started with the tutorials on the Odoo website.

Avatar
Farooq Rajput
Mejor respuesta

in product.template

sales_count_custom = fields.Float(compute='_compute_sales_count_custom',string='90 Days Sale')


@api.depends('product_variant_ids.sales_count_custom')    def_compute_sales_count_custom(self):        for product inself:            product.sales_count_custom =float_round(sum([p.sales_count_custom for p in product.with_context(active_test=False).product_variant_ids]),precision_rounding=product.uom_id.rounding)        defaction_view_sales_custom(self):        action =self.env["ir.actions.actions"]._for_xml_id("sale.report_all_channels_sales_action")        action['domain']=[('product_id','in',self.ids)]        action['context']={            'pivot_measures':['product_uom_qty'],            'active_id':self._context.get('active_id'),            'search_default_Sales':1,            'active_model':'sale.report',            'time_ranges':{'field':'date','range':'last_90_days'},        }        return action


in view 


  <xpathexpr="//div[@name='button_box']"position="inside">                    <buttonclass="oe_stat_button"name="action_view_sales_custom"                        type="object"icon="fa-bar-chart-o"groups="sales_team.group_sale_salesman"help="Sold in the last 90 days"attrs="{'invisible': [('sale_ok', '=', False)]}">                        <divclass="o_field_widget o_stat_info">                            <spanclass="o_stat_value">                                <fieldname="sales_count_custom"widget="statinfo"nolabel="1"class="mr4"/>                                <fieldname="uom_name"/>                            span>                            <spanclass="o_stat_text">90 Daysspan>                        div>                    button>                xpath>

0
Avatar
Descartar
Farooq Rajput

it will work for 90 days. cheers . after looking at this , you can make 180 days one aswell.

¿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
How do i edit odoo default product view?
sales product odoo v15
Avatar
Avatar
Avatar
2
ene 24
4566
Conditionally show or hide product attributes (Odoo Online/Studio)
sales product
Avatar
Avatar
1
oct 25
643
Hide the cost
sales product
Avatar
Avatar
Avatar
2
may 25
4483
Products in multi company
sales product
Avatar
0
nov 24
1510
how to filter out all products which got no sales with the last 3 months or a specific period?
sales product
Avatar
Avatar
1
ago 24
2327
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