[FIX] document :- all record delete in document.directory and create new directory...
[odoo/odoo.git] / addons / document / document_directory.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #    
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.     
19 #
20 ##############################################################################
21
22 import base64
23
24 from osv import osv, fields
25 from osv.orm import except_orm
26 import urlparse
27
28 import os
29 import nodes
30 from tools.translate import _
31
32 class document_directory(osv.osv):
33     _name = 'document.directory'
34     _description = 'Document directory'
35     _order = 'name desc'
36     _columns = {
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.many2one('ir.model.fields', 'Name field', 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'),
63     }
64
65
66     def _get_root_directory(self, cr,uid, context=None):
67         objid=self.pool.get('ir.model.data')
68         try:
69             mid = objid._get_id(cr, uid, 'document', 'dir_root')
70             if not mid:
71                 return False
72             root_id = objid.read(cr, uid, mid, ['res_id'])['res_id']
73             return root_id
74         except Exception, e:
75             import netsvc
76             logger = netsvc.Logger()
77             logger.notifyChannel("document", netsvc.LOG_WARNING, 'Cannot set directory root:'+ str(e))
78             return False
79         return objid.browse(cr, uid, mid, context=context).res_id
80
81     def _get_def_storage(self,cr,uid,context=None):
82         if context and context.has_key('default_parent_id'):
83                 # Use the same storage as the parent..
84                 diro = self.browse(cr,uid,context['default_parent_id'])
85                 if diro.storage_id:
86                         return diro.storage_id.id
87         objid=self.pool.get('ir.model.data')
88         try:
89                 mid =  objid._get_id(cr, uid, 'document', 'storage_default')
90                 return objid.browse(cr, uid, mid, context=context).res_id
91         except Exception:
92                 return None
93         
94     _defaults = {
95         'user_id': lambda self,cr,uid,ctx: uid,
96         'domain': lambda self,cr,uid,ctx: '[]',
97         'type': lambda *args: 'directory',
98         'ressource_id': lambda *a: 0,
99         'parent_id': _get_root_directory,
100         'storage_id': _get_def_storage,
101     }
102     _sql_constraints = [
103         ('dirname_uniq', 'unique (name,parent_id,ressource_id,ressource_parent_type_id)', 'The directory name must be unique !'),
104         ('no_selfparent', 'check(parent_id <> id)', 'Directory cannot be parent of itself!')
105     ]
106     def name_get(self, cr, uid, ids, context={}):
107         res = []
108         all_ids = self.search(cr,uid,[])
109         for d in self.browse(cr, uid, ids, context=context):
110             if d.id not in all_ids:
111                 continue
112
113             s = ''
114             d2 = d
115             while d2 and d2.parent_id:
116                 s = d2.name + (s and ('/' + s) or '')
117                 d2 = d2.parent_id
118             res.append((d.id, s))
119         return res
120
121     def get_full_path(self, cr, uid, dir_id, context=None):
122         """ Return the full path to this directory, in a list, root first
123         """
124         def _parent(dir_id, path):
125             parent=self.browse(cr,uid,dir_id)
126             if parent.parent_id and not parent.ressource_parent_type_id:
127                 _parent(parent.parent_id.id,path)
128                 path.append(parent.name)
129             else:
130                 path.append(parent.name)
131                 return path
132         path = []
133         _parent(dir_id, path)
134         return path
135
136     def ol_get_resource_path(self,cr,uid,dir_id,res_model,res_id):
137         # this method will be used in process module
138         # to be need test and Improvement if resource dir has parent resource (link resource)
139         path=[]
140         def _parent(dir_id,path):
141             parent=self.browse(cr,uid,dir_id)
142             if parent.parent_id and not parent.ressource_parent_type_id:
143                 _parent(parent.parent_id.id,path)
144                 path.append(parent.name)
145             else:
146                 path.append(parent.name)
147                 return path
148
149         directory=self.browse(cr,uid,dir_id)
150         model_ids=self.pool.get('ir.model').search(cr,uid,[('model','=',res_model)])
151         if directory:
152             _parent(dir_id,path)
153             path.append(self.pool.get(directory.ressource_type_id.model).browse(cr,uid,res_id).name)
154             #user=self.pool.get('res.users').browse(cr,uid,uid)
155             #return "ftp://%s:%s@localhost:%s/%s/%s"%(user.login,user.password,config.get('ftp_server_port',8021),cr.dbname,'/'.join(path))
156             # No way we will return the password!
157             return "ftp://user:pass@host:port/test/this"
158         return False
159
160     def _check_recursion(self, cr, uid, ids):
161         level = 100
162         while len(ids):
163             cr.execute('select distinct parent_id from document_directory where id in ('+','.join(map(str,ids))+')')
164             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
165             if not level:
166                 return False
167             level -= 1
168         return True
169
170     _constraints = [
171         (_check_recursion, 'Error! You can not create recursive Directories.', ['parent_id'])
172     ]
173     def __init__(self, *args, **kwargs):
174         res = super(document_directory, self).__init__(*args, **kwargs)
175         #self._cache = {}
176
177     def onchange_content_id(self, cr, uid, ids, ressource_type_id):
178         return {}
179
180     """
181         PRE:
182             uri: of the form "Sales Order/SO001"
183         PORT:
184             uri
185             object: the object.directory or object.directory.content
186             object2: the other object linked (if object.directory.content)
187     """
188     def get_object(self, cr, uid, uri, context=None):
189         """ Return a node object for the given uri.
190            This fn merely passes the call to node_context
191         """
192         if not context:
193                 context = {}
194         lang = context.get('lang',False)
195         if not lang:
196             user = self.pool.get('res.users').browse(cr, uid, uid)
197             lang = user.context_lang 
198             context['lang'] = lang
199             
200         try: #just instrumentation
201                 return nodes.get_node_context(cr, uid, context).get_uri(cr,uri)
202         except Exception,e:
203                 print "exception: ",e
204                 raise
205
206
207     def _locate_child(self, cr,uid, root_id, uri,nparent, ncontext):
208         """ try to locate the node in uri,
209             Return a tuple (node_dir, remaining_path)
210         """
211         did = root_id
212         duri = uri
213         path = []
214         context = ncontext.context        
215         while len(duri):            
216             nid = self.search(cr,uid,[('parent_id','=',did),('name','=',duri[0]),('type','=','directory')], context=context)            
217             if not nid:
218                 break
219             if len(nid)>1:
220                 print "Duplicate dir? p= %d, n=\"%s\"" %(did,duri[0])
221             path.append(duri[0])
222             duri = duri[1:]
223             did = nid[0]
224         root_node = did and self.browse(cr,uid,did, context) or False
225         return (nodes.node_dir(path, nparent,ncontext, root_node), duri)
226
227         
228         nid = self.search(cr,uid,[('parent_id','=',did),('name','=',duri[0]),('type','=','ressource')], context=context)
229         if nid:
230             if len(nid)>1:
231                 print "Duplicate dir? p= %d, n=\"%s\"" %(did,duri[0])
232             path.append(duri[0])
233             duri = duri[1:]
234             did = nid[0]
235             return nodes.node_res_dir(path, nparent,ncontext,self.browse(cr,uid,did, context))
236
237         # Here, we must find the appropriate non-dir child..
238         # Chech for files:
239         fil_obj = self.pool.get('ir.attachment')
240         nid = fil_obj.search(cr,uid,[('parent_id','=',did),('name','=',duri[0])],context=context)
241         if nid:
242                 if len(duri)>1:
243                         # cannot treat child as a dir
244                         return None
245                 if len(nid)>1:
246                         print "Duplicate file?",did,duri[0]
247                 path.append(duri[0])
248                 return nodes.node_file(path,nparent,ncontext,fil_obj.browse(cr,uid,nid[0],context))
249         
250         print "nothing found:",did, duri
251         #still, nothing found
252         return None
253         
254     def old_code():
255         if not uri:
256             return node_database(cr, uid, context=context)
257         turi = tuple(uri)
258         node = node_class(cr, uid, '/', False, context=context, type='database')
259         for path in uri[:]:
260             if path:
261                 node = node.child(path)
262                 if not node:
263                     return False
264         oo = node.object and (node.object._name, node.object.id) or False
265         oo2 = node.object2 and (node.object2._name, node.object2.id) or False
266         return node
267
268     def ol_get_childs(self, cr, uid, uri, context={}):
269         node = self.get_object(cr, uid, uri, context)
270         if uri:
271             children = node.children()
272         else:
273             children= [node]
274         result = map(lambda node: node.path_get(), children)
275         return result
276
277     def copy(self, cr, uid, id, default=None, context=None):
278         if not default:
279             default ={}
280         name = self.read(cr, uid, [id])[0]['name']
281         default.update({'name': name+ " (copy)"})
282         return super(document_directory,self).copy(cr,uid,id,default,context)
283
284     def _check_duplication(self, cr, uid,vals,ids=[],op='create'):
285         name=vals.get('name',False)
286         parent_id=vals.get('parent_id',False)
287         ressource_parent_type_id=vals.get('ressource_parent_type_id',False)
288         ressource_id=vals.get('ressource_id',0)
289         if op=='write':
290             for directory in self.browse(cr,uid,ids):
291                 if not name:
292                     name=directory.name
293                 if not parent_id:
294                     parent_id=directory.parent_id and directory.parent_id.id or False
295                 if not ressource_parent_type_id:
296                     ressource_parent_type_id=directory.ressource_parent_type_id and directory.ressource_parent_type_id.id or False
297                 if not ressource_id:
298                     ressource_id=directory.ressource_id and directory.ressource_id or 0
299                 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)])
300                 if len(res):
301                     return False
302         if op=='create':
303             res=self.search(cr,uid,[('name','=',name),('parent_id','=',parent_id),('ressource_parent_type_id','=',ressource_parent_type_id),('ressource_id','=',ressource_id)])
304             if len(res):
305                 return False
306         return True
307     def write(self, cr, uid, ids, vals, context=None):
308         if not self._check_duplication(cr,uid,vals,ids,op='write'):
309             raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
310         return super(document_directory,self).write(cr,uid,ids,vals,context=context)
311
312     def create(self, cr, uid, vals, context=None):
313         if not self._check_duplication(cr,uid,vals):
314             raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
315         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) :
316             raise osv.except_osv(_('ValidateError'), _('Directory name contains special characters!'))
317         return super(document_directory,self).create(cr, uid, vals, context)
318
319 document_directory()
320
321 class document_directory_dctx(osv.osv):
322     """ In order to evaluate dynamic folders, child items could have a limiting
323         domain expression. For that, their parents will export a context where useful
324         information will be passed on.
325         If you define sth like "s_id" = "this.id" at a folder iterating over sales, its
326         children could have a domain like [('sale_id', = ,dctx_s_id )]
327         This system should be used recursively, that is, parent dynamic context will be
328         appended to all children down the tree.
329     """
330     _name = 'document.directory.dctx'
331     _description = 'Directory dynamic context'
332     _columns = {
333         'dir_id': fields.many2one('document.directory', 'Directory', required=True),
334         '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."),
335         'expr': fields.char('Expression', size=64, required=True, help="A python expression used to evaluate the field.\n" + \
336                 "You can use 'dir_id' for current dir, 'res_id', 'res_model' as a reference to the current record, in dynamic folders"),
337         }
338
339 document_directory_dctx()
340
341
342 class document_directory_node(osv.osv):
343     _inherit = 'process.node'
344     _columns = {
345         'directory_id':  fields.many2one('document.directory', 'Document directory', ondelete="set null"),
346     }
347 document_directory_node()