Document directory: cleanup fields, type, constraints.
[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 = '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         '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', select=1),
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([ 
51             ('directory','Static Directory'),
52             ('ressource','Folders per resource'),
53             ('at_record','Single folder under resource')],
54             'Type', required=True, select=1,
55             help="Defines directory's behaviour."),
56         
57         'ressource_type_id': fields.many2one('ir.model', 'Directories Mapped to Objects',
58             help="Select an object here and Open ERP will create a mapping for each of these " \
59                  "objects, using the given domain, when browsing through FTP."),
60         '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.'),
61         'ressource_parent_type_id': fields.many2one('ir.model', 'Parent Model',
62             help="If you put an object here, this directory template will appear bellow all of these objects. " \
63                  "Don't put a parent directory if you select a parent model."),
64         'ressource_id': fields.integer('Resource ID'),
65         'ressource_tree': fields.boolean('Tree Structure',
66             help="Check this if you want to use the same tree structure as the object selected in the system."),
67         'dctx_ids': fields.one2many('document.directory.dctx', 'dir_id', 'Context fields'),
68         'company_id': fields.many2one('res.company', 'Company'),
69     }
70
71
72     def _get_root_directory(self, cr,uid, context=None):
73         objid=self.pool.get('ir.model.data')
74         try:
75             mid = objid._get_id(cr, uid, 'document', 'dir_root')
76             if not mid:
77                 return False
78             root_id = objid.read(cr, uid, mid, ['res_id'])['res_id']
79             return root_id
80         except Exception, e:
81             import netsvc
82             logger = netsvc.Logger()
83             logger.notifyChannel("document", netsvc.LOG_WARNING, 'Cannot set directory root:'+ str(e))
84             return False
85         return objid.browse(cr, uid, mid, context=context).res_id
86
87     def _get_def_storage(self, cr, uid, context=None):
88         if context and context.has_key('default_parent_id'):
89                 # Use the same storage as the parent..
90                 diro = self.browse(cr, uid, context['default_parent_id'])
91                 if diro.storage_id:
92                         return diro.storage_id.id
93         objid=self.pool.get('ir.model.data')
94         try:
95                 mid =  objid._get_id(cr, uid, 'document', 'storage_default')
96                 return objid.browse(cr, uid, mid, context=context).res_id
97         except Exception:
98                 return None
99         
100     _defaults = {
101         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'document.directory', context=c),
102         'user_id': lambda self,cr,uid,ctx: uid,
103         'domain': lambda self,cr,uid,ctx: '[]',
104         'type': lambda *args: 'directory',
105         'ressource_id': lambda *a: 0,        
106         'storage_id': _get_def_storage,
107     }
108     _sql_constraints = [
109         ('dirname_uniq', 'unique (name,parent_id,ressource_id,ressource_parent_type_id)', 'The directory name must be unique !'),
110         ('no_selfparent', 'check(parent_id <> id)', 'Directory cannot be parent of itself!'),
111         ('dir_parented', 'check(parent_id IS NOT NULL OR storage_id IS NOT NULL)', 'Directory must have a parent or a storage')
112     ]
113     def name_get(self, cr, uid, ids, context={}):
114         res = []
115         if not self.search(cr,uid,[('id','in',ids)]):
116             ids = []
117         for d in self.browse(cr, uid, ids, context=context):
118             s = ''
119             d2 = d
120             while d2 and d2.parent_id:
121                 s = d2.name + (s and ('/' + s) or '')
122                 d2 = d2.parent_id
123             res.append((d.id, s or d.name))
124         return res
125
126     def get_full_path(self, cr, uid, dir_id, context=None):
127         """ Return the full path to this directory, in a list, root first
128         """
129         def _parent(dir_id, path):
130             parent=self.browse(cr, uid, dir_id)
131             if parent.parent_id and not parent.ressource_parent_type_id:
132                 _parent(parent.parent_id.id,path)
133                 path.append(parent.name)
134             else:
135                 path.append(parent.name)
136                 return path
137         path = []
138         _parent(dir_id, path)
139         return path
140
141     def ol_get_resource_path(self, cr, uid, dir_id, res_model, res_id):
142         # this method will be used in process module
143         # to be need test and Improvement if resource dir has parent resource (link resource)
144         path=[]
145         def _parent(dir_id,path):
146             parent=self.browse(cr, uid, dir_id)
147             if parent.parent_id and not parent.ressource_parent_type_id:
148                 _parent(parent.parent_id.id,path)
149                 path.append(parent.name)
150             else:
151                 path.append(parent.name)
152                 return path
153
154         directory=self.browse(cr,uid,dir_id)
155         model_ids=self.pool.get('ir.model').search(cr, uid, [('model','=',res_model)])
156         if directory:
157             _parent(dir_id,path)
158             path.append(self.pool.get(directory.ressource_type_id.model).browse(cr, uid, res_id).name)
159             #user=self.pool.get('res.users').browse(cr,uid,uid)
160             #return "ftp://%s:%s@localhost:%s/%s/%s"%(user.login,user.password,config.get('ftp_server_port',8021),cr.dbname,'/'.join(path))
161             # No way we will return the password!
162             return "ftp://user:pass@host:port/test/this"
163         return False
164
165     def _check_recursion(self, cr, uid, ids):
166         level = 100
167         while len(ids):
168             cr.execute('select distinct parent_id from document_directory where id in ('+','.join(map(str,ids))+')')
169             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
170             if not level:
171                 return False
172             level -= 1
173         return True
174
175     _constraints = [
176         (_check_recursion, 'Error! You can not create recursive Directories.', ['parent_id'])
177     ]
178     def __init__(self, *args, **kwargs):
179         res = super(document_directory, self).__init__(*args, **kwargs)
180         #self._cache = {}
181
182     def onchange_content_id(self, cr, uid, ids, ressource_type_id):
183         return {}
184
185     """
186         PRE:
187             uri: of the form "Sales Order/SO001"
188         PORT:
189             uri
190             object: the object.directory or object.directory.content
191             object2: the other object linked (if object.directory.content)
192     """
193     def get_object(self, cr, uid, uri, context=None):
194         """ Return a node object for the given uri.
195            This fn merely passes the call to node_context
196         """
197         if not context:
198                 context = {}
199         lang = context.get('lang',False)
200         if not lang:
201             user = self.pool.get('res.users').browse(cr, uid, uid)
202             lang = user.context_lang 
203             context['lang'] = lang
204             
205         try: #just instrumentation
206                 return nodes.get_node_context(cr, uid, context).get_uri(cr, uri)
207         except Exception,e:
208                 print "exception: ",e
209                 raise
210
211
212     def _locate_child(self, cr, uid, root_id, uri,nparent, ncontext):
213         """ try to locate the node in uri,
214             Return a tuple (node_dir, remaining_path)
215         """
216         return (nodes.node_database(context=ncontext), uri)         
217         
218     def old_code():
219         if not uri:
220             return node_database(cr, uid, context=context)
221         turi = tuple(uri)
222         node = node_class(cr, uid, '/', False, context=context, type='database')
223         for path in uri[:]:
224             if path:
225                 node = node.child(path)
226                 if not node:
227                     return False
228         oo = node.object and (node.object._name, node.object.id) or False
229         oo2 = node.object2 and (node.object2._name, node.object2.id) or False
230         return node
231
232     def ol_get_childs(self, cr, uid, uri, context={}):
233         node = self.get_object(cr, uid, uri, context)
234         if uri:
235             children = node.children()
236         else:
237             children= [node]
238         result = map(lambda node: node.path_get(), children)
239         return result
240
241     def copy(self, cr, uid, id, default=None, context=None):
242         if not default:
243             default ={}
244         name = self.read(cr, uid, [id])[0]['name']
245         default.update({'name': name+ " (copy)"})
246         return super(document_directory,self).copy(cr, uid, id, default, context)
247
248     def _check_duplication(self, cr, uid, vals, ids=[], op='create'):
249         name=vals.get('name',False)
250         parent_id=vals.get('parent_id',False)
251         ressource_parent_type_id=vals.get('ressource_parent_type_id',False)
252         ressource_id=vals.get('ressource_id',0)
253         if op=='write':
254             for directory in self.browse(cr, uid, ids):
255                 if not name:
256                     name=directory.name
257                 if not parent_id:
258                     parent_id=directory.parent_id and directory.parent_id.id or False
259                 if not ressource_parent_type_id:
260                     ressource_parent_type_id=directory.ressource_parent_type_id and directory.ressource_parent_type_id.id or False
261                 if not ressource_id:
262                     ressource_id=directory.ressource_id and directory.ressource_id or 0
263                 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)])
264                 if len(res):
265                     return False
266         if op=='create':
267             res=self.search(cr,uid,[('name','=',name),('parent_id','=',parent_id),('ressource_parent_type_id','=',ressource_parent_type_id),('ressource_id','=',ressource_id)])
268             if len(res):
269                 return False
270         return True
271     def write(self, cr, uid, ids, vals, context=None):
272         if not self._check_duplication(cr, uid, vals, ids, op='write'):
273             raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
274         return super(document_directory,self).write(cr, uid, ids, vals, context=context)
275
276     def create(self, cr, uid, vals, context=None):
277         if not self._check_duplication(cr, uid, vals):
278             raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
279         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) :
280             raise osv.except_osv(_('ValidateError'), _('Directory name contains special characters!'))
281         return super(document_directory,self).create(cr, uid, vals, context)
282
283 document_directory()
284
285 class document_directory_dctx(osv.osv):
286     """ In order to evaluate dynamic folders, child items could have a limiting
287         domain expression. For that, their parents will export a context where useful
288         information will be passed on.
289         If you define sth like "s_id" = "this.id" at a folder iterating over sales, its
290         children could have a domain like [('sale_id', = ,dctx_s_id )]
291         This system should be used recursively, that is, parent dynamic context will be
292         appended to all children down the tree.
293     """
294     _name = 'document.directory.dctx'
295     _description = 'Directory Dynamic Context'
296     _columns = {
297         'dir_id': fields.many2one('document.directory', 'Directory', required=True),
298         '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."),
299         'expr': fields.char('Expression', size=64, required=True, help="A python expression used to evaluate the field.\n" + \
300                 "You can use 'dir_id' for current dir, 'res_id', 'res_model' as a reference to the current record, in dynamic folders"),
301         }
302
303 document_directory_dctx()
304
305
306 class document_directory_node(osv.osv):
307     _inherit = 'process.node'
308     _columns = {
309         'directory_id':  fields.many2one('document.directory', 'Document directory', ondelete="set null"),
310     }
311 document_directory_node()