1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
24 from osv import osv, fields
25 from osv.orm import except_orm
30 from tools.translate import _
32 class document_directory(osv.osv):
33 _name = 'document.directory'
34 _description = 'Document directory'
37 'name': fields.char('Name', size=64, required=True, select=1),
38 'write_date': fields.datetime('Date Modified', readonly=True),
39 'write_uid': fields.many2one('res.users', 'Last Modification User', readonly=True),
40 'create_date': fields.datetime('Date Created', readonly=True),
41 'create_uid': fields.many2one('res.users', 'Creator', readonly=True),
42 'file_type': fields.char('Content Type', size=32),
43 'domain': fields.char('Domain', size=128, help="Use a domain if you want to apply an automatic filter on visible resources."),
44 'user_id': fields.many2one('res.users', 'Owner'),
45 'storage_id': fields.many2one('document.storage', 'Storage'),
46 'group_ids': fields.many2many('res.groups', 'document_directory_group_rel', 'item_id', 'group_id', 'Groups'),
47 'parent_id': fields.many2one('document.directory', 'Parent Item'),
48 'child_ids': fields.one2many('document.directory', 'parent_id', 'Children'),
49 'file_ids': fields.one2many('ir.attachment', 'parent_id', 'Files'),
50 'content_ids': fields.one2many('document.directory.content', 'directory_id', 'Virtual Files'),
51 'type': fields.selection([('directory','Static Directory'),('ressource','Other Resources')], 'Type', required=True),
52 'ressource_type_id': fields.many2one('ir.model', 'Directories Mapped to Objects',
53 help="Select an object here and Open ERP will create a mapping for each of these " \
54 "objects, using the given domain, when browsing through FTP."),
55 'resource_field': fields.char('Name field',size=32,help='Field to be used as name on resource directories. If empty, the "name" will be used.'),
56 'ressource_parent_type_id': fields.many2one('ir.model', 'Parent Model',
57 help="If you put an object here, this directory template will appear bellow all of these objects. " \
58 "Don't put a parent directory if you select a parent model."),
59 'ressource_id': fields.integer('Resource ID'),
60 'ressource_tree': fields.boolean('Tree Structure',
61 help="Check this if you want to use the same tree structure as the object selected in the system."),
62 'dctx_ids': fields.one2many('document.directory.dctx', 'dir_id', 'Context fields'),
64 def _get_root_directory(self, cr,uid, context=None):
65 objid=self.pool.get('ir.model.data')
67 mid = objid._get_id(cr, uid, 'document', 'dir_root')
72 logger = netsvc.Logger()
73 logger.notifyChannel("document", netsvc.LOG_WARNING, 'Cannot set directory root:'+ str(e))
75 return objid.browse(cr, uid, mid, context=context).res_id
77 def _get_def_storage(self,cr,uid,context=None):
78 if context and context.has_key('default_parent_id'):
79 # Use the same storage as the parent..
80 diro = self.browse(cr,uid,context['default_parent_id'])
82 return diro.storage_id.id
83 objid=self.pool.get('ir.model.data')
85 mid = objid._get_id(cr, uid, 'document', 'storage_default')
86 return objid.browse(cr, uid, mid, context=context).res_id
91 'user_id': lambda self,cr,uid,ctx: uid,
92 'domain': lambda self,cr,uid,ctx: '[]',
93 'type': lambda *args: 'directory',
94 'ressource_id': lambda *a: 0,
95 'parent_id': _get_root_directory,
96 'storage_id': _get_def_storage,
99 ('dirname_uniq', 'unique (name,parent_id,ressource_id,ressource_parent_type_id)', 'The directory name must be unique !'),
100 ('no_selfparent', 'check(parent_id <> id)', 'Directory cannot be parent of itself!')
102 def name_get(self, cr, uid, ids, context={}):
104 for d in self.browse(cr, uid, ids, context=context):
107 while d2 and d2.parent_id:
108 s = d2.name + (s and ('/' + s) or '')
110 res.append((d.id, s))
113 def ol_get_resource_path(self,cr,uid,dir_id,res_model,res_id):
114 # this method will be used in process module
115 # to be need test and Improvement if resource dir has parent resource (link resource)
117 def _parent(dir_id,path):
118 parent=self.browse(cr,uid,dir_id)
119 if parent.parent_id and not parent.ressource_parent_type_id:
120 _parent(parent.parent_id.id,path)
121 path.append(parent.name)
123 path.append(parent.name)
126 directory=self.browse(cr,uid,dir_id)
127 model_ids=self.pool.get('ir.model').search(cr,uid,[('model','=',res_model)])
130 path.append(self.pool.get(directory.ressource_type_id.model).browse(cr,uid,res_id).name)
131 #user=self.pool.get('res.users').browse(cr,uid,uid)
132 #return "ftp://%s:%s@localhost:%s/%s/%s"%(user.login,user.password,config.get('ftp_server_port',8021),cr.dbname,'/'.join(path))
133 # No way we will return the password!
134 return "ftp://user:pass@host:port/test/this"
137 def _check_recursion(self, cr, uid, ids):
140 cr.execute('select distinct parent_id from document_directory where id in ('+','.join(map(str,ids))+')')
141 ids = filter(None, map(lambda x:x[0], cr.fetchall()))
148 (_check_recursion, 'Error! You can not create recursive Directories.', ['parent_id'])
150 def __init__(self, *args, **kwargs):
151 res = super(document_directory, self).__init__(*args, **kwargs)
154 def onchange_content_id(self, cr, uid, ids, ressource_type_id):
159 uri: of the form "Sales Order/SO001"
162 object: the object.directory or object.directory.content
163 object2: the other object linked (if object.directory.content)
165 def get_object(self, cr, uid, uri, context=None):
166 """ Return a node object for the given uri.
167 This fn merely passes the call to node_context
171 lang = context.get('lang',False)
173 user = self.pool.get('res.users').browse(cr, uid, uid)
174 lang = user.context_lang
175 context['lang'] = lang
177 try: #just instrumentation
178 return nodes.get_node_context(cr, uid, context).get_uri(cr,uri)
180 print "exception: ",e
184 def _locate_child(self, cr,uid, root_id, uri,nparent, ncontext):
185 """ try to locate the node in uri,
186 Return a tuple (node_dir, remaining_path)
191 context = ncontext.context
193 nid = self.search(cr,uid,[('parent_id','=',did),('name','=',duri[0]),('type','=','directory')], context=context)
197 print "Duplicate dir? p= %d, n=\"%s\"" %(did,duri[0])
201 root_node = did and self.browse(cr,uid,did, context) or False
202 return (nodes.node_dir(path, nparent,ncontext, root_node), duri)
205 nid = self.search(cr,uid,[('parent_id','=',did),('name','=',duri[0]),('type','=','ressource')], context=context)
208 print "Duplicate dir? p= %d, n=\"%s\"" %(did,duri[0])
212 return nodes.node_res_dir(path, nparent,ncontext,self.browse(cr,uid,did, context))
214 # Here, we must find the appropriate non-dir child..
216 fil_obj = self.pool.get('ir.attachment')
217 nid = fil_obj.search(cr,uid,[('parent_id','=',did),('name','=',duri[0])],context=context)
220 # cannot treat child as a dir
223 print "Duplicate file?",did,duri[0]
225 return nodes.node_file(path,nparent,ncontext,fil_obj.browse(cr,uid,nid[0],context))
227 print "nothing found:",did, duri
228 #still, nothing found
233 return node_database(cr, uid, context=context)
235 node = node_class(cr, uid, '/', False, context=context, type='database')
238 node = node.child(path)
241 oo = node.object and (node.object._name, node.object.id) or False
242 oo2 = node.object2 and (node.object2._name, node.object2.id) or False
245 def ol_get_childs(self, cr, uid, uri, context={}):
246 node = self.get_object(cr, uid, uri, context)
248 children = node.children()
251 result = map(lambda node: node.path_get(), children)
254 def copy(self, cr, uid, id, default=None, context=None):
257 name = self.read(cr, uid, [id])[0]['name']
258 default.update({'name': name+ " (copy)"})
259 return super(document_directory,self).copy(cr,uid,id,default,context)
261 def _check_duplication(self, cr, uid,vals,ids=[],op='create'):
262 name=vals.get('name',False)
263 parent_id=vals.get('parent_id',False)
264 ressource_parent_type_id=vals.get('ressource_parent_type_id',False)
265 ressource_id=vals.get('ressource_id',0)
267 for directory in self.browse(cr,uid,ids):
271 parent_id=directory.parent_id and directory.parent_id.id or False
272 if not ressource_parent_type_id:
273 ressource_parent_type_id=directory.ressource_parent_type_id and directory.ressource_parent_type_id.id or False
275 ressource_id=directory.ressource_id and directory.ressource_id or 0
276 res=self.search(cr,uid,[('id','<>',directory.id),('name','=',name),('parent_id','=',parent_id),('ressource_parent_type_id','=',ressource_parent_type_id),('ressource_id','=',ressource_id)])
280 res=self.search(cr,uid,[('name','=',name),('parent_id','=',parent_id),('ressource_parent_type_id','=',ressource_parent_type_id),('ressource_id','=',ressource_id)])
284 def write(self, cr, uid, ids, vals, context=None):
285 if not self._check_duplication(cr,uid,vals,ids,op='write'):
286 raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
287 return super(document_directory,self).write(cr,uid,ids,vals,context=context)
289 def create(self, cr, uid, vals, context=None):
290 if not self._check_duplication(cr,uid,vals):
291 raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
292 if vals.get('name',False) and (vals.get('name').find('/')+1 or vals.get('name').find('@')+1 or vals.get('name').find('$')+1 or vals.get('name').find('#')+1) :
293 raise osv.except_osv(_('ValidateError'), _('Directory name contains special characters!'))
294 return super(document_directory,self).create(cr, uid, vals, context)
298 class document_directory_dctx(osv.osv):
299 """ In order to evaluate dynamic folders, child items could have a limiting
300 domain expression. For that, their parents will export a context where useful
301 information will be passed on.
302 If you define sth like "s_id" = "this.id" at a folder iterating over sales, its
303 children could have a domain like [('sale_id', = ,dctx_s_id )]
304 This system should be used recursively, that is, parent dynamic context will be
305 appended to all children down the tree.
307 _name = 'document.directory.dctx'
308 _description = 'Directory dynamic context'
310 'dir_id': fields.many2one('document.directory', 'Directory', required=True),
311 'field': fields.char('Field', size=20, required=True, select=1, help="The name of the field. Note that the prefix \"dctx_\" will be prepended to what is typed here."),
312 'expr': fields.char('Expression', size=64, required=True, help="A python expression used to evaluate the field.\n" + \
313 "You can use 'dir_id' for current dir, 'res_id', 'res_model' as a reference to the current record, in dynamic folders"),
316 document_directory_dctx()
319 class document_directory_node(osv.osv):
320 _inherit = 'process.node'
322 'directory_id': fields.many2one('document.directory', 'Document directory', ondelete="set null"),
324 document_directory_node()