Ysa (Open ERP)
2010-03-12 12:24:40 +05:30
31 changed files with 17864 additions and 968 deletions
+4
View File
@@ -644,6 +644,8 @@ def load_module_graph(cr, graph, status=None, perform_checks=True, **kwargs):
new_query = ' '.join(query.split())
if new_query:
cr.execute(new_query)
elif ext == '.yml':
tools.convert_yaml_import(cr, m, fp, idref, mode=mode, **kwargs)
else:
tools.convert_xml_import(cr, m, fp, idref, mode=mode, **kwargs)
fp.close()
@@ -655,6 +657,8 @@ def load_module_graph(cr, graph, status=None, perform_checks=True, **kwargs):
fp = tools.file_open(opj(m, xml))
if ext == '.csv':
tools.convert_csv_import(cr, m, os.path.basename(xml), fp.read(), idref, mode=mode, noupdate=True)
elif ext == '.yml':
tools.convert_yaml_import(cr, m, fp, idref, mode=mode, **kwargs)
else:
tools.convert_xml_import(cr, m, fp, idref, mode=mode, noupdate=True, **kwargs)
fp.close()
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -7,13 +7,13 @@ msgstr ""
"Project-Id-Version: OpenERP Server 5.0.4\n"
"Report-Msgid-Bugs-To: support@openerp.com\n"
"POT-Creation-Date: 2009-12-18 08:39+0000\n"
"PO-Revision-Date: 2010-03-04 05:27+0000\n"
"PO-Revision-Date: 2010-03-11 05:23+0000\n"
"Last-Translator: goranc <goranc@gmail.com>\n"
"Language-Team: openerp-translators\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Launchpad-Export-Date: 2010-03-05 05:00+0000\n"
"X-Launchpad-Export-Date: 2010-03-12 04:50+0000\n"
"X-Generator: Launchpad (build Unknown)\n"
"Language: hr\n"
+19 -15
View File
@@ -7,13 +7,13 @@ msgstr ""
"Project-Id-Version: OpenERP Server 5.0.4\n"
"Report-Msgid-Bugs-To: support@openerp.com\n"
"POT-Creation-Date: 2009-12-18 08:39+0000\n"
"PO-Revision-Date: 2010-02-15 05:46+0000\n"
"Last-Translator: Luigi Grilli <luigi.grilli@gmail.com>\n"
"PO-Revision-Date: 2010-03-11 11:29+0000\n"
"Last-Translator: Maurizio.Colella <m.colella88@gmail.com>\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Launchpad-Export-Date: 2010-02-17 04:54+0000\n"
"X-Launchpad-Export-Date: 2010-03-12 04:50+0000\n"
"X-Generator: Launchpad (build Unknown)\n"
#. module: base
@@ -3278,7 +3278,7 @@ msgstr "Test"
#. module: base
#: field:ir.report.custom.fields,groupby:0
msgid "Group By"
msgstr ""
msgstr "Raggruppa per"
#. module: base
#: code:addons/base/ir/ir_model.py:0
@@ -3354,7 +3354,7 @@ msgstr ""
#: code:addons/base/res/res_user.py:0
#, python-format
msgid "The name of the group can not start with \"-\""
msgstr ""
msgstr "Il nome del gruppo non può iniziare con '-'"
#. module: base
#: wizard_view:module.upgrade,end:0
@@ -3387,7 +3387,7 @@ msgstr "Sicurezza Gruppi"
#. module: base
#: view:res.partner.bank:0
msgid "Bank Account Owner"
msgstr ""
msgstr "Titolare del conto"
#. module: base
#: model:ir.actions.act_window,name:base.act_values_form
@@ -3434,7 +3434,7 @@ msgstr "Nome Menu"
#. module: base
#: field:ir.report.custom,title:0
msgid "Report Title"
msgstr ""
msgstr "Titolo del report"
#. module: base
#: field:ir.report.custom.fields,fontcolor:0
@@ -3763,6 +3763,8 @@ msgstr "Crea / Scrivi"
#: help:res.partner.category,active:0
msgid "The active field allows you to hide the category without removing it."
msgstr ""
"Il campo attivo ti permette di nascondere la categoria senza doverla "
"rimuovere."
#. module: base
#: rml:ir.module.reference:0
@@ -3806,7 +3808,7 @@ msgstr "Oggetti di Lavoro"
#. module: base
#: field:wizard.module.lang.export,advice:0
msgid "Advice"
msgstr ""
msgstr "Consiglio"
#. module: base
#: selection:module.lang.install,init,lang:0
@@ -3819,6 +3821,8 @@ msgid ""
"Provide the field name where the record id is stored after the create "
"operations. If it is empty, you can not track the new record."
msgstr ""
"Assegna un nome al campo in cui viene registrato l'identificativo del "
"record. Se è vuoto, non potrai tracciare il nuovo record"
#. module: base
#: field:ir.ui.view,inherit_id:0
@@ -3862,7 +3866,7 @@ msgstr ""
#: field:ir.model.fields,state:0
#: field:ir.model.grid,state:0
msgid "Manually Created"
msgstr ""
msgstr "Creato manualmente"
#. module: base
#: selection:ir.report.custom.fields,operation:0
@@ -3933,7 +3937,7 @@ msgstr "Firma"
#. module: base
#: field:res.partner.category,complete_name:0
msgid "Full Name"
msgstr ""
msgstr "Nome Completo"
#. module: base
#: model:res.country,name:base.mz
@@ -3944,7 +3948,7 @@ msgstr "Mozambico"
#: model:ir.actions.act_window,name:base.grant_menu_access
#: model:ir.ui.menu,name:base.menu_grant_menu_access
msgid "Manage Menus"
msgstr ""
msgstr "Gestisci i menu"
#. module: base
#: field:ir.actions.server,message:0
@@ -4048,7 +4052,7 @@ msgstr "Mongolia"
#: code:addons/base/res/res_user.py:0
#, python-format
msgid "Error"
msgstr ""
msgstr "Errore"
#. module: base
#: view:res.partner.som:0
@@ -4098,7 +4102,7 @@ msgstr "Formato File"
#. module: base
#: field:res.lang,iso_code:0
msgid "ISO code"
msgstr ""
msgstr "Codice ISO"
#. module: base
#: model:ir.model,name:base.model_res_config_view
@@ -4351,12 +4355,12 @@ msgstr "Email Mittente"
#. module: base
#: field:ir.default,field_name:0
msgid "Object Field"
msgstr ""
msgstr "Campo Oggetto"
#. module: base
#: selection:module.lang.install,init,lang:0
msgid "French (CH) / Français (CH)"
msgstr ""
msgstr "Francese (CH) / Français (CH)"
#. module: base
#: selection:ir.ui.menu,icon:0
+2 -2
View File
@@ -8,13 +8,13 @@ msgstr ""
"Project-Id-Version: openobject-server\n"
"Report-Msgid-Bugs-To: FULL NAME <EMAIL@ADDRESS>\n"
"POT-Creation-Date: 2009-12-18 08:39+0000\n"
"PO-Revision-Date: 2010-03-04 05:29+0000\n"
"PO-Revision-Date: 2010-03-11 05:20+0000\n"
"Last-Translator: Harry (Open ERP) <hmo@tinyerp.com>\n"
"Language-Team: Japanese <ja@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Launchpad-Export-Date: 2010-03-05 05:00+0000\n"
"X-Launchpad-Export-Date: 2010-03-12 04:50+0000\n"
"X-Generator: Launchpad (build Unknown)\n"
#. module: base
File diff suppressed because it is too large Load Diff
+355 -323
View File
File diff suppressed because it is too large Load Diff
+550 -529
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -7,13 +7,13 @@ msgstr ""
"Project-Id-Version: OpenERP Server 5.0.0\n"
"Report-Msgid-Bugs-To: support@openerp.com\n"
"POT-Creation-Date: 2009-12-18 08:39+0000\n"
"PO-Revision-Date: 2010-03-04 05:29+0000\n"
"PO-Revision-Date: 2010-03-11 05:11+0000\n"
"Last-Translator: Fabien (Open ERP) <fp@tinyerp.com>\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Launchpad-Export-Date: 2010-03-05 05:00+0000\n"
"X-Launchpad-Export-Date: 2010-03-12 04:51+0000\n"
"X-Generator: Launchpad (build Unknown)\n"
#. module: base
+3 -2
View File
@@ -1252,9 +1252,10 @@
<newline/>
<label colspan="4" string="Access all the fields related to the current object using expression in double brackets, i.e. [[ object.partner_id.name ]]" align="0.0"/>
</page>
<page string="Create / Write" attrs="{'invisible':[('state','!=','object_create'),('state','!=','object_write')]}">
<page string="Create / Write / Copy" attrs="{'invisible':[('state','!=','object_create'), ('state','!=','object_write'), ('state','!=','object_copy')]}">
<separator colspan="4" string="Fields Mapping"/>
<field name="srcmodel_id" select="2" attrs="{'required':[('state','!=','dummy'), ('state','!=','sms'), ('state','!=','code'), ('state','!=','loop'),('state','!=','trigger'), ('state','!=','client_action'), ('state','!=','email'), ('state','!=','sms'), ('state','!=','other')]}"/>
<field name="srcmodel_id" select="2" attrs="{'required':[('state','!=','dummy'), ('state','!=','sms'), ('state','!=','code'), ('state','!=','loop'), ('state','!=','trigger'), ('state','!=','object_copy'), ('state','!=','client_action'), ('state','!=','email'), ('state','!=','sms'), ('state','!=','other')]}"/>
<field name="copy_object" on_change="change_object(copy_object, state)" select="2" attrs="{'required':[('state','!=','dummy'), ('state','!=','sms'), ('state','!=','code'), ('state','!=','loop'), ('state','!=','trigger'), ('state','!=','object_write'), ('state','!=','object_create'), ('state','!=','client_action'), ('state','!=','email'), ('state','!=','sms'), ('state','!=','other')]}"/>
<field name="fields_lines" nolabel="1" select="2" colspan="4">
<tree string="Field Mappings" editable="top">
<field name="col1" domain="[('model_id','=',parent.srcmodel_id or parent.model_id)]"/>
+43 -5
View File
@@ -377,16 +377,32 @@ server_object_lines()
class actions_server(osv.osv):
def _select_signals(self, cr, uid, context={}):
cr.execute("select distinct t.signal as key, t.signal || ' - [ ' || w.osv || ' ] ' as val from wkf w, wkf_activity a, wkf_transition t "\
" where w.id = a.wkf_id " \
" and t.act_from = a.id " \
" or t.act_to = a.id and t.signal not in (null, NULL)")
cr.execute("select distinct w.osv, t.signal from wkf w, wkf_activity a, wkf_transition t where w.id = a.wkf_id and t.act_from = a.id or t.act_to = a.id and t.signal!='' and t.signal not in (null, NULL)")
result = cr.fetchall() or []
res = []
for rs in result:
if rs[0] is not None and rs[1] is not None:
res.append(rs)
line = rs[0], "%s - (%s)" % (rs[1], rs[0])
res.append(line)
return res
def _select_objects(self, cr, uid, context={}):
model_pool = self.pool.get('ir.model')
ids = model_pool.search(cr, uid, [('name','not ilike','.')])
res = model_pool.read(cr, uid, ids, ['model', 'name'])
return [(r['model'], r['name']) for r in res] + [('','')]
def change_object(self, cr, uid, ids, copy_object, state, context={}):
if state == 'object_copy':
model_pool = self.pool.get('ir.model')
model = copy_object.split(',')[0]
mid = model_pool.search(cr, uid, [('model','=',model)])
return {
'value':{'srcmodel_id':mid[0]},
'context':context
}
else:
return {}
_name = 'ir.actions.server'
_table = 'ir_act_server'
@@ -404,6 +420,7 @@ class actions_server(osv.osv):
('email','Email'),
('sms','SMS'),
('object_create','Create Object'),
('object_copy','Copy Object'),
('object_write','Write Object'),
('other','Multi Actions'),
], 'Action Type', required=True, size=32, help="Type of the Action that is to be executed"),
@@ -428,6 +445,7 @@ class actions_server(osv.osv):
'write_id':fields.char('Write Id', size=256, help="Provide the field name that the record id refers to for the write operation. If it is empty it will refer to the active id of the object."),
'loop_action':fields.many2one('ir.actions.server', 'Loop Action', help="Select the action that will be executed. Loop action will not be avaliable inside loop."),
'expression':fields.char('Loop Expression', size=512, help="Enter the field/expression that will return the list. E.g. select the sale order in Object, and you can have loop on the sales order line. Expression = `object.order_line`."),
'copy_object': fields.reference('Copy Of', selection=_select_objects, size=256),
}
_defaults = {
'state': lambda *a: 'dummy',
@@ -666,6 +684,26 @@ class actions_server(osv.osv):
cr.commit()
if action.record_id:
self.pool.get(action.model_id.model).write(cr, uid, [context.get('active_id')], {action.record_id.name:res_id})
if action.state == 'object_copy':
res = {}
for exp in action.fields_lines:
euq = exp.value
if exp.type == 'equation':
obj_pool = self.pool.get(action.model_id.model)
obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
expr = eval(euq, {'context':context, 'object': obj, 'time':time})
else:
expr = exp.value
res[exp.col1.name] = expr
obj_pool = None
res_id = False
model = action.copy_object.split(',')[0]
cid = action.copy_object.split(',')[1]
obj_pool = self.pool.get(model)
res_id = obj_pool.copy(cr, uid, int(cid), res)
return False
+1 -1
View File
@@ -30,7 +30,7 @@
<form string="Event Type">
<field name="name" select="1"/>
<field name="active" select="1"/>
<field name="key" readonly="1" select="1"/>
<field name="key" select="1"/>
</form>
</field>
</record>
+4 -3
View File
@@ -149,9 +149,10 @@ class res_partner(osv.osv):
'active': fields.boolean('Active'),
'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
'supplier': fields.boolean('Supplier', help="Check this box if the partner is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."),
'city':fields.related('address','city',type='char', string='City'),
'country':fields.related('address','country_id',type='many2one', relation='res.country', string='Country'),
'company_id': fields.many2one('res.company', 'Company',select=1),
'city': fields.related('address', 'city', type='char', string='City'),
'phone': fields.related('address', 'phone', type='char', string='Phone'),
'country': fields.related('address', 'country_id', type='many2one', relation='res.country', string='Country'),
'company_id': fields.many2one('res.company', 'Company', select=1),
}
def _default_category(self, cr, uid, context={}):
+8 -4
View File
@@ -236,11 +236,12 @@
<field name="arch" type="xml">
<tree string="Partners">
<field name="name"/>
<field name="title"/>
<field name="ref"/>
<field name="phone"/>
<field name="city"/>
<field name="country"/>
<field name="lang"/>
<field name="user_id"/>
</tree>
</field>
</record>
@@ -250,11 +251,11 @@
<field name="model">res.partner</field>
<field name="type">form</field>
<field name="arch" type="xml">
<form string="Partners">
<form string="Partners" col='1'>
<group col="6" colspan="4">
<group colspan="5" col="6">
<field name="name" select="1" colspan="6"/>
<field name="ref" select="1"/>
<field name="name" select="1"/>
<field name="ref"/>
<field domain="[('domain', '=', 'partner')]" name="title"/>
<field name="lang"/>
</group>
@@ -342,6 +343,7 @@
<field name="country" select="1"/>
<field name="address" select="1"/>
<field name="category_id" select="1"/>
<field name="user_id" select="1"/>
</group>
</search>
</field>
@@ -584,7 +586,9 @@
<field name="view_mode">tree,form</field>
<field name="domain">[('category_id','child_of', [active_id])]</field>
<field name="context">{'category_id':active_id}</field>
<field name="search_view_id" ref="view_res_partner_filter"/>
</record>
<record id="ir_action_partner_by_category" model="ir.values">
<field eval="'tree_but_open'" name="key2"/>
<field eval="'res.partner.category'" name="model"/>
+21 -9
View File
@@ -21,6 +21,7 @@
from osv import fields, osv
from locale import localeconv
import tools
class lang(osv.osv):
_name = "res.lang"
@@ -59,23 +60,35 @@ class lang(osv.osv):
('name_uniq', 'unique (name)', 'The name of the language must be unique !'),
('code_uniq', 'unique (code)', 'The code of the language must be unique !'),
]
def _group(self,cr,uid,ids,s, monetary=False):
@tools.cache(skiparg=3)
def _lang_data_get(self, cr, uid, lang_id):
conv = localeconv()
lang_obj=self.browse(cr,uid,ids[0])
lang_obj=self.browse(cr,uid,lang_id)
thousands_sep = lang_obj.thousands_sep or conv[monetary and 'mon_thousands_sep' or 'thousands_sep']
decimal_point = lang_obj.decimal_point
grouping = lang_obj.grouping
return (grouping, thousands_sep, decimal_point)
grouping = eval(lang_obj.grouping)
def write(self, cr, uid, ids, vals, context=None):
for lang_id in ids :
self._lang_data_get.clear_cache(cr.dbname,lang_id= lang_id)
return super(lang, self).write(cr, uid, ids, vals, context)
def _group(self, cr, uid, ids, s, monetary=False, grouping=False, thousands_sep=''):
grouping = eval(grouping)
if not grouping:
return (s, 0)
result = ""
seps = 0
spaces = ""
if s[-1] == ' ':
sp = s.find(' ')
spaces = s[sp:]
s = s[:sp]
while s and grouping:
# if grouping is -1, we are done
if grouping[0] == -1:
@@ -101,13 +114,13 @@ class lang(osv.osv):
seps += 1
return result + spaces, seps
def format(self,cr,uid,ids,percent, value, grouping=False, monetary=False):
def format(self, cr, uid, ids, percent, value, grouping=False, monetary=False):
""" Format() will return the language-specific output for float values"""
if percent[0] != '%':
raise ValueError("format() must be given exactly one %char format specifier")
lang_obj=self.browse(cr,uid,ids[0])
lang_grouping, thousands_sep, decimal_point = self._lang_data_get(cr, uid, ids[0])
formatted = percent % value
# floats and decimal ints need special action!
@@ -116,9 +129,8 @@ class lang(osv.osv):
parts = formatted.split('.')
if grouping:
parts[0], seps = self._group(cr,uid,ids,parts[0], monetary=monetary)
parts[0], seps = self._group(cr,uid,ids,parts[0], monetary=monetary, grouping=lang_grouping, thousands_sep=thousands_sep)
decimal_point=lang_obj.decimal_point
formatted = decimal_point.join(parts)
while seps:
sp = formatted.find(' ')
@@ -127,7 +139,7 @@ class lang(osv.osv):
seps -= 1
elif percent[-1] in 'diu':
if grouping:
formatted = self._group(cr,uid,ids,formatted, monetary=monetary)[0]
formatted = self._group(cr,uid,ids,formatted, monetary=monetary, grouping=lang_grouping, thousands_sep=thousands_sep)[0]
return formatted
+1
View File
@@ -193,6 +193,7 @@
<rng:optional> <rng:attribute name="view_mode"/> </rng:optional>
<rng:optional> <rng:attribute name="multi"/> </rng:optional>
<rng:optional> <rng:attribute name="target"/> </rng:optional>
<rng:optional> <rng:attribute name="key2"/> </rng:optional>
<rng:optional> <rng:attribute name="groups"/> </rng:optional>
<rng:empty />
</rng:element>
+10 -6
View File
@@ -127,6 +127,7 @@ class ExportService(object):
LOG_NOTSET = 'notset'
LOG_DEBUG_RPC = 'debug_rpc'
LOG_DEBUG = 'debug'
LOG_TEST = 'test'
LOG_INFO = 'info'
LOG_WARNING = 'warn'
LOG_ERROR = 'error'
@@ -135,6 +136,9 @@ LOG_CRITICAL = 'critical'
logging.DEBUG_RPC = logging.DEBUG - 2
logging.addLevelName(logging.DEBUG_RPC, 'DEBUG_RPC')
logging.TEST = logging.INFO - 5
logging.addLevelName(logging.TEST, 'TEST')
def init_logger():
import os
from tools.translate import resetlocale
@@ -147,9 +151,7 @@ def init_logger():
if tools.config['syslog']:
# SysLog Handler
if os.name == 'nt':
handler = logging.handlers.NTEventLogHandler("%s %s" %
(release.description,
release.version))
handler = logging.handlers.NTEventLogHandler("%s %s" % (release.description, release.version))
else:
handler = logging.handlers.SysLogHandler('/dev/log')
formatter = logging.Formatter("%s %s" % (release.description, release.version) + ':%(levelname)s:%(name)s:%(message)s')
@@ -195,6 +197,7 @@ def init_logger():
'DEBUG_RPC': ('blue', 'white'),
'DEBUG': ('blue', 'default'),
'INFO': ('green', 'default'),
'TEST': ('white', 'blue'),
'WARNING': ('yellow', 'default'),
'ERROR': ('red', 'default'),
'CRITICAL': ('white', 'red'),
@@ -220,9 +223,10 @@ class Logger(object):
log = logging.getLogger(tools.ustr(name))
if level == LOG_DEBUG_RPC and not hasattr(log, level):
fct = lambda msg, *args, **kwargs: log.log(logging.DEBUG_RPC, msg, *args, **kwargs)
setattr(log, LOG_DEBUG_RPC, fct)
if level in [LOG_DEBUG_RPC, LOG_TEST] and not hasattr(log, level):
fct = lambda msg, *args, **kwargs: log.log(getattr(logging, level.upper()), msg, *args, **kwargs)
setattr(log, level, fct)
level_method = getattr(log, level)
+5
View File
@@ -66,6 +66,11 @@ for name, value in [('addons_path', tools.config['addons_path']),
('database user', tools.config['db_user'])]:
logger.notifyChannel("server", netsvc.LOG_INFO, "%s - %s" % ( name, value ))
# Don't allow if the connection to PostgreSQL done by postgres user
if tools.config['db_user'] == 'postgres':
logger.notifyChannel("server", netsvc.LOG_ERROR, "%s" % ("Attempted to connect database with postgres user. This is a security flaws, aborting."))
sys.exit(1)
import time
#----------------------------------------------------------
+28 -15
View File
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
##############################################################################
#
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
@@ -15,7 +15,7 @@
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
@@ -80,6 +80,7 @@ class _column(object):
self.view_load = 0
self.select = select
self.selectable = True
self.group_operator = args.get('group_operator', False)
for a in args:
if args[a]:
setattr(self, a, args[a])
@@ -172,11 +173,18 @@ class float(_column):
_symbol_f = lambda x: __builtin__.float(x or 0.0)
_symbol_set = (_symbol_c, _symbol_f)
def __init__(self, string='unknown', digits=None, **args):
def __init__(self, string='unknown', digits=None, digits_compute=None, **args):
_column.__init__(self, string=string, **args)
self.digits = digits
self.digits_compute = digits_compute
def digits_change(self, cr):
if self.digits_compute:
t = self.digits_compute(cr)
self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
self.digits = t
class date(_column):
_type = 'date'
@@ -314,8 +322,8 @@ class many2one(_column):
except except_orm:
record_name = {}
record_name[record] = '// Access Denied //'
names.update(record_name)
names.update(record_name)
for r in res.keys():
if res[r] and res[r] in names:
res[r] = (res[r], names[res[r]])
@@ -623,12 +631,10 @@ class function(_column):
self._multi = multi
if 'relation' in args:
self._obj = args['relation']
if 'digits' in args:
self.digits = args['digits']
else:
self.digits = (16,2)
self.digits = args.get('digits', (16,2))
self.digits_compute = args.get('digits_compute', None)
self._fnct_inv_arg = fnct_inv_arg
if not fnct_inv:
self.readonly = 1
@@ -638,7 +644,7 @@ class function(_column):
if not fnct_search and not store:
self.selectable = False
if store:
self._classic_read = True
self._classic_write = True
@@ -650,6 +656,13 @@ class function(_column):
self._symbol_f = float._symbol_f
self._symbol_set = float._symbol_set
def digits_change(self, cr):
if self.digits_compute:
t = self.digits_compute(cr)
self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
self.digits = t
def search(self, cr, uid, obj, name, args, context=None):
if not self._fnct_search:
#CHECKME: should raise an exception
@@ -670,14 +683,14 @@ class function(_column):
if self._type == "many2one" :
# Filtering only integer/long values if passed
res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
if res_ids:
obj_model = obj.pool.get(self._obj)
dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
for r in res.keys():
if res[r] and res[r] in dict_names:
res[r] = (res[r], dict_names[res[r]])
if self._type == 'binary' and context.get('bin_size', False):
# convert the data returned by the function with the size of that data...
res = dict(map( get_nice_size, res.items()))
@@ -827,7 +840,7 @@ class dummy(function):
def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
return {}
def __init__(self, *arg, **args):
self.arg = arg
self._relations = []
+8 -21
View File
@@ -315,7 +315,7 @@ def get_pg_type(f):
f_type = (type_dict[type(f)], type_dict[type(f)])
elif isinstance(f, fields.float):
if f.digits:
f_type = ('numeric', 'NUMERIC(%d,%d)' % (f.digits[0], f.digits[1]))
f_type = ('numeric', 'NUMERIC')
else:
f_type = ('float8', 'DOUBLE PRECISION')
elif isinstance(f, (fields.char, fields.reference)):
@@ -337,7 +337,7 @@ def get_pg_type(f):
f_type = (type_dict[t], type_dict[t])
elif isinstance(f, fields.function) and f._type == 'float':
if f.digits:
f_type = ('numeric', 'NUMERIC(%d,%d)' % (f.digits[0], f.digits[1]))
f_type = ('numeric', 'NUMERIC')
else:
f_type = ('float8', 'DOUBLE PRECISION')
elif isinstance(f, fields.function) and f._type == 'selection':
@@ -1007,7 +1007,7 @@ class orm_template(object):
if fields and f not in fields:
continue
res[f] = {'type': self._columns[f]._type}
for arg in ('string', 'readonly', 'states', 'size', 'required',
for arg in ('string', 'readonly', 'states', 'size', 'required', 'group_operator',
'change_default', 'translate', 'help', 'select', 'selectable'):
if getattr(self._columns[f], arg):
res[f][arg] = getattr(self._columns[f], arg)
@@ -1884,13 +1884,10 @@ class orm(orm_template):
fields_pre = [f for f in float_int_fields if
f == self.CONCURRENCY_CHECK_FIELD
or (f in self._columns and getattr(self._columns[f], '_classic_write'))]
avg_fields = context.get('avg',[])
for f in fields_pre:
if f not in ['id','sequence']:
if f in avg_fields:
flist += ',avg('+f+') as '+f
else:
flist += ',sum('+f+') as '+f
operator = fget[f].get('group_operator','sum')
flist += ','+operator+'('+f+') as '+f
cr.execute('select min(%s.id) as id,' % self._table + flist + ' from ' + ','.join(tables) + where_clause + ' group by '+ groupby + limit_str + offset_str, where_params)
alldata = {}
@@ -2190,19 +2187,9 @@ class orm(orm_template):
cr.commit()
for c in casts:
if (f_pg_type==c[0]) and (f._type==c[1]):
# Adding upcoming 6 lines to check whether only the size of the fields got changed or not.E.g. :(16,3) to (16,4)
field_size_change = False
if f_pg_type in ['int4','numeric','float8']:
if f.digits:
field_size = (65535 * f.digits[0]) + f.digits[0] + f.digits[1]
if field_size != f_pg_size:
field_size_change = True
if f_pg_type != f_obj_type or field_size_change:
if f_pg_type != f_obj_type:
if f_pg_type != f_obj_type:
logger.notifyChannel('orm', netsvc.LOG_INFO, "column '%s' in table '%s' changed type to %s." % (k, self._table, c[1]))
if field_size_change:
logger.notifyChannel('orm', netsvc.LOG_INFO, "column '%s' in table '%s' changed in the size." % (k, self._table))
ok = True
cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
@@ -2319,6 +2306,8 @@ class orm(orm_template):
self._columns = self._columns.copy()
for store_field in self._columns:
f = self._columns[store_field]
if hasattr(f, 'digits_change'):
f.digits_change(cr)
if not isinstance(f, fields.function):
continue
if not f.store:
@@ -2603,8 +2592,6 @@ class orm(orm_template):
# all fields which need to be post-processed by a simple function (symbol_get)
fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
if fields_post:
# maybe it would be faster to iterate on the fields then on res, so that we wouldn't need
# to get the _symbol_get in each occurence
for r in res:
for f in fields_post:
r[f] = self._columns[f]._symbol_get(r[f])
+11 -6
View File
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
##############################################################################
#
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
@@ -15,7 +15,7 @@
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
@@ -47,7 +47,7 @@ class except_osv(Exception):
class osv_pool(netsvc.Service):
def check(f):
@wraps(f)
def wrapper(self, dbname, *args, **kwargs):
@@ -99,23 +99,28 @@ class osv_pool(netsvc.Service):
for o in self._init_parent:
self.get(o)._parent_store_compute(cr)
self._init = mode
self._ready = True
return different
def execute_cr(self, cr, uid, obj, method, *args, **kw):
object = pooler.get_pool(cr.dbname).get(obj)
if not object:
raise except_osv('Object Error', 'Object %s doesn\'t exist' % str(obj))
return getattr(object, method)(cr, uid, *args, **kw)
@check
def execute(self, db, uid, obj, method, *args, **kw):
db, pool = pooler.get_db_and_pool(db)
cr = db.cursor()
try:
try:
if method.startswith('_'):
raise except_osv('Method Error', 'Private method %s can not be calleble.' % (method,))
res = pool.execute_cr(cr, uid, obj, method, *args, **kw)
if res is None:
self.logger.notifyChannel("web-services", netsvc.LOG_WARNING,
'Method can not return a None value (crash in XML-RPC)')
cr.commit()
except Exception:
cr.rollback()
+1 -2
View File
@@ -24,7 +24,7 @@ pool_dic = {}
def get_db_and_pool(db_name, force_demo=False, status=None, update_module=False):
if not status:
status={}
db = get_db_only(db_name)
if db_name in pool_dic:
@@ -81,4 +81,3 @@ def get_pool(db_name, force_demo=False, status=None, update_module=False):
return pool
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
+12 -3
View File
@@ -25,12 +25,20 @@ import cStringIO
import marshal
class Myexception(Exception):
"""
custome exception object store
* faultcode
* faulestring
* args
"""
def __init__(self, faultCode, faultString):
self.faultCode = faultCode
self.faultString = faultString
self.args = (faultCode, faultString)
class mysocket:
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -40,14 +48,17 @@ class mysocket:
# prepare this socket for long operations: it may block for infinite
# time, but should exit as soon as the net is down
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
def connect(self, host, port=False):
if not port:
protocol, buf = host.split('//')
host, port = buf.split(':')
self.sock.connect((host, int(port)))
def disconnect(self):
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
def mysend(self, msg, exception=False, traceback=None):
msg = cPickle.dumps([msg,traceback])
size = len(msg)
@@ -59,6 +70,7 @@ class mysocket:
if sent == 0:
raise RuntimeError, "socket connection broken"
totalsent = totalsent + sent
def myreceive(self):
buf=''
while len(buf) < 8:
@@ -89,6 +101,3 @@ class mysocket:
raise res[0]
else:
return res[0]
+2 -2
View File
@@ -89,7 +89,7 @@ class configmanager(object):
hasSSL = check_ssl()
self._LOGLEVELS = dict([(getattr(netsvc, 'LOG_%s' % x), getattr(logging, x))
for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'DEBUG_RPC', 'NOTSET')])
for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'TEST', 'DEBUG', 'DEBUG_RPC', 'NOTSET')])
version = "%s %s" % (release.description, release.version)
parser = optparse.OptionParser(version=version)
@@ -120,7 +120,7 @@ class configmanager(object):
parser.add_option('--debug', dest='debug_mode', action='store_true', default=False, help='enable debug mode')
parser.add_option("--assert-exit-level", dest='assert_exit_level', type="choice", choices=self._LOGLEVELS.keys(),
help="specify the level at which a failed assertion will stop the server. Accepted values: %s" % (self._LOGLEVELS.keys(),))
parser.add_option('--price_accuracy', dest='price_accuracy', default='2', help='specify the price accuracy')
parser.add_option('--price_accuracy', dest='price_accuracy', default='2', help='deprecated since v6.0, replaced by module decimal_precision')
parser.add_option('--no-database-list', action="store_false", dest='list_db', default=True, help="disable the ability to return the list of databases")
if hasSSL:
+5 -2
View File
@@ -37,6 +37,7 @@ import netsvc
import osv
import pooler
from config import config
from yaml_import import convert_yaml_import
class ConvertError(Exception):
def __init__(self, doc, orig_excpt):
@@ -368,9 +369,10 @@ form: module.record_id""" % (xml_id,)
domain = rec.get('domain','').encode('utf-8') or '{}'
context = rec.get('context','').encode('utf-8') or '{}'
res_model = rec.get('res_model','').encode('utf-8')
src_model = rec.get('src_model','').encode('utf-8')
src_model = rec.get('src_model','').encode('utf-8')
view_type = rec.get('view_type','').encode('utf-8') or 'form'
view_mode = rec.get('view_mode','').encode('utf-8') or 'tree,form'
usage = rec.get('usage','').encode('utf-8')
limit = rec.get('limit','').encode('utf-8')
auto_refresh = rec.get('auto_refresh','').encode('utf-8')
@@ -418,7 +420,8 @@ form: module.record_id""" % (xml_id,)
self.idref[xml_id] = int(id)
if src_model:
keyword = 'client_action_relate'
#keyword = 'client_action_relate'
keyword = rec.get('key2','').encode('utf-8') or 'client_action_relate'
keys = [('action', keyword), ('res_model', res_model)]
value = 'ir.actions.act_window,'+str(id)
replace = rec.get('replace','') or True
+788
View File
@@ -0,0 +1,788 @@
# -*- encoding: utf-8 -*-
import types
import time # used to eval time.strftime expressions
import logging
import pooler
import netsvc
import misc
from config import config
import yaml
logger_channel = 'tests'
class YamlImportException(Exception):
pass
class YamlImportAbortion(Exception):
pass
class YamlTag(object):
"""
Superclass for constructors of custom tags defined in yaml file.
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __getitem__(self, key):
return getattr(self, key)
def __getattr__(self, attr):
return None
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, sorted(self.__dict__.items()))
class Assert(YamlTag):
def __init__(self, model, id, severity=logging.ERROR, string="NONAME", **kwargs):
self.model = model
self.id = id
self.severity = severity
self.string = string
super(Assert, self).__init__(**kwargs)
class Record(YamlTag):
def __init__(self, model, id, **kwargs):
self.model = model
self.id = id
super(Record, self).__init__(**kwargs)
class Python(YamlTag):
def __init__(self, model, severity=logging.ERROR, name="", **kwargs):
self.model= model
self.severity = severity
self.name = name
super(Python, self).__init__(**kwargs)
class Menuitem(YamlTag):
def __init__(self, id, name, **kwargs):
self.id = id
self.name = name
super(Menuitem, self).__init__(**kwargs)
class Workflow(YamlTag):
def __init__(self, model, action, **kwargs):
self.model = model
self.action = action
super(Workflow, self).__init__(**kwargs)
class ActWindow(YamlTag):
def __init__(self, model, action, **kwargs):
self.model = model
self.action = action
super(ActWindow, self).__init__(**kwargs)
class Function(YamlTag):
def __init__(self, model, name, **kwargs):
self.model = model
self.name = name
super(Function, self).__init__(**kwargs)
class Report(YamlTag):
def __init__(self, model, name, string, **kwargs):
self.model = model
self.name = name
self.string = string
super(Report, self).__init__(**kwargs)
class Delete(YamlTag):
def __init__(self, model, id, search, **kwargs):
self.model = model
self.id = id
self.search = search
super(Delete, self).__init__(**kwargs)
class Context(YamlTag):
def __init__(self, **kwargs):
super(Context, self).__init__(**kwargs)
class Url(YamlTag):
def __init__(self, **kwargs):
super(Url, self).__init__(**kwargs)
class Eval(YamlTag):
def __init__(self, expression):
self.expression = expression
super(Eval, self).__init__()
class IrSet(YamlTag):
def __init__(self):
super(IrSet, self).__init__()
def assert_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Assert(**kwargs)
def record_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Record(**kwargs)
def python_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Python(**kwargs)
def menuitem_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Menuitem(**kwargs)
def workflow_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Workflow(**kwargs)
def act_window_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return ActWindow(**kwargs)
def function_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Function(**kwargs)
def report_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Report(**kwargs)
def delete_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Delete(**kwargs)
def context_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Context(**kwargs)
def url_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return Url(**kwargs)
def eval_constructor(loader, node):
expression = loader.construct_scalar(node)
return Eval(expression)
def ir_set_constructor(loader, node):
kwargs = loader.construct_mapping(node)
return IrSet(**kwargs)
yaml.add_constructor(u"!assert", assert_constructor)
yaml.add_constructor(u"!record", record_constructor)
yaml.add_constructor(u"!python", python_constructor)
yaml.add_constructor(u"!menuitem", menuitem_constructor)
yaml.add_constructor(u"!workflow", workflow_constructor)
yaml.add_constructor(u"!act_window", act_window_constructor)
yaml.add_constructor(u"!function", function_constructor)
yaml.add_constructor(u"!report", report_constructor)
yaml.add_constructor(u"!context", context_constructor)
yaml.add_constructor(u"!delete", delete_constructor)
yaml.add_constructor(u"!url", url_constructor)
yaml.add_constructor(u"!eval", eval_constructor)
yaml.add_constructor(u"!ir_set", ir_set_constructor)
def _is_yaml_mapping(node, tag_constructor):
value = isinstance(node, types.DictionaryType) \
and len(node.keys()) == 1 \
and isinstance(node.keys()[0], tag_constructor)
return value
def is_comment(node):
return isinstance(node, types.StringTypes)
def is_assert(node):
return _is_yaml_mapping(node, Assert)
def is_record(node):
return _is_yaml_mapping(node, Record)
def is_python(node):
return _is_yaml_mapping(node, Python)
def is_menuitem(node):
return isinstance(node, Menuitem) \
or _is_yaml_mapping(node, Menuitem)
def is_function(node):
return isinstance(node, Function) \
or _is_yaml_mapping(node, Function)
def is_report(node):
return isinstance(node, Report)
def is_workflow(node):
return isinstance(node, Workflow)
def is_act_window(node):
return isinstance(node, ActWindow)
def is_delete(node):
return isinstance(node, Delete)
def is_context(node):
return isinstance(node, Context)
def is_url(node):
return isinstance(node, Url)
def is_eval(node):
return isinstance(node, Eval)
def is_ir_set(node):
return _is_yaml_mapping(node, IrSet)
class TestReport(object):
def __init__(self):
self._report = {}
def record(self, success, severity):
"""
Records the result of an assertion for the failed/success count.
Returns success.
"""
if severity in self._report:
self._report[severity][success] += 1
else:
self._report[severity] = {success: 1, not success: 0}
return success
def __str__(self):
res = []
res.append('\nAssertions report:\nLevel\tsuccess\tfailure')
success = failure = 0
for severity in self._report:
res.append("%s\t%s\t%s" % (severity, self._report[severity][True], self._report[severity][False]))
success += self._report[severity][True]
failure += self._report[severity][False]
res.append("total\t%s\t%s" % (success, failure))
res.append("end of report (%s assertion(s) checked)" % success + failure)
return "\n".join(res)
class RecordDictWrapper(dict):
"""
Used to pass a record as locals in eval:
records do not strictly behave like dict, so we force them to.
"""
def __init__(self, record):
self.record = record
def __getitem__(self, key):
if key in self.record:
return self.record[key]
return dict.__getitem__(self, key)
class YamlInterpreter(object):
def __init__(self, cr, module, id_map, mode, filename, noupdate=False):
self.cr = cr
self.module = module
self.id_map = id_map
self.mode = mode
self.filename = filename
self.assert_report = TestReport()
self.noupdate = noupdate
self.logger = logging.getLogger("%s.%s" % (logger_channel, self.module))
self.pool = pooler.get_pool(cr.dbname)
self.uid = 1
self.context = {} # opererp context
self.eval_context = {'ref': self._ref, '_ref': self._ref} # added '_ref' so that record['ref'] is possible
def _ref(self):
return lambda xml_id: self.get_id(xml_id)
def get_model(self, model_name):
model = self.pool.get(model_name)
assert model, "The model %s does not exist." % (model_name,)
return model
def validate_xml_id(self, xml_id):
id = xml_id
if '.' in xml_id:
module, id = xml_id.split('.', 1)
assert '.' not in id, "The ID reference '%s' must contains maximum one dot.\n" \
"It is used to refer to other modules ID, in the form: module.record_id" \
% (xml_id,)
if module != self.module:
module_count = self.pool.get('ir.module.module').search_count(self.cr, self.uid, \
['&', ('name', '=', module), ('state', 'in', ['installed'])])
assert module_count == 1, 'The ID "%s" refers to an uninstalled module.' % (xml_id,)
if len(id) > 64: # TODO where does 64 come from (DB is 128)? should be a constant or loaded form DB
self.logger.log(logging.ERROR, 'id: %s is to long (max: 64)', id)
def get_id(self, xml_id):
if not xml_id:
raise YamlImportException("The xml_id should be a non empty string.")
if isinstance(xml_id, types.IntType):
id = xml_id
elif xml_id in self.id_map:
id = self.id_map[xml_id]
else:
if '.' in xml_id:
module, xml_id = xml_id.split('.', 1)
else:
module = self.module
ir_id = self.pool.get('ir.model.data')._get_id(self.cr, self.uid, module, xml_id)
obj = self.pool.get('ir.model.data').read(self.cr, self.uid, ir_id, ['res_id'])
id = int(obj['res_id'])
self.id_map[xml_id] = id
return id
def get_context(self, node, eval_dict):
context = self.context.copy()
if node.context:
context.update(eval(node.context, eval_dict))
return context
def isnoupdate(self, node):
return self.noupdate or node.noupdate or False
def process_comment(self, node):
return node
def _log_assert_failure(self, severity, msg, *args):
self.assert_report.record(False, severity)
self.logger.log(severity, msg, *args)
if severity >= config['assert_exit_level']:
raise YamlImportAbortion('Severe assertion failure (%s), aborting.' % logging.getLevelName(severity))
return
def _get_assertion_id(self, assertion):
if assertion.id:
ids = [self.get_id(assertion.id)]
elif assertion.search:
q = eval(assertion.search, self.eval_context)
ids = self.pool.get(assertion.model).search(self.cr, self.uid, q, context=assertion.context)
if not ids:
raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
return ids
def process_assert(self, node):
assertion, expressions = node.items()[0]
if self.isnoupdate(assertion) and self.mode != 'init':
return
model = self.get_model(assertion.model)
ids = self._get_assertion_id(assertion)
if assertion.count and len(ids) != assertion.count:
msg = 'assertion "%s" failed!\n' \
' Incorrect search count:\n' \
' expected count: %d\n' \
' obtained count: %d\n'
args = (assertion.string, assertion.count, len(ids))
self._log_assert_failure(assertion.severity, msg, *args)
else:
context = self.get_context(assertion, self.eval_context)
for id in ids:
record = model.browse(self.cr, self.uid, id, context)
for test in expressions.get('test', ''):
try:
success = eval(test, self.eval_context, RecordDictWrapper(record))
except Exception, e:
raise YamlImportAbortion(e)
if not success:
msg = 'Assertion "%s" FAILED\ntest: %s\n'
args = (assertion.string, test)
self._log_assert_failure(assertion.severity, msg, *args)
return
else: # all tests were successful for this assertion tag (no break)
self.assert_report.record(True, assertion.severity)
def process_record(self, node):
record, fields = node.items()[0]
self.validate_xml_id(record.id)
if self.isnoupdate(record) and self.mode != 'init':
model = self.get_model(record.model)
record_dict = self._create_record(model, fields)
self.logger.debug("RECORD_DICT %s" % record_dict)
id = self.pool.get('ir.model.data')._update(self.cr, self.uid, record.model, \
self.module, record_dict, record.id, noupdate=self.isnoupdate(record), mode=self.mode)
self.id_map[record.id] = int(id)
if config.get('import_partial', False):
self.cr.commit()
def _create_record(self, model, fields):
record_dict = {}
for field_name, expression in fields.items():
field_value = self._eval_field(model, field_name, expression)
record_dict[field_name] = field_value
return record_dict
def _eval_field(self, model, field_name, expression):
column = model._columns[field_name]
if column._type == "many2one":
value = self.get_id(expression)
elif column._type == "one2many":
other_model = self.get_model(column._obj)
value = [(0, 0, self._create_record(other_model, fields)) for fields in expression]
elif column._type == "many2many":
ids = [self.get_id(xml_id) for xml_id in expression]
value= [(6, 0, ids)]
else: # scalar field
if isinstance(expression, Eval):
value = eval(expression.expression)
else:
value = expression
# raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
return value
def process_context(self, node):
self.context = node.__dict__
if node.uid:
self.uid = self.get_id(node.uid)
if node.noupdate:
self.noupdate = node.noupdate
def process_python(self, node):
def log(msg, *args):
self.logger.log(logging.TEST, msg, *args)
python, statements = node.items()[0]
model = self.get_model(python.model)
statements = statements.replace("\r\n", "\n")
code_context = {'self': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
try:
code = compile(statements, self.filename, 'exec')
eval(code, {'ref': self.get_id}, code_context)
except AssertionError, e:
self._log_assert_failure(python.severity, 'AssertionError in Python code %s: %s', python.name, e)
return
except Exception, e:
raise YamlImportAbortion(e)
else:
self.assert_report.record(True, python.severity)
def process_workflow(self, node):
workflow, values = node.items()[0]
if self.isnoupdate(workflow) and self.mode != 'init':
return
model = self.get_model(workflow.model)
if workflow.ref:
id = self.get_id(workflow.ref)
else:
if not values:
raise YamlImportException('You must define a child node if you do not give a ref.')
if not len(values) == 1:
raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
value = values[0]
if not 'model' in value and (not 'eval' in value or not 'search' in value):
raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
value_model = self.get_model(value['model'])
local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)}
local_context.update(self.id_map)
id = eval(value['eval'], self.eval_context, local_context)
if workflow.uid is not None:
uid = workflow.uid
else:
uid = self.uid
wf_service = netsvc.LocalService("workflow")
wf_service.trg_validate(uid, model, id, workflow.action, self.cr)
def process_function(self, node):
function, values = node.items()[0]
if self.isnoupdate(function) and self.mode != 'init':
return
context = self.get_context(function, self.eval_context)
args = []
if function.eval:
args = eval(function.eval, self.eval_context)
for value in values:
if not 'model' in value and (not 'eval' in value or not 'search' in value):
raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
value_model = self.get_model(value['model'])
local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=context)}
local_context.update(self.id_map)
id = eval(value['eval'], self.eval_context, local_context)
if id != None:
args.append(id)
model = self.get_model(function.model)
method = function.name
getattr(model, method)(self.cr, self.uid, *args)
def _set_group_values(self, node, values):
if node.groups:
group_names = node.groups.split(',')
groups_value = []
for group in group_names:
if group.startswith('-'):
group_id = self.get_id(group[1:])
groups_value.append((3, group_id))
else:
group_id = self.get_id(group)
groups_value.append((4, group_id))
values['groups_id'] = groups_value
def process_menuitem(self, node):
self.validate_xml_id(node.id)
if not node.parent:
parent_id = False
self.cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (node.name,))
res = self.cr.fetchone()
values = {'parent_id': parent_id, 'name': node.name}
else:
parent_id = self.get_id(node.parent)
values = {'parent_id': parent_id}
if node.name:
values['name'] = node.name
try:
res = [ self.get_id(node.id) ]
except: # which exception ?
res = None
if node.action:
action_type = node.type or 'act_window'
icons = {
"act_window": 'STOCK_NEW',
"report.xml": 'STOCK_PASTE',
"wizard": 'STOCK_EXECUTE',
"url": 'STOCK_JUMP_TO',
}
values['icon'] = icons.get(action_type, 'STOCK_NEW')
if action_type == 'act_window':
action_id = self.get_id(node.action)
self.cr.execute('select view_type,view_mode,name,view_id,target from ir_act_window where id=%s', (action_id,))
ir_act_window_result = self.cr.fetchone()
assert ir_act_window_result, "No window action defined for this id %s !\n" \
"Verify that this is a window action or add a type argument." % (node.action,)
action_type, action_mode, action_name, view_id, target = ir_act_window_result
if view_id:
self.cr.execute('SELECT type FROM ir_ui_view WHERE id=%s', (view_id,))
# TODO guess why action_mode is ir_act_window.view_mode above and ir_ui_view.type here
action_mode = self.cr.fetchone()
self.cr.execute('SELECT view_mode FROM ir_act_window_view WHERE act_window_id=%s ORDER BY sequence LIMIT 1', (action_id,))
if self.cr.rowcount:
action_mode = self.cr.fetchone()
if action_type == 'tree':
values['icon'] = 'STOCK_INDENT'
elif action_mode and action_mode.startswith('tree'):
values['icon'] = 'STOCK_JUSTIFY_FILL'
elif action_mode and action_mode.startswith('graph'):
values['icon'] = 'terp-graph'
elif action_mode and action_mode.startswith('calendar'):
values['icon'] = 'terp-calendar'
if target == 'new':
values['icon'] = 'STOCK_EXECUTE'
if not values.get('name', False):
values['name'] = action_name
elif action_type == 'wizard':
action_id = self.get_id(node.action)
self.cr.execute('select name from ir_act_wizard where id=%s', (action_id,))
ir_act_wizard_result = self.cr.fetchone()
if (not values.get('name', False)) and ir_act_wizard_result:
values['name'] = ir_act_wizard_result[0]
else:
raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
if node.sequence:
values['sequence'] = node.sequence
if node.icon:
values['icon'] = node.icon
self._set_group_values(node, values)
pid = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
'ir.ui.menu', self.module, values, node.id, mode=self.mode, \
noupdate=self.isnoupdate(node), res_id=res and res[0] or False)
if node.id and parent_id:
self.id_map[node.id] = int(parent_id)
if node.action and pid:
action_type = node.type or 'act_window'
action_id = self.get_id(node.action)
action = "ir.actions.%s,%d" % (action_type, action_id)
self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
'tree_but_open', 'Menuitem', [('ir.ui.menu', int(parent_id))], action, True, True, xml_id=node.id)
def process_act_window(self, node):
self.validate_xml_id(node.id)
view_id = False
if node.view:
view_id = self.get_id(node.view)
context = eval(node.context, self.eval_context)
values = {
'name': node.name,
'type': type or 'ir.actions.act_window',
'view_id': view_id,
'domain': node.domain,
'context': context,
'res_model': node.res_model,
'src_model': node.src_model,
'view_type': node.view_type or 'form',
'view_mode': node.view_mode or 'tree,form',
'usage': node.usage,
'limit': node.limit,
'auto_refresh': node.auto_refresh,
}
self._set_group_values(node, values)
if node.target:
values['target'] = node.target
id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
self.id_map[node.id] = int(id)
if node.src_model:
keyword = 'client_action_relate'
value = 'ir.actions.act_window,%s' % id
replace = node.replace or True
self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', keyword, \
node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
# TODO add remove ir.model.data
def process_delete(self, node):
ids = []
if len(node.search):
ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
if len(node.id):
try:
ids.append(self.get_id(node.id))
except:
pass
if len(ids):
self.pool.get(node.model).unlink(self.cr, self.uid, ids)
self.pool.get('ir.model.data')._unlink(self.cr, self.uid, node.model, ids, direct=True)
def process_url(self, node):
self.validate_xml_id(node.id)
res = {'name': node.name, 'url': node.url, 'target': node.target}
id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
"ir.actions.url", self.module, res, node.id, mode=self.mode)
self.id_map[node.id] = int(id)
# ir_set
if (not node.menu or eval(node.menu)) and id:
keyword = node.keyword or 'client_action_multi'
value = 'ir.actions.url,%s' % id
replace = node.replace or True
self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
keyword, node.url, ["ir.actions.url"], value, replace=replace, \
noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
def process_ir_set(self, node):
if not self.mode == 'init':
return False
_, fields = node.items()[0]
res = {}
for fieldname, expression in fields.items():
if isinstance(expression, Eval):
value = eval(expression.expression, self.eval_context)
else:
value = expression
res[fieldname] = value
self.pool.get('ir.model.data').ir_set(self.cr, self.uid, res['key'], res['key2'], \
res['name'], res['models'], res['value'], replace=res.get('replace',True), \
isobject=res.get('isobject', False), meta=res.get('meta',None))
def process_report(self, node):
values = {}
for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
values[dest] = getattr(node, f)
assert values[dest], "Attribute %s of report is empty !" % (f,)
for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
if getattr(node, field):
values[dest] = getattr(node, field)
if node.auto:
values['auto'] = eval(node.auto)
if node.sxw:
sxw_content = misc.file_open(node.sxw).read()
values['report_sxw_content'] = sxw_content
if node.header:
values['header'] = eval(node.header)
values['multi'] = node.multi and eval(node.multi)
xml_id = node.id
self.validate_xml_id(xml_id)
self._set_group_values(node, values)
id = self.pool.get('ir.model.data')._update(self.cr, self.uid, "ir.actions.report.xml", \
self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
self.id_map[xml_id] = int(id)
if not node.menu or eval(node.menu):
keyword = node.keyword or 'client_print_multi'
value = 'ir.actions.report.xml,%s' % id
replace = node.replace or True
self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
def process_none(self):
"""
Empty node or commented node should not pass silently.
"""
self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
def process(self, yaml_string):
"""
Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
"""
is_preceded_by_comment = False
for node in yaml.load(yaml_string):
is_preceded_by_comment = self._log(node, is_preceded_by_comment)
try:
self._process_node(node)
except YamlImportException, e:
self.logger.log(logging.ERROR, e)
except Exception, e:
self.logger.log(logging.ERROR, e)
raise e
def _process_node(self, node):
if is_comment(node):
self.process_comment(node)
elif is_assert(node):
self.process_assert(node)
elif is_record(node):
self.process_record(node)
elif is_python(node):
self.process_python(node)
elif is_menuitem(node):
self.process_menuitem(node)
elif is_delete(node):
self.process_delete(node)
elif is_url(node):
self.process_url(node)
elif is_context(node):
self.process_context(node)
elif is_ir_set(node):
self.process_ir_set(node)
elif is_act_window(node):
self.process_act_window(node)
elif is_report(node):
self.process_report(node)
elif is_workflow(node):
if isinstance(node, types.DictionaryType):
self.process_workflow(node)
else:
self.process_workflow({node: []})
elif is_function(node):
if isinstance(node, types.DictionaryType):
self.process_function(node)
else:
self.process_function({node: []})
elif node is None:
self.process_none()
else:
raise YamlImportException("Can not process YAML block: %s" % node)
def _log(self, node, is_preceded_by_comment):
if is_comment(node):
is_preceded_by_comment = True
self.logger.log(logging.TEST, node)
elif not is_preceded_by_comment:
if isinstance(node, types.DictionaryType):
msg = "Creating %s\n with %s"
args = node.items()[0]
self.logger.log(logging.TEST, msg, *args)
else:
self.logger.log(logging.TEST, node)
else:
is_preceded_by_comment = False
return is_preceded_by_comment
def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False, report=None):
if idref is None:
idref = {}
yaml_string = yamlfile.read()
yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
yaml_interpreter.process(yaml_string)
# keeps convention of convert.py
convert_yaml_import = yaml_import
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
+9 -9
View File
@@ -2,17 +2,17 @@
ADMIN_PASSWD='admin'
method_1() {
cat '-' << EOF
cat '-' << EOF
<xml>
<methodCall>
<methodName>set_loglevel</methodName>
<params>
<param><value><string>$ADMIN_PASSWD</string></value>
</param>
<param>
<value><string>$1</string></value>
</param>
</params>
<methodName>set_loglevel</methodName>
<params>
<param><value><string>$ADMIN_PASSWD</string></value>
</param>
<param>
<value><string>$1</string></value>
</param>
</params>
</methodCall>
EOF
}
+39
View File
@@ -0,0 +1,39 @@
# Norwegian Bokmal translation for openobject-server
# Copyright (c) 2010 Rosetta Contributors and Canonical Ltd 2010
# This file is distributed under the same license as the openobject-server package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2010.
#
msgid ""
msgstr ""
"Project-Id-Version: openobject-server\n"
"Report-Msgid-Bugs-To: FULL NAME <EMAIL@ADDRESS>\n"
"POT-Creation-Date: 2009-08-24 22:41+0300\n"
"PO-Revision-Date: 2010-03-10 14:03+0000\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: Norwegian Bokmal <nb@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Launchpad-Export-Date: 2010-03-12 04:51+0000\n"
"X-Generator: Launchpad (build Unknown)\n"
#. Type: string
#. Description
#: ../openerp-server.templates:1001
msgid "Dedicated system account for the Open ERP server:"
msgstr ""
#. Type: string
#. Description
#: ../openerp-server.templates:1001
msgid ""
"The Open ERP server must use a dedicated account for its operation so that "
"the system's security is not compromised by running it with superuser "
"privileges."
msgstr ""
#. Type: string
#. Description
#: ../openerp-server.templates:1001
msgid "Please choose that account's username."
msgstr ""
+41
View File
@@ -0,0 +1,41 @@
# Slovak translation for openobject-addons
# Copyright (c) 2009 Rosetta Contributors and Canonical Ltd 2009
# This file is distributed under the same license as the openobject-addons package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2009.
#
msgid ""
msgstr ""
"Project-Id-Version: openobject-addons\n"
"Report-Msgid-Bugs-To: FULL NAME <EMAIL@ADDRESS>\n"
"POT-Creation-Date: 2009-08-24 22:41+0300\n"
"PO-Revision-Date: 2010-03-10 05:18+0000\n"
"Last-Translator: Peter Kohaut <peter.kohaut@gmail.com>\n"
"Language-Team: Slovak <sk@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Launchpad-Export-Date: 2010-03-12 04:51+0000\n"
"X-Generator: Launchpad (build Unknown)\n"
#. Type: string
#. Description
#: ../openerp-server.templates:1001
msgid "Dedicated system account for the Open ERP server:"
msgstr "Priradený systémový účet pre OpenERP server:"
#. Type: string
#. Description
#: ../openerp-server.templates:1001
msgid ""
"The Open ERP server must use a dedicated account for its operation so that "
"the system's security is not compromised by running it with superuser "
"privileges."
msgstr ""
"OpenERP server musí mať priradený účet pod ktorým bude pracovať. Bezpečnosť "
"systému nebude narušená tak, ako keby server pracoval pod superuser účtom."
#. Type: string
#. Description
#: ../openerp-server.templates:1001
msgid "Please choose that account's username."
msgstr "Prosím vyberte používateľské meno účtu."
+4 -4
View File
@@ -2,12 +2,12 @@
# ADMIN_PASSWD='admin'
method_1() {
cat '-' << EOF
cat '-' << EOF
<xml>
<methodCall>
<methodName>get_stats</methodName>
<params>
</params>
<methodName>get_stats</methodName>
<params>
</params>
</methodCall>
EOF
}
+2 -1
View File
@@ -59,6 +59,7 @@ required_modules = [
('pydot', 'pydot module'),
('pytz', 'Timezone handling library for Python'),
('reportlab', 'reportlab module'),
('yaml', 'YAML parser and emitter for Python'),
]
def check_modules():
@@ -174,7 +175,7 @@ options = {
"lxml.objectify", "decimal", "xml", "encodings",
"dateutil", "wizard", "pychart", "PIL", "pyparsing",
"pydot", "asyncore","asynchat", "reportlab", "vobject",
"HTMLParser", "select"],
"HTMLParser", "select", "yaml"],
"excludes" : ["Tkconstants","Tkinter","tcl"],
}
}