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'
36 'name': fields.char('Name', size=64, required=True, select=1),
37 'write_date': fields.datetime('Date Modified', readonly=True),
38 'write_uid': fields.many2one('res.users', 'Last Modification User', readonly=True),
39 'create_date': fields.datetime('Date Created', readonly=True),
40 'create_uid': fields.many2one('res.users', 'Creator', readonly=True),
41 'file_type': fields.char('Content Type', size=32),
42 'domain': fields.char('Domain', size=128, help="Use a domain if you want to apply an automatic filter on visible resources."),
43 'user_id': fields.many2one('res.users', 'Owner'),
44 'storage_id': fields.many2one('document.storage', 'Storage'),
45 'group_ids': fields.many2many('res.groups', 'document_directory_group_rel', 'item_id', 'group_id', 'Groups'),
46 'parent_id': fields.many2one('document.directory', 'Parent Item'),
47 'child_ids': fields.one2many('document.directory', 'parent_id', 'Children'),
48 'file_ids': fields.one2many('ir.attachment', 'parent_id', 'Files'),
49 'content_ids': fields.one2many('document.directory.content', 'directory_id', 'Virtual Files'),
50 'type': fields.selection([('directory','Static Directory'),('ressource','Other Resources')], 'Type', required=True),
51 'ressource_type_id': fields.many2one('ir.model', 'Directories Mapped to Objects',
52 help="Select an object here and Open ERP will create a mapping for each of these " \
53 "objects, using the given domain, when browsing through FTP."),
54 '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.'),
55 'ressource_parent_type_id': fields.many2one('ir.model', 'Parent Model',
56 help="If you put an object here, this directory template will appear bellow all of these objects. " \
57 "Don't put a parent directory if you select a parent model."),
58 'ressource_id': fields.integer('Resource ID'),
59 'ressource_tree': fields.boolean('Tree Structure',
60 help="Check this if you want to use the same tree structure as the object selected in the system."),
61 'dctx_ids': fields.one2many('document.directory.dctx', 'dir_id', 'Context fields'),
63 def _get_root_directory(self, cr,uid, context=None):
64 objid=self.pool.get('ir.model.data')
66 mid = objid._get_id(cr, uid, 'document', 'dir_root')
71 logger = netsvc.Logger()
72 logger.notifyChannel("document", netsvc.LOG_WARNING, 'Cannot set directory root:'+ str(e))
74 return objid.browse(cr, uid, mid, context=context).res_id
76 def _get_def_storage(self,cr,uid,context=None):
77 if context and context.has_key('default_parent_id'):
78 # Use the same storage as the parent..
79 diro = self.browse(cr,uid,context['default_parent_id'])
81 return diro.storage_id.id
82 objid=self.pool.get('ir.model.data')
84 mid = objid._get_id(cr, uid, 'document', 'storage_default')
85 return objid.browse(cr, uid, mid, context=context).res_id
90 'user_id': lambda self,cr,uid,ctx: uid,
91 'domain': lambda self,cr,uid,ctx: '[]',
92 'type': lambda *args: 'directory',
93 'ressource_id': lambda *a: 0,
94 'parent_id': _get_root_directory,
95 'storage_id': _get_def_storage,
98 ('dirname_uniq', 'unique (name,parent_id,ressource_id,ressource_parent_type_id)', 'The directory name must be unique !'),
99 ('no_selfparent', 'check(parent_id <> id)', 'Directory cannot be parent of itself!')
102 def ol_get_resource_path(self,cr,uid,dir_id,res_model,res_id):
103 # this method will be used in process module
104 # to be need test and Improvement if resource dir has parent resource (link resource)
106 def _parent(dir_id,path):
107 parent=self.browse(cr,uid,dir_id)
108 if parent.parent_id and not parent.ressource_parent_type_id:
109 _parent(parent.parent_id.id,path)
110 path.append(parent.name)
112 path.append(parent.name)
115 directory=self.browse(cr,uid,dir_id)
116 model_ids=self.pool.get('ir.model').search(cr,uid,[('model','=',res_model)])
119 path.append(self.pool.get(directory.ressource_type_id.model).browse(cr,uid,res_id).name)
120 #user=self.pool.get('res.users').browse(cr,uid,uid)
121 #return "ftp://%s:%s@localhost:%s/%s/%s"%(user.login,user.password,config.get('ftp_server_port',8021),cr.dbname,'/'.join(path))
122 # No way we will return the password!
123 return "ftp://user:pass@host:port/test/this"
126 def _check_recursion(self, cr, uid, ids):
129 cr.execute('select distinct parent_id from document_directory where id in ('+','.join(map(str,ids))+')')
130 ids = filter(None, map(lambda x:x[0], cr.fetchall()))
137 (_check_recursion, 'Error! You can not create recursive Directories.', ['parent_id'])
139 def __init__(self, *args, **kwargs):
140 res = super(document_directory, self).__init__(*args, **kwargs)
143 def onchange_content_id(self, cr, uid, ids, ressource_type_id):
148 uri: of the form "Sales Order/SO001"
151 object: the object.directory or object.directory.content
152 object2: the other object linked (if object.directory.content)
154 def get_object(self, cr, uid, uri, context=None):
155 """ Return a node object for the given uri.
156 This fn merely passes the call to node_context
160 lang = context.get('lang',False)
162 user = self.pool.get('res.users').browse(cr, uid, uid)
163 lang = user.context_lang
164 context['lang'] = lang
166 try: #just instrumentation
167 return nodes.get_node_context(cr, uid, context).get_uri(cr,uri)
169 print "exception: ",e
173 def _locate_child(self, cr,uid, root_id, uri,nparent, ncontext):
174 """ try to locate the node in uri,
175 Return a tuple (node_dir, remaining_path)
180 context = ncontext.context
182 nid = self.search(cr,uid,[('parent_id','=',did),('name','=',duri[0]),('type','=','directory')], context=context)
186 print "Duplicate dir? p= %d, n=\"%s\"" %(did,duri[0])
191 return (nodes.node_dir(path, nparent,ncontext,self.browse(cr,uid,did, context)), duri)
194 nid = self.search(cr,uid,[('parent_id','=',did),('name','=',duri[0]),('type','=','ressource')], context=context)
197 print "Duplicate dir? p= %d, n=\"%s\"" %(did,duri[0])
201 return nodes.node_res_dir(path, nparent,ncontext,self.browse(cr,uid,did, context))
203 # Here, we must find the appropriate non-dir child..
205 fil_obj = self.pool.get('ir.attachment')
206 nid = fil_obj.search(cr,uid,[('parent_id','=',did),('name','=',duri[0])],context=context)
209 # cannot treat child as a dir
212 print "Duplicate file?",did,duri[0]
214 return nodes.node_file(path,nparent,ncontext,fil_obj.browse(cr,uid,nid[0],context))
216 print "nothing found:",did, duri
217 #still, nothing found
222 return node_database(cr, uid, context=context)
224 node = node_class(cr, uid, '/', False, context=context, type='database')
227 node = node.child(path)
230 oo = node.object and (node.object._name, node.object.id) or False
231 oo2 = node.object2 and (node.object2._name, node.object2.id) or False
234 def ol_get_childs(self, cr, uid, uri, context={}):
235 node = self.get_object(cr, uid, uri, context)
237 children = node.children()
240 result = map(lambda node: node.path_get(), children)
243 def copy(self, cr, uid, id, default=None, context=None):
246 name = self.read(cr, uid, [id])[0]['name']
247 default.update({'name': name+ " (copy)"})
248 return super(document_directory,self).copy(cr,uid,id,default,context)
250 def _check_duplication(self, cr, uid,vals,ids=[],op='create'):
251 name=vals.get('name',False)
252 parent_id=vals.get('parent_id',False)
253 ressource_parent_type_id=vals.get('ressource_parent_type_id',False)
254 ressource_id=vals.get('ressource_id',0)
256 for directory in self.browse(cr,uid,ids):
260 parent_id=directory.parent_id and directory.parent_id.id or False
261 if not ressource_parent_type_id:
262 ressource_parent_type_id=directory.ressource_parent_type_id and directory.ressource_parent_type_id.id or False
264 ressource_id=directory.ressource_id and directory.ressource_id or 0
265 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)])
269 res=self.search(cr,uid,[('name','=',name),('parent_id','=',parent_id),('ressource_parent_type_id','=',ressource_parent_type_id),('ressource_id','=',ressource_id)])
273 def write(self, cr, uid, ids, vals, context=None):
274 if not self._check_duplication(cr,uid,vals,ids,op='write'):
275 raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
276 return super(document_directory,self).write(cr,uid,ids,vals,context=context)
278 def create(self, cr, uid, vals, context=None):
279 if not self._check_duplication(cr,uid,vals):
280 raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
281 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) :
282 raise osv.except_osv(_('ValidateError'), _('Directory name contains special characters!'))
283 return super(document_directory,self).create(cr, uid, vals, context)
287 class document_directory_dctx(osv.osv):
288 """ In order to evaluate dynamic folders, child items could have a limiting
289 domain expression. For that, their parents will export a context where useful
290 information will be passed on.
291 If you define sth like "s_id" = "this.id" at a folder iterating over sales, its
292 children could have a domain like [('sale_id', = ,dctx_s_id )]
293 This system should be used recursively, that is, parent dynamic context will be
294 appended to all children down the tree.
296 _name = 'document.directory.dctx'
297 _description = 'Directory dynamic context'
299 'dir_id': fields.many2one('document.directory', 'Directory', required=True),
300 '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."),
301 'expr': fields.char('Expression', size=64, required=True, help="A python expression used to evaluate the field.\n" + \
302 "You can use 'dir_id' for current dir, 'res_id', 'res_model' as a reference to the current record, in dynamic folders"),
305 document_directory_dctx()
308 class document_directory_node(osv.osv):
309 _inherit = 'process.node'
311 'directory_id': fields.many2one('document.directory', 'Document directory', ondelete="set null"),
313 document_directory_node()