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

V19: Create Scheduled Actions

Suscribirse

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

Se marcó esta pregunta
2 Respuestas
227 Vistas
Avatar
Benoit Vanasse

Hello and thank you for taking the time to review my post.

I would like to preface that I know a little about coding but not much, I am trying to configure my own Odoo for my small business.

I have to do maintenance on Equipment for my clients at set intervals (typically 3 month interval).

I would like to set Activity to remind myself to create the maintenance task. I do not wish to create the task automatically because those maintenance are often pushed to a later date by my customers.

With Studio, I added the following fields:

  • Date field : to display the next planned maintenance date
  • Integer field : to display the desired interval for maintenance (default 3)
I went to Scheduled Action and created a new action.
I set the Model to "Maintenance Equipment" which is where I keep my Equipment data.
The action is set to execute every 1 day.

I tried to get a code from GPT to run Action and create an automatic Activity everyday and then increase the value of the Date field by the number of months in the Integer field.

The code saves but when I try to run it manually, I do not see any added Activities being generated. Could anyone help me fix this code please?

Thank you!
Ben

Code:

# Get today's date using Odoo's fields helper
today = fields.Date.today()

# Find all equipment whose next PM date is today or earlier
to_process = records.filtered(
    lambda r: r.x_studio_next_pm_date and r.x_studio_next_pm_date <= today
)

for rec in to_process:
    # Create a reminder activity (admin must create PM task manually)
    env['mail.activity'].create({
        'res_model_id': env['ir.model']._get_id(rec._name),
        'res_id': rec.id,
        'activity_type_id': env.ref('mail.mail_activity_data_todo').id,
        'summary': "PM due for %s" % rec.name,
        'note': "Time to review this equipment and create a Field Service task if needed.",
        'date_deadline': today,
        'user_id': 11,  # put the correct user ID here
    })

    # Reschedule next PM date (use Odoo's Date.add, no import)
    freq = rec.x_studio_pm_frequency or 3
    next_date = fields.Date.add(rec.x_studio_next_pm_date, months=freq)

    # Use write() instead of direct assignment
    rec.write({
        'x_studio_next_pm_date': next_date,
    })


0
Avatar
Descartar
Codesphere Tech

Hello,
Try this:
to_process = model.search([
('x_studio_next_pm_date', '<=', today),
('x_studio_next_pm_date', '!=', False)
])

Benoit Vanasse
Autor
Thank you for the suggestion!

I read this updated code and still I did not get any activities generated. :(

Code:

# Get today's date using Odoo's fields helper
today = fields.Date.today()

# Find all equipment whose next PM date is today or earlier
to_process = model.search([
('x_studio_next_pm_date', '<=', today),
('x_studio_next_pm_date', '!=', False)
])

for rec in to_process:
    # Create a reminder activity (admin must create PM task manually)
    env['mail.activity'].create({
        'res_model_id': env['ir.model']._get_id(rec._name),
        'res_id': rec.id,
        'activity_type_id': env.ref('mail.mail_activity_data_todo').id,
        'summary': "PM due for %s" % rec.name,
        'note': "Time to review this equipment and create a Field Service task if needed.",
        'date_deadline': today,
        'user_id': 11,  # put the correct user ID here
    })

    # Reschedule next PM date (use Odoo's Date.add, no import)
    freq = rec.x_studio_pm_frequency or 3
    next_date = fields.Date.add(rec.x_studio_next_pm_date, months=freq)

    # Use write() instead of direct assignment
    rec.write({
        'x_studio_next_pm_date': next_date,
    })


Avatar
Kunjan Patel
Mejor respuesta
Hello Benoit Vanasse,
I hope you are doing well

Quick Fix for Odoo v19 Scheduled Actions
1. Search returns no records - verify equipment actually has x_studio_next_pm_date <= today
2.Missing required fields in activity creation - need res_model_id and user_id

Working Code:
  from datetime import date
  from dateutil.relativedelta import relativedelta

  today = date.today()
  equipment = env['maintenance.equipment'].search([
      ('x_studio_next_pm_date', '<=', today)
  ])
  for rec in equipment:
      env['mail.activity'].create({
          'res_model_id': env['ir.model']._get('maintenance.equipment').id,
          'res_id': env.user.id,
      })

      interval = rec.x_studio_pm_interval or 3
      rec.write({
          'x_studio_next_pm_date': today + relativedelta(months=interval)
      })

Debug: Check server logs after "Run Manually" to see if records are found.


I hope this information helps you

Thanks & Regards,
Kunjan Patel

0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta
Hi,
To create a scheduled action in Odoo v19:

    First, activate Developer Mode.

    Then go to Settings → Technical → Automation → Scheduled Actions.

    Click New. Fill in:

        Name — give a clear title.

        Model — choose which model the action should run on (for example: sale.order, stock.move, or a custom model).

        Action — choose “code” if you want to run a Python method of the model, and in the Code field write something like:
        model.your_method_name()

        Interval — define how often it runs (e.g. every 1 day, 1 hour, etc).

        Next Execution Date, Number of Calls (e.g. -1 for infinite).

    Save the scheduled action — if “Active” is checked, Odoo will run it automatically according to schedule.

If you need to test it immediately, you can hit Run Manually from the Scheduled Actions list (in developer mode) to trigger it right away.


Hope it helps

-2
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

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

Registrarse
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