Você está na página 1de 21

Technical Training - Exercises

Release 6.0.RC1

OpenERP
2010-12-06

Contents
1 Conguration 1.1 Open Source RAD with OpenObject . . . . . . . . . . . . . 1.2 Installing OpenERP . . . . . . . . . . . . . . . . . . . . . . OpenERP Architecture . . . . . . . . . . . . . . . . . . . . 1.3 Package installation . . . . . . . . . . . . . . . . . . . . . . 1.4 Installing from source . . . . . . . . . . . . . . . . . . . . . Typical bazaar checkout procedure (on Debian-based Linux) 1.5 Database creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 3 3 3 4 4 4 4 5 5 5 6 6 6 6 6 7 7 7 7 8 8 8 8 9 10 11 11 11 12

Build an OpenERP module 2.1 Composition of a module . . . . . . . . . . . . . . . . . . . . . . . 2.2 Module Stucture . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3 Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4 Object Service - ORM . . . . . . . . . . . . . . . . . . . . . . . . Predened osv.osv attributes for business objects . . . . . . . . . . 2.5 ORM eld types . . . . . . . . . . . . . . . . . . . . . . . . . . . . Common attributes supported by all elds (optional unless specied) Simple elds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.6 Special/Reserved eld names . . . . . . . . . . . . . . . . . . . . . 2.7 Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Action declaration . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

Building views: basics 3.1 Generic view declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Form elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objects Relations 4.1 Relational elds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inheritance 5.1 Inheritance mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Predened osv.osv attributes for business objects . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2 View inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ORM Methods 6.1 Functional elds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Predened osv.osv attributes for business objects . . . . . . . . . . . . . . . . . . . . . . . . . . Advanced Views 7.1 List & Tree . . 7.2 Calendars . . . 7.3 Search views . 7.4 Gantt Charts . . 7.5 (Charts) Graphs Workows Security 9.1 Group-based access control mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ir.model.access.csv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

12 12 13 14 14 14 15 15 15 16 17 17 17 18 18 18 18 19 19 20 21 21

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

8 9

10 Wizards 10.1 Wizard objects (osv_memory) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.2 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.3 Wizard execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Internationalization 12 Reports 12.1 Expressions used in OpenERP report templates . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 WebServices 13.1 Python example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Based on a real case, this chapter covers: building an OpenERP module and its interface, Views, Reports, Workows, Security aspects, Wizards, WebServices, Internationalization, Rapid Application Development (RAD) and Performance Optimization.

1 Conguration
1.1 Open Source RAD with OpenObject
OpenERP is a modern Enterprise Management Software, released under the AGPL license, and featuring CRM, HR, Sales, Accounting, Manufacturing, Inventory, Project Management, ... It is based on OpenObject, a modular, scalable, and intuitive Rapid Application Development (RAD) framework written in Python. OpenObject features a complete and modular toolbox for quickly building applications: integrated ObjectRelationship Mapping (ORM) support, template-based Model-View-Controller (MVC) interfaces, a report generation system, automated internationalization, and much more. Python is a high-level dynamic programming language, ideal for RAD, combining power with clear syntax, and a core kept small by design. Tip: Useful links Main website, with OpenERP downloads: www.openerp.com Functional & technical documentation: doc.openerp.com Community resources: www.launchpad.net/open-object Integration server: test,openobject.com Learning Python: doc.python.org OpenERP E-Learning platform: edu.openerp.com

1.2 Installing OpenERP


OpenERP is distributed as packages/installers for most platforms, but can of course be installed from the source on any platform. OpenERP Architecture OpenERP uses the well-known client-server paradigm, with different pieces of software acting as client and server depending on the desired conguration.Client software. OpenERP provides a thick desktop client (GTK+) on all platforms, and a web interface is also accessible using any modern browser. Tip: Installation procedure The procedure for installing OpenERP is likely to evolve (dependencies and so on), so make sure to always check the specic documentation (packaged & on website) for the latest procedures. See http://doc.openerp.com/install.

1.3 Package installation


Windows Linux All-in-one installer, and separate installers for server, client, and webserver are on the website openerp-server and openerp-client packages are available via corresponding package manager (e.g. Synaptic on Ubuntu) OR using BaZaar bzr branch lp:openerp (or openerp/trunk for the trunk version) when identied on Launchpad, then cd openerp (cd trunk in the trunk version) and ./bzr_set.py Look online for package installers for the GTK client, as well as tutorials for installing the server (e.g. devteam.taktik.be)

Mac

1.4 Installing from source


There are two alternatives: 1. using a tarball provided on the website, 2. or directly getting the source using Bazaar (distributed Source Version Control). You also need to install the required dependencies (PostgreSQL and a few Python libraries - see documentation on doc.openerp.com). Note: OpenERP being Python-based, no compilation step is needed.

Typical bazaar checkout procedure (on Debian-based Linux)


$ sudo apt-get install bzr $ bzr branch lp:openerp $ cd openerp && python ./bzr_set.py # install bazaar version control # retrieve source installer # fetch code and perform setup

1.5 Database creation


After installation, run the server and the client. From the GTK client, use File / Databases / New Database to create a new database (default super admin password is admin). Each database has its own modules and conguration. Note: Demonstration data can also be included.

2 Build an OpenERP module


2.1 Composition of a module

A module can contain the following elements : Business object : declared as Python classes extending the osv.osv OpenObject class, the persistence of these resource is completly managed by OpenObject, Data : XML/CSV les with meta-data (views and workows declaration), conguration data (modules parametrization) and demo data (optional bu recommended for testing), Wizards : stateful interactive forms used to assist users, often available as contextual actions on resources, Reports : RML (XML format). MAKO or OpenOfce report templates, to be merged with any kind of business data, and generate HTML, ODT or PDF reports.

2.2 Module Stucture

Each module is contained in its own directory within the server/bin/addons directory in the server installation. The __init__.py le is the Python module descriptor, because an OpenERP module is also a regular Python module. Note: It is possible to declare a personal addons directory in the conguration le of OpenERP (passed to the server with the -c option) using the addons_path option

2.3 Menus
The menuitem entity is a shortcut for declaring an ir.ui.menu record and connect it with a corresponding action via an ir.model.data record.
<menuitem id="menu_id" parent="parent_menu_id" name="label" icon="icon-code" action="action_id" groups="groupname1,groupname2" sequence="10"/>

Exercise 1 - Module Creation Create the empty module Open Academy, with a corresponding menu entry in OpenERP

2.4 Object Service - ORM


Key component of OpenObject, the Object Service (OSV) implements a complete Object-Relational mapping layer, freeing developers from having to write basic SQL plumbing. Business objects are declared as Python classes inheriting from the osv.osv class, which makes them part of the OpenObject Model, and magically persisted by the ORM layer. Predened osv.osv attributes for business objects _name (required) _columns (required) _defaults business object name, in dot-notation (in module namespace) dictionary {eld names > object elds declarations } dictionary: { eld names > functions providing defaults } _defaults[name] = lambda self,cr,uid,context: eggs Alternative eld to use as name, used by osvs name_get() (default: name) ...

_rec_name ...

2.5 ORM eld types


Objects may contain 3 types of elds: simple, relational, and functional. Simple types are integers, oats, booleans, strings, etc. Relational elds represent the relationships between objects (one2many, many2one, many2many). Functional elds are not stored in the database but calculated on-the-y as Python functions. Common attributes supported by all elds (optional unless specied) string : Field label (required) required : True if mandatory readonly : True if not editable help : Help tooltip select : 1 to include in search views and optimize for list ltering (with database index) business object name, in dot-notation (in module namespace) context : Dictionary with contextual parameters (for relational elds)

Simple elds boolean(...) integer(...) date(...) datetime(...) time(...) start_date: elds.date(Start Date) active: elds.boolean(Active) priority: elds.integer(Priority) char(string,size,translate=False,..) text(string, translate=False,...) [Text-based elds] translate: True if eld values can be translated by users size: maximum size for char elds (41,45) oat(string, digits=None, ...) [Floating-point value with arbitrary precision and scale] digits: tuple (precision, scale) (58) . If digits is not provided, its a oat, not a decimal type.

2.6 Special/Reserved eld names


A few eld names are reserved for pre-dened behavior in OpenObject. Some of them are created automatically by the system, and in that case any eld with that name will be ignored. id unique system identier for the object (created by ORM, do not add it)

name denes the value used by default to display the record in lists, etc. if missing, set _rec_name to specify another eld to use for this purpose ... ...

Exercise 2 - Dene a class Dene a new class Course in the openacademy module.

2.7 Actions
Actions are declared as regular records and can be triggered in 3 ways: 1. by clicking on menu items linked to a specic action 2. by clicking on buttons in views, if these are connected to actions 3. as contextual actions on an object Action declaration
1 2 3 4 5 6 7 8 9 10 11

<record model="ir.actions.act_window" id="action_id"> <field name="name">action.name</field> <field name="view_id" ref="view_id"/> <field name="domain">[list of 3-tuples (max 250 characters)]</field> <field name="context">{context dictionary (max 250 characters)}</field> <field name="res_model">object.model.name</field> <field name="view_type">form|tree</field> <field name="view_mode">form,tree,calendar,graph</field> <field name="target">new</field> <field name="search_view_id" ref="search_view_id"/> </record>

Exercise 3 - Dene new menu entries Dene new menu entries to access courses and sessions under the OpenAcademy menu entry; one should be able to 1) display a list of all the courses and 2) create/modify new courses.

3 Building views: basics


Exercise 1 - Customise a view through the view editor of the web interface Create a tree view for the Course object, displaying the name of the course and its description. Views form a hierarchy. Several views of the same type can be declared on the same object, and will be used depending on their priorities. By declaring an inherited view it is possible to add/remove features in a view.

3.1 Generic view declaration


<record model="ir.ui.view" id="view_id"> <field name="name">view.name</field> <field name="model">object_name</field> <field name="type">form</field> # tree,form,calendar,search,graph,gantt <field name="priority" eval="16"/> <field name="arch" type="xml"> <!-- view content: <form>, <tree>, <graph>, ... --> </field> </record>

3.2 Forms
Forms allow creation/edition or resources, and correspond to <form> elements. Form elements Common attributes for all elements : string: label of the element nolabel: 1 to hide the eld label colspan: number of column on which the eld must span rowspan: number of rows on which the eld must span col: number of column this element must allocate to its child elements invisible: 1 to hide this element completely eval: evaluate this Python code as element content (content is string by default) attrs: Python map dening dynamic conditions on these attributes: readonly, invisible, required based on search tuples on other eld values

Field

Automatic widgets depending on the corresponding eld type. Attributes: string: label of the eld, also for search (overrides eld name) select: 1 to show the eld in normal search, 2 for advanced only nolabel: 1 to hide the eld label required: override required eld attribute readonly: override readonly eld attribute password: True to hide characters typed in this eld context: Python code declaring a context dictionary domain: Python code declaring list of tuples for restricting values on_change: Python method call to trigger when value is changed completion: 1 to enable auto-completion of values when possible groups: comma-separated list of group (id) allowed to see this eld widget: select alternative widget (one2many_list, many2many, url, email, image, oat_time, reference, text_wiki, text_html, progressbar)

properties button

dynamic widget showing all available properties (no attribute) clickable widget associated with actions. Specic attributes: type: type of button: workow (default), object, or action name: workow signal, function name (without parentheses) or action to call (depending on type) conrm: text of conrmation message when clicked states: comma-separated list of states in which this button is shown icon: optional icon (all GTK STOCK icons e.g. gtk-ok)

separator newline label group notebook, page

horizontal separator line for structuring views, with optional label place-holder for completing the current line of the view free-text caption or legend in the form used to organise elds in groups with optional label (adds frame) notebook elements are tab containers for page elements. Attributes: name: label for the tab/page position: tabs position in notebook (inside, top, bottom, left, right)

Exercise 2 - Customise tree and form views using XML Create your own tree and form views for the Course object. Data displayed should be: In the tree view, the name of the course ; In the form view, the name and the description of the course.

Exercise 3 - Notebooks In the Course form view, display the description under a tab, such that it will be easy to add other tabs later, containg additional information.

4 Objects Relations

Exercise 1 - Create classes Create Session and Attendee classes and add a menu item and an action to display the sessions.

4.1 Relational elds


Common attributes supported by relational elds domain: optional restriction in the form of arguments for search (see search()) many2one(obj, ondelete=set null,...) (50) : Relationship towards a parent object (using a foreign key)

obj: _name of destination object (required) ondelete: deletion handling, e.g. set null, cascade, see PostgreSQL documentation one2many(obj, eld_id, ...) (55) : Virtual relationship towards multiple objects (inverse of many2one)

obj: _name of destination object (required) eld_id: eld name of inverse many2one, i.e. corresponding foreign key (required) many2many(obj, rel, eld1, eld2, ...) (56) : Bidirectional multiple relationship between objects

obj: _name of destination object (required) rel: relationship table to use (required) eld1: name of eld in rel table storing the id of the current object (required) eld2: name of eld in rel table storing the id of the target object (required) Exercise 2 - Relations many2one, one2many Using ORM eld types (one2many, many2one), modify the Course, Session and Attendee classes to reect their relations with other objects, dened as follows:

10

Exercise 3 - Modify the views Modify the tree and form views for the Course object and create these views for the Session object. Data displayed should be, for the Course object: In the tree view, the name of the course and the responsible for that course; In the form view, the name and the responsible on the top, as well as the description of the course in one tab and and the related sessions in a second tab. For the Session object: In the tree view, the name of the session and the related course; In the form view, all the elds of the Session object. Since the amount of data to display is quite large, try to arrange the form views in such a way that information looks clear.

5 Inheritance
5.1 Inheritance mechanisms

Exercise 4 - Add an inheritance mechanism Add a Partner class which inherits of the existing Partner class.

Predened osv.osv attributes for business objects _inherit _inherits _name of the parent business object (for prototype inheritance) for multiple / instance inheritance mechanism: dictionary mapping the _name of the parent business objects to the names of the corresponding foreign key elds to use

11

5.2 View inheritance


Existing views should be modifying through inherited views, never directly. An inherited view references its parent view using the inherit_id eld, and may add or modify existing elements in the view by referencing them through XPath expressions, specifying the appropriate position. position inside: placed inside match (default) before: placed before match replace: replace match after: placed after match

Tip: XPath reference can be found at www.w3.org/TR/xpath


<!-- improved idea categories list --> <record id="idea_category_list2" model="ir.ui.view"> <field name="name">id.category.list2</field> <field name="model">ir.ui.view</field> <field name="inherit_id" ref="id_category_list"/> <field name="arch" type="xml"> <xpath expr="/tree/field[@name=description]" position="after"> <field name="idea_ids" string="Number of ideas"/> </xpath> </field> </record>

Exercise 1 - Add an inheritance mechanism Using class inheritance, create a Partner class which modies the existing Partner class. Using views inheritance, modify the existing partners form view to display the new elds.

Exercise 2 - domain Add a mechanism allowing the Session form view to allow the user to choose the instructor only among the partners the Instructor eld of which is set to True.

Exercise 3 - domain We now decide to create new categories among the partners: Teacher/Teacher Level 1 and Teacher/Teacher Level 2. Modify the domain dened in the previous exercise to allow the user to choose the instructor among the partners the Instructor eld of which is set to True or those who are in one of the categories we dened.

6 ORM Methods
6.1 Functional elds
function(fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type=oat, fnct_search=None, obj=None, method=False, store=False, multi=False, ...) : Functional eld simulating a real eld, computed rather than stored fnct [function to compute the eld value (required)] def fnct(self, cr, uid, ids, eld_name, arg, context) returns a dictionary { idsvalues } with values of type type

12

fnct_inv [function used to write a value in the eld instead] def fnct_inv(obj, cr, uid, id, name, value, fnct_inv_arg, context) type : type of simulated eld (any other type besides function) fnct_search [function used to search on this eld] def fnct_search(obj, cr, uid, obj, name, args) returns a list of tuples arguments for search(), e.g. [(id,in,[1,3,5])] obj : model _name of simulated eld if it is a relational eld store, multi : optimization mechanisms (see usage in Performance Section) related(f1, f2, ..., type=oat, ...) [Shortcut eld equivalent to browsing chained elds] f1,f2,... : chained elds to reach target (f1 required) (51) type : type of target eld property(obj, type=oat, view_load=None, group_name=None, ...) [Dynamic attribute with specic access rights] obj : object (required) type : type of equivalent eld Exercise 1 - Functional elds Add a functional eld to the Session class, that contains the percentage of remaining seats in a session. Display that percentage in the session tree and form views. One it is done, try to display it under the form of a progressbar.

Exercise 2 - Onchange methods Modify the Session form view and the Session class in such a way that the percentage of remaining seats refreshes whenever the number of available seats or the number of attendees changes, without having to save the modications.

6.2 Predened osv.osv attributes for business objects


_constraints list of tuples dening the Python constraints, in the form (func_name, message, elds). list of tuples dening the SQL constraints, in the form (name, sql_def, message).

_sql_constraints

Exercise 3 - Add constraints Add a constraint which checks that the course description and the course title are not the same.

Exercise 4 - Add an sql constraint Add an sql constraint to check that a Course has a unique name.

13

Exercise 5 - Add a duplicate option Since we added a constraint for the Course name uniqueness, it is not possible to use the duplicate function anymore (Form > Duplicate). Re-implement your own copy method which allows to duplicate the Course object, changing the original name into Copy of [original name].

Exercise 6 - Active objects Default values Dene the start_date default value as today. Add an active eld in the Session class and set the session as active by default.

7 Advanced Views
7.1 List & Tree
Lists include eld elements, are created with type tree, and have a <tree> parent element. Attributes colors: list of colors mapped to Python conditions editable: top or bottom to allow in-place edit toolbar: set to True to display the top level of object hierarchies as a side toolbar (example: the menu) eld, group, separator, tree, button, lter, newline

Allowed elements

<tree string="Idea Categories" toolbar="1" colors="blue:state==draft"> <field name="name"/> <field name="state"/> </tree>

Exercise 1 - List coloring Modify the Session tree view in such a way that sessions lasting less than 5 days are colored blue, and the ones lasting more than 15 days are colored red. Note: duration eld Beware! If the duration eld is not declared in the view, the client will not be aware of its existence. That would result in an error.

7.2 Calendars
Views used to display date elds as calendar events (<calendar> parent). Attributes color: name of eld for color segmentation date_start: name of eld containing event start date/time day_length: length of a calendar day in hours (default: 8) date_stop: name of eld containing event stop date/time OR date_delay: name of eld containing event duration

Allowed elements

eld (to dene the label for each calendar event)

14

<calendar string="Ideas" date_start="invent_date" color="inventor_id"> <field name="name"/> </calendar>

Exercise 2 - Calendar view Add a Calendar view to the Session object enabling the user to view the events associated to the Open Academy.

7.3 Search views


Search views are used to customize the search panel on top of list views, and are declared with the search type, and a top-level <search> element. After dening a search view with a unique id, add it to the action opening the list view using the search_view_id eld in its declaration. Allowed elements eld, group, separator, label, search, lter, newline, properties lter elements allow dening button for domain lters adding a context attribute to elds makes widgets that alter the search context (useful for context-sensitive elds, e.g. pricelist-dependent prices)

Exercise 3 - Search views Add a search view containing: 1) a eld to search the courses based on their title and 2) a button to lter the courses of which the current user is the responsible. Make the latter selected by default.

7.4 Gantt Charts


Bar chart typically used to show project schedule (<gantt> parent element). Attributes Allowed elements same as <calendar> eld, level level elements are used to dene the Gantt chart levels, with the enclosed eld used as label for that drill-down level

<gantt string="Ideas" date_start="invent_date" color="inventor_id"> <level object="idea.idea" link="id" domain="[]"> <field name="inventor_id"/> </level> </gantt>

Exercise 4 - Gantt charts Add a Gantt Chart enabling the user to view the sessions scheduling linked to the Open Academy module. The sessions should be grouped by instructor.

7.5 (Charts) Graphs


Views used to display statistical charts (<graph> parent element).

15

Attributes

type: type of chart: bar, pie (default) orientation: horizontal, vertical eld, with specic behavior: rst eld in view is X axis, 2nd one is Y, 3rd one is Z 2 elds required, 3rd one is optional group attribute denes the GROUP BY eld (set to 1) operator attribute sets the aggregation operator to use for other elds when one eld is grouped (+,*,**,min,max)

Allowed elements

<graph string="Total idea score by Inventor" type="bar"> <field name="inventor_id" /> <field name="score" operator="+"/> </graph>

Exercise 5 - Graph view Add a Graph view for the session object, that displays, for each course, the number of attendees under the fom of a bar chart.

8 Workows
Workows are models associated to business objects describing the dynamics of the company. Workows are also used to track processes that evolve over time. Exercise 1 - Static Workow Create a state attribute which will be used for dening a workow for the Session object. A session can have three states: Draft (default), Conrmed and Done. Add a (read-only) eld to visualize the state, and buttons to change the state in the Session form. The valid transitions are: Draft -> Conrmed Conrmed -> Draft Conrmed -> Done Done -> Draft A sales order generates an invoice and a shipping order is an example of workow used in Open ERP.

Workows may be associated with any object in OpenERP, and are entirely customizable. Workows are used to structure and manage the lifecycles of business objects and documents, and dene transitions, triggers, etc. with

16

graphical tools. Workows, activities (nodes or actions) and transitions (conditions) are declared as XML records, as usual. The tokens that navigate in workows are called workitems. Exercise 2 - Dynamic workow editor Using the workow editor, create the same workow as the one dened earlier for the Session object. Transform the Session form view such that the buttons change the state in the workow. Note: Workow on create A workow associated to a session is created during the creation of that session. There is therefore no workow instance associated to session instances created before the denition of the workow.

Exercise 3 - Server actions Create server actions and modify the previous workow in order to re-create the same behaviour as previously, but without using the Python methods of the Session class.

Exercise 4 - XML workows Install the base_module_record module. Use it to export the workow created in the workow editor into an XML le, that you can incorporate in your module.

9 Security
Access control mechanisms must be combined to achieve a coherent security policy.

9.1 Group-based access control mechanisms


Groups are created as normal records on the res.groups model, and granted menu access via menu denitions. However even without a menu, objects may still be accessible indirectly, so actual object-level permissions (create,read,write,unlink) must be dened for groups. They are usually inserted via CSV les inside modules. It is also possible to restrict access to specic elds on a view or object using the elds groups attribute. ir.model.access.csv
"id","name","model_id:id","group_id:id","perm_read","perm_write","perm_create", "perm_unlink" "access_idea_idea","idea.idea","model_idea_idea","base.group_user",1,1,1,0 "access_idea_vote","idea.vote","model_idea_vote","base.group_user",1,1,1,0

Exercise 1 - Add access control through OpenERP interface Create a new user John Smith. Then create a group OpenAcademy / SessionRead with read access to the Session and Attendee objects.

Exercise 2 - Add access control through data les in your module Using a xml data le, create a OpenAcademy / Manager group, with no access rights dened yet (just create the empty group).

17

Exercise 3 - Add access control through data les in your module Use a CSV le to add read, write, creation and deletion rights on the Course, Session and Attendees objects to the OpenAcademy / Manager group. You can also create rights associated to no group, such as a read only access on Course and a read only access on Session.

10 Wizards
10.1 Wizard objects (osv_memory)
Wizards describe stateful interactive sessions with the user through dynamic forms. Wizards make use of the osv_memory in-memory persistence to allow constructing wizards from regular business objects and views, without storing them in the database. In-memory objects are created by extending osv.osv_memory. Exercise 1 - Dene the wizard class Dene the create_attendee_wizard class and implement its structure.

10.2 Views
Wizards use regular views and their buttons may use a special=cancel attribute to close the wizard window when clicked.

10.3 Wizard execution


Such wizards are launched via regular action records, with a special target eld used to open the wizard view in a new window. Exercise 2 - Make the wizard available through a menuitem Create a menuitem and the necessary action to use the wizard.

Exercise 3 - Customise the form view Customise the form view in order to show all the elds of the class.

Exercise 4 - Create methods Create the action_add_attendee method in the create_attendee_wizard class, and add a button in the form view to call it. Also add a Cancel button that closes the wizard window.

Exercise 5 - Add an onchange method Add an onchange method in order to display the list of existing attendees for a given session, once the session is selected.

18

Exercise 6 - Bind the wizard to the context bar Bind the wizard to the context bar of the session model.

Extra Exercise - Wizard on multiple records Make the wizard able to add attendees to several sessions at once.

11 Internationalization
Each module can provide its own translations within the i18n directory, by having les named LANG.po where LANG is the locale code for the language, or the language and country combination when they differ (e.g. pt.po or pt_BR.po). Translations will be loaded automatically by OpenERP for all enabled languages. Developers always use English when creating a module, then export the module terms using OpenERPs gettext POT export feature (Administration>Translations>Export a Translation File without specifying a language), to create the module template POT le, and then derive the translated PO les. Many IDEs have plugins or modes for editing and merging PO/POT les. Tip: The GNU gettext format (Portable Object) used by OpenERP is integrated into LaunchPad, making it an online collaborative translation platform.
|- idea/ |- i18n/ | - idea.pot | - fr.po | - pt_BR.po | (...) # # # # # The module directory Translation files Translation Template (exported from OpenERP) French translation Brazilian Portuguese translation

Tip: By default OpenERPs POT export only extracts labels inside XML les or inside eld denitions in Python code, but any Python string can be translated this way by surrounding it with the tools.translate._ method (e.g. _(Label) )

Exercise 1 - Translate a module Choose a second language for your OpenERP installation. Translate your module using the facilities provided by OpenERP.

12 Reports
Reports in OpenERP can be rendered in different ways: Custom reports: those reports can be directly created via the client interface, no programming required. Those reports are represented by business objects (ir.report.custom) High quality personalized reports using openreport: no programming required but you have to write 2 small XML les: a template which indicates the data you plan to report an XSL : RML stylesheet Hard coded reports OpenOfce Writer templates

19

There are several report engines in OpenERP, to produce reports from different sources and in many formats.

12.1 Expressions used in OpenERP report templates


[[ <content> ]] double brackets content is evaluated as a Python expression based on the following expressions

Predened expressions : objects contains the list of records to print data comes from the wizard launching the report user contains the current user (as per browse()) time gives access to Python time module repeatIn(list,var,tag) repeats the current parent element named tag for each object in list, making the object available as var during each loop setTag(tag1,tag2) replaces the parent RML tag1 with tag2 removeParentNode(tag) removes parent RML element tag formatLang(value, digits=2, date=False, date_time=False, grouping=True, monetary=False) can be used to format a date, time or amount according to the locale setLang(lang_code) sets the current language and locale for translations Exercise 1 - Install the OpenOfce plugin Install the report designer module and add the OpenOfce OpenERP plugin.

Exercise 2 - Create a new report Create a report for the Session object, displaying for each session its name, date, duration, percentage of completion, responsible name and list of attendees.

Exercise 3 - i18n Create a report for the Session object, displaying its name, date, duration, percentage of completion, responsible name and list of attendees.

Exercise 4 - RML Export the OpenOfce report to a RML le, add it to your module and add an action to the session object for printing the report.

20

13 WebServices
The web-service module offer a common interface for all web-services : SOAP XML-RPC NET-RPC Business objects can also be accessed via the distributed object mechanism. They can all be modied via the client interface with contextual views. OpenERP is accessible through XML-RPC interfaces, for which libraries exist in many languages.

13.1 Python example


import xmlrpclib # ... define HOST, PORT, DB, USER, PASS url = http://%s:%d/xmlrpc/common % (HOST,PORT) sock = xmlrpclib.ServerProxy(url) uid = sock.login(DB,USER,PASS) print "Logged in as %s (uid:%d)" % (USER,uid) # Create a new idea url = http://%s:%d/xmlrpc/object % (HOST,PORT) sock = xmlrpclib.ServerProxy(url) args = { name : Another idea, description : This is another idea of mine, inventor_id: uid, } idea_id = sock.execute(DB,uid,PASS,idea.idea,create,args)

Exercise 1 - Add a new service to the client Write a Python program able to send XML-RPC requests to a PC running OpenERP (yours, or your instructors). This program should be display all the existing sessions and the corresponding number of seats, and to create a new session for one of the courses. In this case, ask the server to create Session objects.

21

Você também pode gostar