cundi / blog

push issues as a blog
2 stars 0 forks source link

在Odoo中创建自动动作[翻译] #41

Open cundi opened 8 years ago

cundi commented 8 years ago

原文链接:http://www.odoo.yenthevg.com/creating-automated-actions-in-odoo/

Creating automated actions in Odoo

NOVEMBER 14, 2015YENTHE666

Hi guys,

In this tutorial I will learn you how to create and manage automated actions, which are also known as schedulers. Schedulers are automated actions that run automatically over a time period and can do a lot of things. They give you the ability to execute actions on your database without needing manual interaction.

In this example I will create an automated action that runs every 2 minutes and which loops over all records on the database table (scheduler.demo). Every record on this model will keep track of how many times the scheduler ran over it, just to show to you how automated actions work in combination with database actions.

1. Creating the model and fields

The first step is to create a model (if you don’t have one yet) and to create some fields on this model:

class scheduler_demo(models.Model):
    _name = 'scheduler.demo'
    name = fields.Char(required=True)
    numberOfUpdates = fields.Integer('Number of updates', help='The number of times the scheduler has run and updated this field')
    lastModified = fields.Date('Last updated')

This will create a new model named ‘scheduler.demo’ which will contain three fields: a text field for the name, an integer field to keep track of how many times the record was updated and a date field. This is all you need on the database level. You have your fields in the database so you only need to show them to the user now!

2. Creating the views

Now that you have the database part ready it is time to create your view. In this example I will create a simple form view and tree view which shows the fields ‘name’, ‘numberOfUpdates’ and ‘lastModified’ that we just created in our model:

<!-- Form view -->
<record id="view_scheduler_record_form" model="ir.ui.view">
    <field name="name">scheduler.demo.form</field>
    <field name="model">scheduler.demo</field>
    <field name="arch" type="xml">
        <form string="Schedule record">
        <group>
        <field name="name"/>
        <field name="numberOfUpdates"/>
        <field name="lastModified"/>
            </group>
        </form>
    </field>
</record>

<!-- tree (list) view-->
<record id="view_scheduler_tree" model="ir.ui.view">
    <field name="name">scheduler.demo.tree</field>
    <field name="model">scheduler.demo</field>
    <field name="arch" type="xml">
        <tree string="Schedule records">
        <field name="name"/>
        <field name="numberOfUpdates"/>
        <field name="lastModified"/>
        </tree>
    </field>
</record>

3. Creating the automated action

Now that we’ve created the models and the views we need an automated action that will run automatically with a specific interval.

Tip: If you want to build new modules in the guidelines from Odoo you should add the code for an automated action under yourDefaultModule/data/ in a separate XML file.

An important thing to note with automated actions is that they should always be defined within a noupdate field since this shouldn’t be updated when you update your module. So let us create an automated action that runs every 2 minutes that keeps running over and over again for the model ‘schedule.demo’. A last criteria is that the automated action calls a Python function from where we can do our operations on the database. The result:

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data noupdate="1">
        <record id="ir_cron_scheduler_demo_action" model="ir.cron">
            <field name="name">Demo scheduler</field>
            <field name="user_id" ref="base.user_root"/>
            <field name="interval_number">2</field>
            <field name="interval_type">minutes</field>
            <field name="numbercall">-1</field>
            <field eval="False" name="doall"/>
            <field eval="'scheduler.demo'" name="model"/>
            <field eval="'process_demo_scheduler_queue'" name="function"/>
        </record>
   </data>
</openerp>

When you would install your module this would give the following automated action:

Automated action example

3.1 DIVING DEEPER INTO THE AUTOMATED ACTION

Lets break down the code step by step so that we know exactly what it does. If you don’t want to read this you can scroll down to chapter 4.

The first thing you’ll notice is the data noupdate=”1″, this is telling Odoo that all code within this tag shouldn’t be updated when you update your module. The next thing you’ll notice is the record id and model.

<record id="ir_cron_scheduler_demo_action" model="ir.cron">
</record>

The id is an unique identifier for Odoo to know what record is linked to which id. The model called (‘ir.cron’) is the model specifically made by Odoo for all automated actions. This model contains all automated actions and should always be specified.

<field name="name">Demo scheduler</field>

The next line is the name. This name will be shown on the automated action and is what the user will see.

<field name="user_id" ref="base.user_root"/>

The next line is the ‘user_id’. This user id is referring to a specific user, in most cases this will be base.user_root. Why? This is the user where the automated action is executed with and when you use the root account you’re always sure you have acces rights to everything!

<field name="interval_number">2</field>

The next line is the ‘interval_number’. The interval_number is always a number and will tell you how often the automated action should run. In this example it will run every 2 … The next line then specified is the ‘interval_type’ which is telling you how often you want to run the ‘interval_number’. When we look at the next line:

<field name="interval_type">minutes</field>

The line ‘interval_number’ and ‘interval_type’ are always combined and give you an exact timing on how often the automated action should be run. In this example the automated action will run every 2 minutes. Tip: the options for ‘interval_type’ are ‘minutes’,’hours’,’days’, ‘work_days’,’weeks’ and ‘months’. The next line is the field ‘numbercall’:

<field name="numbercall">-1</field>

This field tells Odoo how often this automated action should be run. If you would fill in ’10’ then the action would run 10 times. When you want it to run forever you simply fill in ‘-1’.

<field eval="False" name="doall"/>

The next line, ‘doall’ has two options: True or False. When the field is set to False you’re telling Odoo that missed automated actions should be executed when the server restarts if they where missed (for example when a server has been down for 24 hours then the planner would need to run the scheduler for every time it was missed in those 24 hours).

<field eval="'scheduler.demo'" name="model"/>

The field ‘model’ specifies on which model the automated action should be called, it is as simple as that! Now for the last line:

<field eval="'process_demo_scheduler_queue'" name="function"/>

This line is telling Odoo that it should call a function with the name ‘process_demo_scheduler_queue’ from the Python file. So this is the link to your Python and this again gives us the ability to acces the database.

Congratulations, you now know how automated actions work!

4. Adding the Python function

Alright, we’re almost done! There is just one more thing to do: create the Python function that is called by the automated action. On the code from the automated action you could see it is calling a Python function ‘process_demo_scheduler_queue’, so let us create this in the Python file that uses the model ‘scheduler.demo’:

class scheduler_demo(models.Model):
    _name = 'scheduler.demo'
    name = fields.Char(required=True)
    numberOfUpdates = fields.Integer('Number of updates', help='The number of times the scheduler has run and updated this field')
    lastModified = fields.Date('Last updated')

    #This function is called when the scheduler goes off
    def process_demo_scheduler_queue(self, cr, uid, context=None):

From here on you can do anything you like! You can call models, search values, update values, do calls to external systems, … In this example I will loop over all records on the table ‘schedule.demo’ and I will increase the value from the field ‘numberOfUpdates’ by 1 every time the scheduler is run. The code:

    #This function is called when the scheduler goes off
    def process_demo_scheduler_queue(self, cr, uid, context=None):
    scheduler_line_obj = self.pool.get('scheduler.demo')
    #Contains all ids for the model scheduler.demo
    scheduler_line_ids = self.pool.get('scheduler.demo').search(cr, uid, [])   
    #Loops over every record in the model scheduler.demo
        for scheduler_line_id in scheduler_line_ids :
        #Contains all details from the record in the variable scheduler_line
            scheduler_line =scheduler_line_obj.browse(cr, uid,scheduler_line_id ,context=context)
        numberOfUpdates = scheduler_line.numberOfUpdates
        #Prints out the name of every record.
            _logger.info('line: ' + scheduler_line.name)
        #Update the record
        scheduler_line_obj.write(cr, uid, scheduler_line_id, {'numberOfUpdates': (numberOfUpdates +1), 'lastModified': datetime.date.today()}, context=context)

So, what does this function exactly do? It will get all the ids from the table ‘schedule.demo’, we will then loop over one record at a time and by the id from the record we will find all the values from the specific record. After having the record details we will update the value from the field ‘numberOfUpdates’ and we will finally update the value in the database!

5. Conclusion

Automated actions are a very powerful tool in Odoo and the options are almost unlimited. Automated actions are ideal for automatically doing things in Odoo without having to do them manually. It is a great feature in Odoo to save you time and to make things go smoother.

Do you want to try a demo module and see the source code of this tutorial? You can view on my Github account.

Has this tutorial helped you, do you have any feedback or questions? Post away!