[FIX] res_lang : if value of thousands_sep is not present in language,method will...
[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.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'),
63     }
64     def _get_root_directory(self, cr,uid, context=None):
65         objid=self.pool.get('ir.model.data')
66         try:
67             mid = objid._get_id(cr, uid, 'document', 'dir_root')            
68             if not mid:
69                 return False
70         except Exception, e:
71             import netsvc
72             logger = netsvc.Logger()
73             logger.notifyChannel("document", netsvc.LOG_WARNING, 'Cannot set directory root:'+ str(e))
74             return False
75         return objid.browse(cr, uid, mid, context=context).res_id
76
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'])
81                 if diro.storage_id:
82                         return diro.storage_id.id
83         objid=self.pool.get('ir.model.data')
84         try:
85                 mid =  objid._get_id(cr, uid, 'document', 'storage_default')
86                 return objid.browse(cr, uid, mid, context=context).res_id
87         except Exception:
88                 return None
89         
90     _defaults = {
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,
97     }
98     _sql_constraints = [
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!')
101     ]
102     def name_get(self, cr, uid, ids, context={}):
103         res = []
104         for d in self.browse(cr, uid, ids, context=context):
105             s = ''
106             d2 = d
107             while d2 and d2.parent_id:
108                 s = d2.name + (s and ('/' + s) or '')
109                 d2 = d2.parent_id
110             res.append((d.id, s))
111         return res
112
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)
116         path=[]
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)
122             else:
123                 path.append(parent.name)
124                 return path
125
126         directory=self.browse(cr,uid,dir_id)
127         model_ids=self.pool.get('ir.model').search(cr,uid,[('model','=',res_model)])
128         if directory:
129             _parent(dir_id,path)
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"
135         return False
136
137     def _check_recursion(self, cr, uid, ids):
138         level = 100
139         while len(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()))
142             if not level:
143                 return False
144             level -= 1
145         return True
146
147     _constraints = [
148         (_check_recursion, 'Error! You can not create recursive Directories.', ['parent_id'])
149     ]
150     def __init__(self, *args, **kwargs):
151         res = super(document_directory, self).__init__(*args, **kwargs)
152         #self._cache = {}
153
154     def onchange_content_id(self, cr, uid, ids, ressource_type_id):
155         return {}
156
157     """
158         PRE:
159             uri: of the form "Sales Order/SO001"
160         PORT:
161             uri
162             object: the object.directory or object.directory.content
163             object2: the other object linked (if object.directory.content)
164     """
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
168         """
169         if not context:
170                 context = {}
171         lang = context.get('lang',False)
172         if not lang:
173             user = self.pool.get('res.users').browse(cr, uid, uid)
174             lang = user.context_lang 
175             context['lang'] = lang
176             
177         try: #just instrumentation
178                 return nodes.get_node_context(cr, uid, context).get_uri(cr,uri)
179         except Exception,e:
180                 print "exception: ",e
181                 raise
182
183
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)
187         """
188         did = root_id
189         duri = uri
190         path = []
191         context = ncontext.context        
192         while len(duri):            
193             nid = self.search(cr,uid,[('parent_id','=',did),('name','=',duri[0]),('type','=','directory')], context=context)            
194             if not nid:
195                 break
196             if len(nid)>1:
197                 print "Duplicate dir? p= %d, n=\"%s\"" %(did,duri[0])
198             path.append(duri[0])
199             duri = duri[1:]
200             did = nid[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)
203
204         
205         nid = self.search(cr,uid,[('parent_id','=',did),('name','=',duri[0]),('type','=','ressource')], context=context)
206         if nid:
207             if len(nid)>1:
208                 print "Duplicate dir? p= %d, n=\"%s\"" %(did,duri[0])
209             path.append(duri[0])
210             duri = duri[1:]
211             did = nid[0]
212             return nodes.node_res_dir(path, nparent,ncontext,self.browse(cr,uid,did, context))
213
214         # Here, we must find the appropriate non-dir child..
215         # Chech for files:
216         fil_obj = self.pool.get('ir.attachment')
217         nid = fil_obj.search(cr,uid,[('parent_id','=',did),('name','=',duri[0])],context=context)
218         if nid:
219                 if len(duri)>1:
220                         # cannot treat child as a dir
221                         return None
222                 if len(nid)>1:
223                         print "Duplicate file?",did,duri[0]
224                 path.append(duri[0])
225                 return nodes.node_file(path,nparent,ncontext,fil_obj.browse(cr,uid,nid[0],context))
226         
227         print "nothing found:",did, duri
228         #still, nothing found
229         return None
230         
231     def old_code():
232         if not uri:
233             return node_database(cr, uid, context=context)
234         turi = tuple(uri)
235         node = node_class(cr, uid, '/', False, context=context, type='database')
236         for path in uri[:]:
237             if path:
238                 node = node.child(path)
239                 if not node:
240                     return False
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
243         return node
244
245     def ol_get_childs(self, cr, uid, uri, context={}):
246         node = self.get_object(cr, uid, uri, context)
247         if uri:
248             children = node.children()
249         else:
250             children= [node]
251         result = map(lambda node: node.path_get(), children)
252         return result
253
254     def copy(self, cr, uid, id, default=None, context=None):
255         if not default:
256             default ={}
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)
260
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)
266         if op=='write':
267             for directory in self.browse(cr,uid,ids):
268                 if not name:
269                     name=directory.name
270                 if not parent_id:
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
274                 if not ressource_id:
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)])
277                 if len(res):
278                     return False
279         if op=='create':
280             res=self.search(cr,uid,[('name','=',name),('parent_id','=',parent_id),('ressource_parent_type_id','=',ressource_parent_type_id),('ressource_id','=',ressource_id)])
281             if len(res):
282                 return False
283         return True
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)
288
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)
295
296 document_directory()
297
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.
306     """
307     _name = 'document.directory.dctx'
308     _description = 'Directory dynamic context'
309     _columns = {
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"),
314         }
315
316 document_directory_dctx()
317
318
319 class document_directory_node(osv.osv):
320     _inherit = 'process.node'
321     _columns = {
322         'directory_id':  fields.many2one('document.directory', 'Document directory', ondelete="set null"),
323     }
324 document_directory_node()