bzr revid: olt@tinyerp.com-20090811130141-8bfrv1qv587j4kx0
This commit is contained in:
olt
2009-08-11 09:01:41 -04:00
52 changed files with 127752 additions and 12952 deletions
+1 -1
View File
@@ -328,7 +328,7 @@ CREATE TABLE ir_model_data (
write_date timestamp without time zone,
write_uid integer,
noupdate boolean,
name character varying(64) NOT NULL,
name character varying(128) NOT NULL,
date_init timestamp without time zone,
date_update timestamp without time zone,
module character varying(64) NOT NULL,
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+18 -18
View File
@@ -25,7 +25,7 @@ from osv.orm import except_orm
import tools
class ir_attachment(osv.osv):
def check(self, cr, uid, ids, mode):
def check(self, cr, uid, ids, mode, context=None):
if not ids:
return
ima = self.pool.get('ir.model.access')
@@ -34,7 +34,7 @@ class ir_attachment(osv.osv):
cr.execute('select distinct res_model from ir_attachment where id in ('+','.join(map(str, ids))+')')
for obj in cr.fetchall():
if obj[0]:
ima.check(cr, uid, obj[0], mode)
ima.check(cr, uid, obj[0], mode, context=context)
def search(self, cr, uid, args, offset=0, limit=None, order=None,
context=None, count=False):
@@ -52,7 +52,7 @@ class ir_attachment(osv.osv):
if m['res_model']:
if m['res_model'] not in cache:
cache[m['res_model']] = ima.check(cr, uid, m['res_model'], 'read',
raise_exception=False)
raise_exception=False, context=context)
if not cache[m['res_model']]:
ids.remove(m['id'])
@@ -60,26 +60,26 @@ class ir_attachment(osv.osv):
return len(ids)
return ids
def read(self, cr, uid, ids, *args, **kwargs):
self.check(cr, uid, ids, 'read')
return super(ir_attachment, self).read(cr, uid, ids, *args, **kwargs)
def read(self, cr, uid, ids, fields_to_read=None, context=None, load='_classic_read'):
self.check(cr, uid, ids, 'read', context=context)
return super(ir_attachment, self).read(cr, uid, ids, fields_to_read, context, load)
def write(self, cr, uid, ids, *args, **kwargs):
self.check(cr, uid, ids, 'write')
return super(ir_attachment, self).write(cr, uid, ids, *args, **kwargs)
def write(self, cr, uid, ids, vals, context=None):
self.check(cr, uid, ids, 'write', context=context)
return super(ir_attachment, self).write(cr, uid, ids, vals, context)
def copy(self, cr, uid, id, *args, **kwargs):
self.check(cr, uid, [id], 'write')
return super(ir_attachment, self).copy(cr, uid, id, *args, **kwargs)
def copy(self, cr, uid, id, default=None, context=None):
self.check(cr, uid, [id], 'write', context=context)
return super(ir_attachment, self).copy(cr, uid, id, default, context)
def unlink(self, cr, uid, ids, *args, **kwargs):
self.check(cr, uid, ids, 'unlink')
return super(ir_attachment, self).unlink(cr, uid, ids, *args, **kwargs)
def unlink(self, cr, uid, ids, context=None):
self.check(cr, uid, ids, 'unlink', context=context)
return super(ir_attachment, self).unlink(cr, uid, ids, context)
def create(self, cr, uid, values, *args, **kwargs):
def create(self, cr, uid, values, context=None):
if 'res_model' in values and values['res_model'] != '':
self.pool.get('ir.model.access').check(cr, uid, values['res_model'], 'create')
return super(ir_attachment, self).create(cr, uid, values, *args, **kwargs)
self.pool.get('ir.model.access').check(cr, uid, values['res_model'], 'create', context=context)
return super(ir_attachment, self).create(cr, uid, values, context)
def action_get(self, cr, uid, context=None):
dataobj = self.pool.get('ir.model.data')
+9 -5
View File
@@ -73,7 +73,7 @@ class ir_model(osv.osv):
def write(self, cr, user, ids, vals, context=None):
if context:
del context['__last_update']
context.pop('__last_update', None)
return super(ir_model,self).write(cr, user, ids, vals, context)
def create(self, cr, user, vals, context=None):
@@ -229,6 +229,9 @@ class ir_model_fields(osv.osv):
'field_description': lambda *a: '',
}
_order = "id"
_sql_constraints = [
('size_gt_zero', 'CHECK (size>0)', 'Size of the field can never be less than 1 !'),
]
def unlink(self, cr, user, ids, context=None):
for field in self.browse(cr, user, ids, context):
if field.state <> 'manual':
@@ -244,17 +247,18 @@ class ir_model_fields(osv.osv):
vals['model'] = model_data.model
if context and context.get('manual',False):
vals['state'] = 'manual'
res = super(ir_model_fields,self).create(cr, user, vals, context)
res = super(ir_model_fields,self).create(cr, user, vals, context)
if vals.get('state','base') == 'manual':
if not vals['name'].startswith('x_'):
raise except_orm(_('Error'), _("Custom fields must have a name that starts with 'x_' !"))
if 'relation' in vals and not self.pool.get('ir.model').search(cr, user, [('model','=',vals['relation'])]):
raise except_orm(_('Error'), _("Model %s Does not Exist !" % vals['relation']))
if self.pool.get(vals['model']):
self.pool.get(vals['model']).__init__(self.pool, cr)
self.pool.get(vals['model'])._auto_init(cr, {})
return res
ir_model_fields()
@@ -312,7 +316,7 @@ class ir_model_access(osv.osv):
# pass no groups -> no access
return False
def check(self, cr, uid, model, mode='read', raise_exception=True):
def check(self, cr, uid, model, mode='read', raise_exception=True, context=None):
if uid==1:
# User root have all accesses
# TODO: exclude xml-rpc requests
@@ -400,7 +404,7 @@ ir_model_access()
class ir_model_data(osv.osv):
_name = 'ir.model.data'
_columns = {
'name': fields.char('XML Identifier', required=True, size=64),
'name': fields.char('XML Identifier', required=True, size=128),
'model': fields.char('Object', required=True, size=64),
'module': fields.char('Module', required=True, size=64),
'res_id': fields.integer('Resource ID'),
+1 -1
View File
@@ -35,7 +35,7 @@ def _check_xml(self, cr, uid, ids, context={}):
if not relaxng.validate(eview):
logger = netsvc.Logger()
logger.notifyChannel('init', netsvc.LOG_ERROR, 'The view does not fit the required schema !')
logger.notifyChannel('init', netsvc.LOG_ERROR, relaxng.error_log.last_error)
logger.notifyChannel('init', netsvc.LOG_ERROR, tools.ustr(relaxng.error_log.last_error))
return False
return True
+4 -2
View File
@@ -7,8 +7,10 @@
<xsl:variable name="rightMargin">1cm</xsl:variable>
<xsl:variable name="topMargin">1cm</xsl:variable>
<xsl:variable name="bottomMargin">1cm</xsl:variable>
<xsl:variable name="pageSize">29.7cm,21cm</xsl:variable>
<!--:variable name="pageSize">29.7cm,21cm</xsl:variable> Or use default width and height for frame -->
<xsl:variable name="pageSize">
<xsl:value-of select="/report/config/PageSize"/>
</xsl:variable>
<xsl:variable name="page_format">a4_letter</xsl:variable>
<xsl:template name="first_page_frames">
+31 -9
View File
@@ -103,14 +103,24 @@ class expression(object):
left, operator, right = e
working_table = table
if left in table._inherit_fields:
working_table = table.pool.get(table._inherit_fields[left][0])
if working_table not in self.__tables.values():
self.__joins.append(('%s.%s=%s.%s' % (working_table._table, 'id', table._table, table._inherits[working_table._name]), working_table._table))
self.__tables[i] = working_table
main_table = table
fargs = left.split('.', 1)
index = i
if left in table._inherit_fields:
while True:
field = main_table._columns.get(fargs[0], False)
if field:
working_table = main_table
self.__tables[index-1] = self.__tables[i]
self.__tables[i] = working_table
break
working_table = main_table.pool.get(main_table._inherit_fields[left][0])
if working_table not in self.__tables.values():
self.__joins.append(('%s.%s=%s.%s' % (working_table._table, 'id', main_table._table, main_table._inherits[working_table._name]), working_table._table))
self.__tables[index] = working_table
index += 1
main_table = working_table
field = working_table._columns.get(fargs[0], False)
if not field:
if left == 'id' and operator == 'child_of':
@@ -198,10 +208,22 @@ class expression(object):
self.__exp[i] = (left, 'in', right)
else:
# other field type
# add the time part to datetime field when it's not there:
if field._type == 'datetime' and self.__exp[i][2] and len(self.__exp[i][2]) == 10:
self.__exp[i] = list(self.__exp[i])
if operator in ('>', '>='):
self.__exp[i][2] += ' 00:00:00'
elif operator in ('<', '<='):
self.__exp[i][2] += ' 23:59:59'
self.__exp[i] = tuple(self.__exp[i])
if field.translate:
if operator in ('like', 'ilike', 'not like', 'not ilike'):
right = '%%%s%%' % right
operator = operator == '=like' and 'like' or operator
query1 = '( SELECT res_id' \
@@ -224,7 +246,7 @@ class expression(object):
' SELECT id' \
' FROM "' + working_table._table + '"' \
' WHERE "' + left + '" ' + operator + instr + ")"
query2 = [working_table._name + ',' + left,
context.get('lang', False) or 'en_US',
'model',
+11 -8
View File
@@ -827,15 +827,18 @@ class property(function):
int(prop.value.split(',')[1])) or False
obj = obj.pool.get(self._obj)
existing_ids = obj.search(cr, uid, [('id','in',res.values())])
deleted_ids = []
for res_id in res.values():
if res_id and (res_id not in existing_ids):
if res_id not in deleted_ids:
cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
deleted_ids.append(res_id)
names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
to_check = res.values()
if default_val and default_val not in to_check:
to_check += [default_val]
existing_ids = obj.search(cr, uid, [('id', 'in', to_check)])
for id, res_id in res.items():
if res_id not in existing_ids:
cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
res[id] = default_val
names = dict(obj.name_get(cr, uid, existing_ids, context))
for r in res.keys():
if res[r] and res[r] in names:
res[r] = (res[r], names[res[r]])
+191 -77
View File
@@ -381,8 +381,12 @@ class orm_template(object):
vals['select_level']
))
if 'module' in context:
name1 = 'field_' + self._table + '_' + k
cr.execute("select name from ir_model_data where name=%s", (name1,))
if cr.fetchone():
name1 = name1 + "_" + str(id)
cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
(('field_'+self._table+'_'+k)[:64], context['module'], 'ir.model.fields', id)
(name1, context['module'], 'ir.model.fields', id)
)
else:
for key, val in vals.items():
@@ -434,32 +438,45 @@ class orm_template(object):
def __export_row(self, cr, uid, row, fields, context=None):
def check_type(type,r):
if type == 'float':
def check_type(field_type):
if field_type == 'float':
return 0.0
elif type == 'integer':
elif field_type == 'integer':
return 0
elif type == 'char':
return ''
return r
elif field_type == 'boolean':
return False
return ''
lines = []
data = map(lambda x: '', range(len(fields)))
done = []
for fpos in range(len(fields)):
f = fields[fpos]
f = fields[fpos]
if f:
r = row
i = 0
while i < len(f):
r = r[f[i]]
if f[i] == 'db_id':
r = r['id']
elif f[i] == 'id':
model_data = self.pool.get('ir.model.data')
data_ids = model_data.search(cr, uid, [('model','=',r._table_name),('res_id','=',r['id'])])
if len(data_ids):
d = model_data.read(cr, uid, data_ids, ['name','module'])[0]
if d['module']:
r = '%s.%s'%(d['module'],d['name'])
else:
r = d['name']
else:
break
else:
r = r[f[i]]
if not r:
if f[i] in self._columns:
r = check_type(self._columns[f[i]]._type,r)
r = check_type(self._columns[f[i]]._type)
elif f[i] in self._inherit_fields:
r = check_type(self._inherit_fields[f[i]][2]._type,r)
data[fpos] = tools.ustr(r)
r = check_type(self._inherit_fields[f[i]][2]._type)
data[fpos] = r
break
if isinstance(r, (browse_record_list, list)):
first = True
@@ -467,56 +484,89 @@ class orm_template(object):
or [], fields)
if fields2 in done:
break
done.append(fields2)
done.append(fields2)
for row2 in r:
lines2 = self.__export_row(cr, uid, row2, fields2,
context)
context)
if first:
for fpos2 in range(len(fields)):
if lines2 and lines2[0][fpos2]:
data[fpos2] = lines2[0][fpos2]
if not data[fpos]:
dt = ''
for rr in r :
if isinstance(rr.name, browse_record):
rr = rr.name
dt+=rr.name+','
data[fpos] = dt[:-1]
break
lines += lines2[1:]
first = False
else:
lines += lines2
lines += lines2
break
i += 1
if i == len(f):
if isinstance(r, browse_record):
r = r.name
data[fpos] = tools.ustr(r or '')
return [data] + lines
def export_data(self, cr, uid, ids, fields, context=None):
def export_data(self, cr, uid, ids, fields_to_export, context=None):
if not context:
context = {}
fields = map(lambda x: x.split('/'), fields)
imp_comp = context.get('import_comp',False)
cols = self._columns.copy()
for f in self._inherit_fields:
cols.update({f: self._inherit_fields[f][2]})
fields_to_export = map(lambda x: x.split('/'), fields_to_export)
fields_export = fields_to_export+[]
warning = ''
warning_fields = []
for field in fields_export:
if imp_comp and len(field)>1:
warning_fields.append('/'.join(map(lambda x:x in cols and cols[x].string or x,field)))
elif len (field) <=1:
if imp_comp and cols.get(field and field[0],False):
if ((isinstance(cols[field[0]], fields.function) and not cols[field[0]].store) \
or isinstance(cols[field[0]], fields.related)\
or isinstance(cols[field[0]], fields.one2many)):
warning_fields.append('/'.join(map(lambda x:x in cols and cols[x].string or x,field)))
datas = []
if imp_comp and len(warning_fields):
warning = 'Following columns cannot be exported since you select to be import compatible.\n%s' %('\n'.join(warning_fields))
cr.rollback()
return {'warning' : warning}
for row in self.browse(cr, uid, ids, context):
datas += self.__export_row(cr, uid, row, fields, context)
return datas
datas += self.__export_row(cr, uid, row, fields_to_export, context)
return {'datas':datas}
def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
if not context:
context = {}
fields = map(lambda x: x.split('/'), fields)
logger = netsvc.Logger()
def process_liness(self, datas, prefix, fields_def, position=0):
ir_model_data_obj = self.pool.get('ir.model.data')
def process_liness(self, datas, prefix, current_module, model_name, fields_def, position=0):
line = datas[position]
row = {}
translate = {}
todo = []
warning = ''
data_id = False
data_res_id = False
is_xml_id = False
is_db_id = False
ir_model_data_obj = self.pool.get('ir.model.data')
#
# Import normal fields
#
for i in range(len(fields)):
if i >= len(line):
raise Exception(_('Please check that all your lines have %d columns.') % (len(fields),))
field = fields[i]
if field == ["id"]:
data_id = line[i]
if not line[i]:
continue
field = fields[i]
if (len(field)==len(prefix)+1) and field[len(prefix)].endswith(':id'):
res_id = False
if line[i]:
@@ -526,8 +576,7 @@ class orm_template(object):
if '.' in word:
module, xml_id = word.rsplit('.', 1)
else:
module, xml_id = current_module, word
ir_model_data_obj = self.pool.get('ir.model.data')
module, xml_id = current_module, word
id = ir_model_data_obj._get_id(cr, uid, module,
xml_id)
res_id2 = ir_model_data_obj.read(cr, uid, [id],
@@ -540,8 +589,7 @@ class orm_template(object):
if '.' in line[i]:
module, xml_id = line[i].rsplit('.', 1)
else:
module, xml_id = current_module, line[i]
ir_model_data_obj = self.pool.get('ir.model.data')
module, xml_id = current_module, line[i]
id = ir_model_data_obj._get_id(cr, uid, module, xml_id)
res_id = ir_model_data_obj.read(cr, uid, [id],
['res_id'])[0]['res_id']
@@ -554,10 +602,67 @@ class orm_template(object):
continue
if (len(field) == len(prefix)+1) and \
(prefix == field[0:len(prefix)]):
if field[len(prefix)] == "id":
# XML ID
db_id = False
is_xml_id = data_id = line[i]
d = data_id.split('.')
module = len(d)>1 and d[0] or ''
name = len(d)>1 and d[1] or d[0]
data_ids = ir_model_data_obj.search(cr, uid, [('module','=',module),('model','=',model_name),('name','=',name)])
if len(data_ids):
d = ir_model_data_obj.read(cr, uid, data_ids, ['res_id'])[0]
db_id = d['res_id']
if is_db_id and not db_id:
data_ids = ir_model_data_obj.search(cr, uid, [('module','=',module),('model','=',model_name),('res_id','=',is_db_id)])
if not len(data_ids):
ir_model_data_obj.create(cr, uid, {'module':module, 'model':model_name, 'name':name, 'res_id':is_db_id})
db_id = is_db_id
if is_db_id and int(db_id) != int(is_db_id):
warning += ("Id is not the same than existing one: " + str(is_db_id) + " !\n")
logger.notifyChannel("import", netsvc.LOG_ERROR,
"Id is not the same than existing one: " + str(is_db_id) + ' !\n')
continue
if field[len(prefix)] == "db_id":
# Database ID
try:
line[i]= int(line[i])
except Exception, e:
warning += (str(e) + "!\n")
logger.notifyChannel("import", netsvc.LOG_ERROR,
str(e) + '!\n')
continue
is_db_id = line[i]
obj_model = self.pool.get(model_name)
ids = obj_model.search(cr, uid, [('id','=',line[i])])
if not len(ids):
warning += ("Database ID doesn't exist: " + model_name + ": " + str(line[i]) + " !\n")
logger.notifyChannel("import", netsvc.LOG_ERROR,
"Database ID doesn't exist: " + model_name + ": " + str(line[i]) + ' !\n')
continue
else:
data_res_id = ids[0]
data_ids = ir_model_data_obj.search(cr, uid, [('model','=',model_name),('res_id','=',line[i])])
if len(data_ids):
d = ir_model_data_obj.read(cr, uid, data_ids, ['name','module'])[0]
data_id = d['name']
if d['module']:
data_id = '%s.%s'%(d['module'],d['name'])
else:
data_id = d['name']
if is_xml_id and not data_id:
data_id = is_xml_id
if is_xml_id and is_xml_id!=data_id:
warning += ("Id is not the same than existing one: " + str(line[i]) + " !\n")
logger.notifyChannel("import", netsvc.LOG_ERROR,
"Id is not the same than existing one: " + str(line[i]) + ' !\n')
continue
if fields_def[field[len(prefix)]]['type'] == 'integer':
res = line[i] and int(line[i])
elif fields_def[field[len(prefix)]]['type'] == 'boolean':
res = line[i] and eval(line[i])
res = line[i] and bool(line[i])
elif fields_def[field[len(prefix)]]['type'] == 'float':
res = line[i] and float(line[i])
elif fields_def[field[len(prefix)]]['type'] == 'selection':
@@ -569,7 +674,7 @@ class orm_template(object):
sel = fields_def[field[len(prefix)]]['selection'](self,
cr, uid, context)
for key, val in sel:
if line[i] in [str(key),str(val)]: #Acepting key or value for selection field
if line[i] in [tools.ustr(key),tools.ustr(val)]: #Acepting key or value for selection field
res = key
break
if line[i] and not res:
@@ -584,7 +689,7 @@ class orm_template(object):
if line[i]:
relation = fields_def[field[len(prefix)]]['relation']
res2 = self.pool.get(relation).name_search(cr, uid,
line[i], [], operator='=')
line[i], [], operator='=', context=context)
res = (res2 and res2[0][0]) or False
if not res:
warning += ('Relation not found: ' + line[i] + \
@@ -598,7 +703,7 @@ class orm_template(object):
relation = fields_def[field[len(prefix)]]['relation']
for word in line[i].split(config.get('csv_internal_sep')):
res2 = self.pool.get(relation).name_search(cr,
uid, word, [], operator='=')
uid, word, [], operator='=', context=context)
res3 = (res2 and res2[0][0]) or False
if not res3:
warning += ('Relation not found: ' + \
@@ -618,19 +723,20 @@ class orm_template(object):
if field[0] not in todo:
todo.append(field[len(prefix)])
#
# Import one2many fields
# Import one2many, many2many fields
#
nbrmax = 1
for field in todo:
newfd = self.pool.get(fields_def[field]['relation']).fields_get(
relation_obj = self.pool.get(fields_def[field]['relation'])
newfd = relation_obj.fields_get(
cr, uid, context=context)
res = process_liness(self, datas, prefix + [field], newfd, position)
(newrow, max2, w2, translate2, data_id2) = res
res = process_liness(self, datas, prefix + [field], current_module, relation_obj._name, newfd, position)
(newrow, max2, w2, translate2, data_id2, data_res_id2) = res
nbrmax = max(nbrmax, max2)
warning = warning + w2
reduce(lambda x, y: x and y, newrow)
warning = warning + w2
reduce(lambda x, y: x and y, newrow)
row[field] = (reduce(lambda x, y: x or y, newrow.values()) and \
[(0, 0, newrow)]) or []
[(0, 0, newrow)]) or []
i = max2
while (position+i)<len(datas):
ok = True
@@ -641,11 +747,11 @@ class orm_template(object):
if not ok:
break
(newrow, max2, w2, translate2, data_id2) = process_liness(
self, datas, prefix+[field], newfd, position+i)
(newrow, max2, w2, translate2, data_id2, data_res_id2) = process_liness(
self, datas, prefix+[field], current_module, relation_obj._name, newfd, position+i)
warning = warning+w2
if reduce(lambda x, y: x or y, newrow.values()):
row[field].append((0, 0, newrow))
row[field].append((0, 0, newrow))
i += max2
nbrmax = max(nbrmax, i)
@@ -653,7 +759,7 @@ class orm_template(object):
for i in range(max(nbrmax, 1)):
#if datas:
datas.pop(0)
result = (row, nbrmax, warning, translate, data_id)
result = (row, nbrmax, warning, translate, data_id, data_res_id)
return result
fields_def = self.fields_get(cr, uid, context=context)
@@ -668,16 +774,16 @@ class orm_template(object):
counter += 1
res = {}
#try:
(res, other, warning, translate, data_id) = \
process_liness(self, datas, [], fields_def)
if warning:
(res, other, warning, translate, data_id, res_id) = \
process_liness(self, datas, [], current_module, self._name, fields_def)
if warning:
cr.rollback()
return (-1, res, 'Line ' + str(counter) +' : ' + warning, '')
try:
id = self.pool.get('ir.model.data')._update(cr, uid, self._name,
id = ir_model_data_obj._update(cr, uid, self._name,
current_module, res, xml_id=data_id, mode=mode,
noupdate=noupdate)
noupdate=noupdate, res_id=res_id)
except Exception, e:
import psycopg2
if isinstance(e,psycopg2.IntegrityError):
@@ -1209,7 +1315,7 @@ class orm_template(object):
def read_string(self, cr, uid, id, langs, fields=None, context=None):
res = {}
res2 = {}
self.pool.get('ir.model.access').check(cr, uid, 'ir.translation', 'read')
self.pool.get('ir.model.access').check(cr, uid, 'ir.translation', 'read', context=context)
if not fields:
fields = self._columns.keys() + self._inherit_fields.keys()
for lang in langs:
@@ -1232,7 +1338,7 @@ class orm_template(object):
return res
def write_string(self, cr, uid, id, langs, vals, context=None):
self.pool.get('ir.model.access').check(cr, uid, 'ir.translation', 'write')
self.pool.get('ir.model.access').check(cr, uid, 'ir.translation', 'write', context=context)
for lang in langs:
for field in vals:
if field in self._columns:
@@ -1933,13 +2039,13 @@ class orm(orm_template):
self._inherits_reload_src()
def fields_get(self, cr, user, fields=None, context=None):
read_access = self.pool.get('ir.model.access').check(cr, user, self._name, 'write', raise_exception=False)
read_access = self.pool.get('ir.model.access').check(cr, user, self._name, 'write', raise_exception=False, context=context)
return super(orm, self).fields_get(cr, user, fields, context, read_access)
def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
if not context:
context = {}
self.pool.get('ir.model.access').check(cr, user, self._name, 'read')
self.pool.get('ir.model.access').check(cr, user, self._name, 'read', context=context)
if not fields:
fields = self._columns.keys() + self._inherit_fields.keys()
select = ids
@@ -2154,11 +2260,18 @@ class orm(orm_template):
self._check_concurrency(cr, ids, context)
self.pool.get('ir.model.access').check(cr, uid, self._name, 'unlink')
self.pool.get('ir.model.access').check(cr, uid, self._name, 'unlink', context=context)
properties = self.pool.get('ir.property')
domain = [('res_id', '=', False),
('value', 'in', ['%s,%s' % (self._name, i) for i in ids]),
]
if properties.search(cr, uid, domain, context=context):
raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
wf_service = netsvc.LocalService("workflow")
for id in ids:
wf_service.trg_delete(uid, self._name, id, cr)
for oid in ids:
wf_service.trg_delete(uid, self._name, oid, cr)
#cr.execute('select * from '+self._table+' where id in ('+str_d+')', ids)
#res = cr.dictfetchall()
@@ -2176,7 +2289,7 @@ class orm(orm_template):
if d1:
cr.execute('SELECT id FROM "'+self._table+'" ' \
'WHERE id IN ('+str_d+')'+d1, sub_ids+d2)
if not cr.rowcount == len({}.fromkeys(ids)):
if not cr.rowcount == len(sub_ids):
raise except_orm(_('AccessError'),
_('You try to bypass an access rule (Document type: %s).') % \
self._description)
@@ -2188,13 +2301,13 @@ class orm(orm_template):
cr.execute('delete from "'+self._table+'" ' \
'where id in ('+str_d+')', sub_ids)
for order, object, ids, fields in result_store:
for order, object, store_ids, fields in result_store:
if object<>self._name:
obj = self.pool.get(object)
cr.execute('select id from '+obj._table+' where id in ('+','.join(map(str, ids))+')')
ids = map(lambda x: x[0], cr.fetchall())
if ids:
obj._store_set_values(cr, uid, ids, fields, context)
cr.execute('select id from '+obj._table+' where id in ('+','.join(map(str, store_ids))+')')
rids = map(lambda x: x[0], cr.fetchall())
if rids:
obj._store_set_values(cr, uid, rids, fields, context)
return True
#
@@ -2240,7 +2353,7 @@ class orm(orm_template):
self._check_concurrency(cr, ids, context)
self.pool.get('ir.model.access').check(cr, user, self._name, 'write')
self.pool.get('ir.model.access').check(cr, user, self._name, 'write', context=context)
upd0 = []
upd1 = []
@@ -2321,7 +2434,7 @@ class orm(orm_template):
# call the 'set' method of fields which are not classic_write
upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
# default element in context must be remove when call a one2many or many2many
# default element in context must be removed when call a one2many or many2many
rel_context = context.copy()
for c in context.items():
if c[0].startswith('default_'):
@@ -2411,7 +2524,7 @@ class orm(orm_template):
"""
if not context:
context = {}
self.pool.get('ir.model.access').check(cr, user, self._name, 'create')
self.pool.get('ir.model.access').check(cr, user, self._name, 'create', context=context)
default = []
@@ -2474,12 +2587,13 @@ class orm(orm_template):
#End
for field in vals:
if self._columns[field]._classic_write:
upd0 = upd0 + ',"' + field + '"'
upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
upd2.append(self._columns[field]._symbol_set[1](vals[field]))
else:
upd_todo.append(field)
if field in self._columns:
if self._columns[field]._classic_write:
upd0 = upd0 + ',"' + field + '"'
upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
upd2.append(self._columns[field]._symbol_set[1](vals[field]))
else:
upd_todo.append(field)
if field in self._columns \
and hasattr(self._columns[field], 'selection') \
and vals[field]:
@@ -2529,12 +2643,12 @@ class orm(orm_template):
cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1,pleft+2,id_new))
# default element in context must be remove when call a one2many or many2many
# default element in context must be removed when call a one2many or many2many
rel_context = context.copy()
for c in context.items():
if c[0].startswith('default_'):
del rel_context[c[0]]
for field in upd_todo:
self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context)
self._validate(cr, user, [id_new], context)
@@ -2733,7 +2847,7 @@ class orm(orm_template):
if 'state' in self._defaults:
default['state'] = self._defaults['state'](self, cr, uid, context)
data = self.read(cr, uid, [id], context=context)[0]
fields = self.fields_get(cr, uid)
fields = self.fields_get(cr, uid, context=context)
trans_data=[]
for f in fields:
ftype = fields[f]['type']
@@ -2792,11 +2906,11 @@ class orm(orm_template):
def copy(self, cr, uid, id, default=None, context=None):
trans_obj = self.pool.get('ir.translation')
data, trans_data = self.copy_data(cr, uid, id, default, context)
new_id=self.create(cr, uid, data)
new_id = self.create(cr, uid, data, context)
for record in trans_data:
del record['id']
record['res_id']=new_id
trans_obj.create(cr,uid,record)
record['res_id'] = new_id
trans_obj.create(cr, uid, record, context)
return new_id
def exists(self, cr, uid, id, context=None):
+34 -8
View File
@@ -27,8 +27,10 @@ from lxml import etree
from report import render
import libxml2
import libxslt
import locale
import time, os
import mx.DateTime
class report_printscreen_list(report_int):
def __init__(self, name):
@@ -70,7 +72,16 @@ class report_printscreen_list(report_int):
result = model.fields_view_get(cr, uid, view_type='tree', context=context)
fields_order = self._parse_string(result['arch'])
rows = model.read(cr, uid, datas['ids'], result['fields'].keys(), context )
rows = model.read(cr, uid, datas['ids'], result['fields'].keys(), context)
ids2 = [x['id'] for x in rows] # getting the ids from read result
if datas['ids'] != ids2: # sorted ids were not taken into consideration for print screen
rows_new = []
for id in datas['ids']:
element = [elem for elem in rows if elem['id']==id]
rows_new.append(element[0])
rows = rows_new
res = self._create_table(uid, datas['ids'], result['fields'], fields_order, rows, context, model_desc)
return (self.obj.get(), 'pdf')
@@ -87,7 +98,8 @@ class report_printscreen_list(report_int):
n.text = text
config.append(n)
_append_node('date', time.strftime('%d/%m/%Y'))
#_append_node('date', time.strftime('%d/%m/%Y'))
_append_node('date', time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))))
_append_node('PageSize', '%.2fmm,%.2fmm' % tuple(pageSize))
_append_node('PageWidth', '%.2f' % (pageSize[0] * 2.8346,))
_append_node('PageHeight', '%.2f' %(pageSize[1] * 2.8346,))
@@ -106,7 +118,7 @@ class report_printscreen_list(report_int):
for f in fields_order:
s = 0
ince += 1
if fields[f]['type'] in ('date','time','float','integer'):
if fields[f]['type'] in ('date','time','datetime','float','integer'):
s = 60
strmax -= s
if fields[f]['type'] in ('float','integer'):
@@ -132,13 +144,11 @@ class report_printscreen_list(report_int):
new_doc.append(header)
lines = etree.Element("lines")
tsum = []
count = len(fields_order)
for i in range(0,count):
tsum.append(0)
for line in results:
node_line = etree.Element("row")
count = -1
@@ -158,10 +168,28 @@ class report_printscreen_list(report_int):
if fields[f]['type'] in ('one2many','many2many') and line[f]:
line[f] = '( '+tools.ustr(len(line[f])) + ' )'
if fields[f]['type'] == 'float':
if fields[f]['type'] == 'float' and line[f]:
precision=(('digits' in fields[f]) and fields[f]['digits'][1]) or 2
line[f]='%.2f'%(line[f])
if fields[f]['type'] == 'date' and line[f]:
format = str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))
d1= mx.DateTime.strptime(line[f],'%Y-%m-%d')
new_d1 = d1.strftime(format)
line[f] = new_d1
if fields[f]['type'] == 'time' and line[f]:
format = str(locale.nl_langinfo(locale.T_FMT))
d1= mx.DateTime.strptime(line[f],'%H:%M:%S')
new_d1 = d1.strftime(format)
line[f] = new_d1
if fields[f]['type'] == 'datetime' and line[f]:
format = str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))+' '+str(locale.nl_langinfo(locale.T_FMT))
d1= mx.DateTime.strptime(line[f],'%Y-%m-%d %H:%M:%S')
new_d1 = d1.strftime(format)
line[f] = new_d1
col = etree.Element("col")
col.set('para','yes')
col.set('tree','no')
@@ -169,7 +197,6 @@ class report_printscreen_list(report_int):
col.text = tools.ustr(line[f] or '')
if temp[count] == 1:
tsum[count] = float(tsum[count]) + float(line[f]);
else:
col.text = '/'
node_line.append(col)
@@ -197,7 +224,6 @@ class report_printscreen_list(report_int):
lines.append(node_line)
new_doc.append(lines)
styledoc = libxml2.parseFile(os.path.join(tools.config['root_path'],'addons/base/report/custom_new.xsl'))
style = libxslt.parseStylesheetDoc(styledoc)
+6 -6
View File
@@ -203,7 +203,7 @@ class _rml_doc(object):
self.canvas.save()
class _rml_canvas(object):
def __init__(self, canvas,localcontext, doc_tmpl=None, doc=None, images={}, path='.', title=None):
def __init__(self, canvas, localcontext, doc_tmpl=None, doc=None, images={}, path='.', title=None):
self.localcontext = localcontext
self.canvas = canvas
self.styles = doc.styles
@@ -216,7 +216,7 @@ class _rml_canvas(object):
self.canvas.setTitle(self.title)
def _textual(self, node, x=0, y=0):
rc = utils._process_text(self, node.text or '')
rc = utils._process_text(self, node.text.encode('utf-8') or '')
for n in node:
if n.tag == 'seq':
from reportlab.lib.sequencer import getSequencer
@@ -295,7 +295,7 @@ class _rml_canvas(object):
self.canvas.circle(x_cen=utils.unit_get(node.get('x')), y_cen=utils.unit_get(node.get('y')), r=utils.unit_get(node.get('radius')), **utils.attr_get(node, [], {'fill':'bool','stroke':'bool'}))
def _place(self, node):
flows = _rml_flowable(self.doc, images=self.images, path=self.path, title=self.title).render(node)
flows = _rml_flowable(self.doc, self.localcontext, images=self.images, path=self.path, title=self.title).render(node)
infos = utils.attr_get(node, ['x','y','width','height'])
infos['y']+=infos['height']
@@ -433,12 +433,12 @@ class _rml_draw(object):
def render(self, canvas, doc):
canvas.saveState()
cnv = _rml_canvas(canvas,self.localcontext, doc, self.styles, images=self.images, path=self.path, title=self.canvas_title)
cnv = _rml_canvas(canvas, self.localcontext, doc, self.styles, images=self.images, path=self.path, title=self.canvas_title)
cnv.render(self.node)
canvas.restoreState()
class _rml_flowable(object):
def __init__(self,doc,localcontext, images={}, path='.', title=None):
def __init__(self, doc, localcontext, images={}, path='.', title=None):
self.localcontext = localcontext
self.doc = doc
self.styles = doc.styles
@@ -454,7 +454,7 @@ class _rml_flowable(object):
if key in ('rml_except', 'rml_loop', 'rml_tag'):
del txt_n.attrib[key]
if True or not self._textual(n).isspace():
txt_n.text = self._textual(n)
txt_n.text = utils.xml2str(self._textual(n))
txt_n.tail = ''
rc1 += etree.tostring(txt_n)
#rc1 += utils._process_text(self, node.tail or '')
+3 -2
View File
@@ -41,6 +41,7 @@ import re
import reportlab
from lxml import etree
import copy
import tools
_regex = re.compile('\[\[(.+?)\]\]')
@@ -111,7 +112,7 @@ def _process_text(self, txt):
pass
if type(txt)==type('') or type(txt)==type(u''):
txt2 = str2xml(txt)
result += txt2
result += tools.ustr(txt2)
elif (txt is not None) and (txt is not False):
result += str(txt)
return result
@@ -119,7 +120,7 @@ def _process_text(self, txt):
def text_get(node):
rc = ''
for node in node.getchildren():
rc = rc + node.text
rc = rc + tools.ustr(node.text)
return rc
units = [
+2 -2
View File
@@ -239,7 +239,7 @@ class rml_parse(object):
self.default_lang[lang] = self.lang_dict.copy()
return True
def formatLang(self, value, digits=2, date=False,date_time=False, grouping=True, monetary=False, currency=None):
def formatLang(self, value, digits=2, date=False,date_time=False, grouping=True, monetary=False):
if isinstance(value, (str, unicode)) and not value:
return ''
if not self.lang_dict_called:
@@ -305,7 +305,7 @@ class rml_parse(object):
head_dom = etree.XML(rml_head)
for tag in head_dom.getchildren():
found = rml_dom.find('.//'+tag.tag)
if found and len(found):
if found is not None and len(found):
if tag.get('position'):
found.append(tag)
else :
+2 -2
View File
@@ -28,9 +28,9 @@ _uid_cache = {}
def login(db, login, password):
cr = pooler.get_db(db).cursor()
if password:
cr.execute('select id from res_users where login=%s and password=%s and active', (login.encode('utf-8'), password.encode('utf-8')))
cr.execute('select id from res_users where login=%s and password=%s and active', (tools.ustr(login), tools.ustr(password)))
else:
cr.execute('select id from res_users where login=%s and password is null and active', (login.encode('utf-8'),))
cr.execute('select id from res_users where login=%s and password is null and active', (tools.ustr(login),))
res = cr.fetchone()
cr.close()
if res:
+34 -25
View File
@@ -29,7 +29,7 @@ import thread
import threading
import time
import sys
import platform
from tools.translate import _
import addons
import ir
@@ -38,7 +38,7 @@ import pooler
import release
import sql_db
import tools
import locale
logging.basicConfig()
class db(netsvc.Service):
@@ -192,7 +192,7 @@ class db(netsvc.Service):
if tools.config['db_host']:
cmd.append('--host=' + tools.config['db_host'])
if tools.config['db_port']:
cmd.append('--port=' + tools.config['db_port'])
cmd.append('--port=' + str(tools.config['db_port']))
cmd.append(db_name)
stdin, stdout = tools.exec_pg_command_pipe(*tuple(cmd))
@@ -236,7 +236,7 @@ class db(netsvc.Service):
if tools.config['db_host']:
cmd.append('--host=' + tools.config['db_host'])
if tools.config['db_port']:
cmd.append('--port=' + tools.config['db_port'])
cmd.append('--port=' + str(tools.config['db_port']))
cmd.append('--dbname=' + db_name)
args2 = tuple(cmd)
@@ -374,6 +374,7 @@ class common(netsvc.Service):
self.exportMethod(self.get_available_updates)
self.exportMethod(self.get_migration_scripts)
self.exportMethod(self.get_server_environment)
self.exportMethod(self.login_message)
def ir_set(self, db, uid, password, keys, args, name, value, replace=True, isobject=False):
security.check(db, uid, password)
@@ -528,30 +529,38 @@ GNU Public Licence.
def get_server_environment(self):
try:
revno = os.popen('bzr revno').read()
rev_log = ''
cnt = 0
for line in os.popen('bzr log -r %s'%(int(revno))).readlines():
if line.find(':')!=-1:
if not cnt == 4:
rev_log += '\t' + line
cnt += 1
else:
break
rev_id = os.popen('bzr revision-info').read()
except Exception,e:
rev_log = 'Exception: %s\n' % (str(e))
rev_id = 'Exception: %s\n' % (tools.ustr(e))
os_lang = os.environ.get('LANG', '').split('.')[0]
environment = '\nEnvironment_Information : \n' \
'PlatForm : %s\n' \
'Operating System : %s\n' \
'Operating System Version : %s\n' \
'Operating System Locale : %s\n'\
'Python Version : %s\n'\
'OpenERP-Server Version : %s\n'\
'Last revision Details: \n%s' \
%(sys.platform,os.name,str(sys.version.split('\n')[1]),os_lang,str(sys.version[0:5]),release.version,rev_log)
os_lang = '.'.join( [x for x in locale.getdefaultlocale() if x] )
if not os_lang:
os_lang = 'NOT SET'
environment = '\nEnvironment Information : \n' \
'System : %s\n' \
'OS Name : %s\n' \
%(platform.platform(), platform.os.name)
if os.name == 'posix':
if platform.system() == 'Linux':
lsbinfo = os.popen('lsb_release -a').read()
environment += '%s'%(lsbinfo)
else:
environment += 'Your System is not lsb compliant\n'
environment += 'Operating System Release : %s\n' \
'Operating System Version : %s\n' \
'Operating System Architecture : %s\n' \
'Operating System Locale : %s\n'\
'Python Version : %s\n'\
'OpenERP-Server Version : %s\n'\
'Last revision No. & ID : %s'\
%(platform.release(), platform.version(), platform.architecture()[0],
os_lang, platform.python_version(),release.version,rev_id)
return environment
def login_message(self):
return tools.config.get('login_message', False)
common()
class objects_proxy(netsvc.Service):
+3 -1
View File
@@ -98,7 +98,9 @@ def amount_to_text(number, currency):
cents_number = int(number * 100) % 100
cents_name = (cents_number > 1) and 'cents' or 'cent'
cents = _100_to_text(cents_number)
cents = cents_number and '%s %s' % (cents, cents_name) or ''
cents = cents_number and '%s %s' % (cents.lower(), cents_name) or ''
if cents:
lacs += ' and %s' % (cents, )
return lacs
+1
View File
@@ -78,6 +78,7 @@ class configmanager(object):
'log_level': logging.INFO,
'assert_exit_level': logging.WARNING, # level above which a failed assert will be raise
'cache_timeout': 100000,
'login_message': False,
}
hasSSL = check_ssl()
+1 -1
View File
@@ -876,7 +876,7 @@ def convert_xml_import(cr, module, xmlfile, idref=None, mode='init', noupdate=Fa
except Exception, e:
logger = netsvc.Logger()
logger.notifyChannel('init', netsvc.LOG_ERROR, 'The XML file does not fit the required schema !')
logger.notifyChannel('init', netsvc.LOG_ERROR, relaxng.error_log.last_error)
logger.notifyChannel('init', netsvc.LOG_ERROR, misc.ustr(relaxng.error_log.last_error))
raise
if idref is None:
+3 -3
View File
@@ -659,9 +659,9 @@ class cache(object):
if time.time()-self.timeout > self.lasttime:
self.lasttime = time.time()
t = time.time()-self.timeout
for key in self.cache.keys():
if self.cache[key][1]<t:
del self.cache[key]
old_keys = [key for key in self.cache if self.cache[key][1] < t]
for key in old_keys:
del self.cache[key]
kwargs2 = self._unify_args(*args, **kwargs)
+21 -13
View File
@@ -545,20 +545,28 @@ def trans_generate(lang, modules, dbname=None):
modobj = pool.get('ir.module.module')
installed_modids = modobj.search(cr, uid, [('state', '=', 'installed')])
installed_modules = map(lambda m: m['name'], modobj.read(cr, uid, installed_modids, ['name']))
if tools.config['root_path'] in tools.config['addons_path'] :
path_list = [tools.config['root_path']]
else :
path_list = [tools.config['root_path'],tools.config['addons_path']]
for root, dirs, files in tools.osutil.walksymlinks(tools.config['root_path']):
for fname in fnmatch.filter(files, '*.py'):
fabsolutepath = join(root, fname)
frelativepath = fabsolutepath[len(tools.config['root_path'])+1:]
module = get_module_from_path(frelativepath)
is_mod_installed = module in installed_modules
if (('all' in modules) or (module in modules)) and is_mod_installed:
code_string = tools.file_open(fabsolutepath, subdir='').read()
iter = re.finditer(
'[^a-zA-Z0-9_]_\([\s]*["\'](.+?)["\'][\s]*\)',
code_string, re.M)
for i in iter:
push_translation(module, 'code', frelativepath, 0, encode(i.group(1)))
for path in path_list:
for root, dirs, files in tools.osutil.walksymlinks(path):
for fname in fnmatch.filter(files, '*.py'):
fabsolutepath = join(root, fname)
frelativepath = fabsolutepath[len(path):]
module = get_module_from_path(frelativepath)
is_mod_installed = module in installed_modules
if (('all' in modules) or (module in modules)) and is_mod_installed:
code_string = tools.file_open(fabsolutepath, subdir='').read()
iter = re.finditer('[^a-zA-Z0-9_]_\([\s]*["\'](.+?)["\'][\s]*\)',
code_string, re.S)
if module in installed_modules :
frelativepath =str("addons"+frelativepath)
for i in iter:
push_translation(module, 'code', frelativepath, 0, encode(i.group(1)))
out = [["module","type","name","res_id","src","value"]] # header
+1 -1
View File
@@ -52,7 +52,7 @@ class workflow_service(netsvc.Service):
cr.execute('select instance_id from wkf_triggers where res_id=%s and model=%s', (res_id,res_type))
res = cr.fetchall()
for (instance_id,) in res:
cr.execute('select uid,res_type,res_id from wkf_instance where id=%s', (instance_id,))
cr.execute('select %s,res_type,res_id from wkf_instance where id=%s', (uid, instance_id,))
ident = cr.fetchone()
instance.update(cr, instance_id, ident)