[FIX] web: form_view: FieldStatus widget: fixed hidden states/stages not appearing...
[odoo/odoo.git] / addons / google_spreadsheet / google_spreadsheet.py
1 ##############################################################################
2 #
3 #    OpenERP, Open Source Management Solution
4 #    Copyright (C) 2004-2012 OpenERP SA (<http://www.openerp.com>).
5 #
6 #    This program is free software: you can redistribute it and/or modify
7 #    it under the terms of the GNU Affero General Public License as
8 #    published by the Free Software Foundation, either version 3 of the
9 #    License, or (at your option) any later version.
10 #
11 #    This program is distributed in the hope that it will be useful,
12 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #    GNU Affero General Public License for more details.
15 #
16 #    You should have received a copy of the GNU Affero General Public License
17 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 ##############################################################################
20
21 import simplejson
22 import logging
23 from lxml import etree
24 import re
25 import urllib
26 import urllib2
27
28 from openerp.osv import osv
29 from openerp import SUPERUSER_ID
30
31 _logger = logging.getLogger(__name__)
32
33 class config(osv.osv):
34     _inherit = 'google.drive.config'
35
36     def get_google_scope(self):
37         scope = super(config, self).get_google_scope()
38         return '%s https://spreadsheets.google.com/feeds' % scope
39
40     def write_config_formula(self, cr, uid, attachment_id, spreadsheet_key, model, domain, groupbys, view_id, context=None):
41         access_token = self.get_access_token(cr, uid, scope='https://spreadsheets.google.com/feeds', context=context)
42
43         fields = self.pool.get(model).fields_view_get(cr, uid, view_id=view_id, view_type='tree')
44         doc = etree.XML(fields.get('arch'))
45         display_fields = []
46         for node in doc.xpath("//field"):
47             if node.get('modifiers'):
48                 modifiers = simplejson.loads(node.get('modifiers'))
49                 if not modifiers.get('invisible') and not modifiers.get('tree_invisible'):
50                     display_fields.append(node.get('name'))
51         fields = " ".join(display_fields)
52         domain = domain.replace("'", r"\'").replace('"', "'")
53         if groupbys:
54             fields = "%s %s" % (groupbys, fields)
55             formula = '=oe_read_group("%s";"%s";"%s";"%s")' % (model, fields, groupbys, domain)
56         else:
57             formula = '=oe_browse("%s";"%s";"%s")' % (model, fields, domain)
58         url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
59         dbname = cr.dbname
60         user = self.pool['res.users'].read(cr, uid, uid, ['login', 'password'], context=context)
61         username = user['login']
62         password = user['password']
63         if self.pool['ir.module.module'].search_count(cr, SUPERUSER_ID, ['&', ('name', '=', 'auth_crypt'), ('state', '=', 'installed')]) == 1:
64             config_formula = '=oe_settings("%s";"%s")' % (url, dbname)
65         else:
66             config_formula = '=oe_settings("%s";"%s";"%s";"%s")' % (url, dbname, username, password)
67         request = '''<feed xmlns="http://www.w3.org/2005/Atom"
68       xmlns:batch="http://schemas.google.com/gdata/batch"
69       xmlns:gs="http://schemas.google.com/spreadsheets/2006">
70   <id>https://spreadsheets.google.com/feeds/cells/%s/od6/private/full</id>
71   <entry>
72     <batch:id>A1</batch:id>
73     <batch:operation type="update"/>
74     <id>https://spreadsheets.google.com/feeds/cells/%s/od6/private/full/R1C1</id>
75     <link rel="edit" type="application/atom+xml"
76       href="https://spreadsheets.google.com/feeds/cells/%s/od6/private/full/R1C1"/>
77     <gs:cell row="1" col="1" inputValue="%s"/>
78   </entry>
79   <entry>
80     <batch:id>A2</batch:id>
81     <batch:operation type="update"/>
82     <id>https://spreadsheets.google.com/feeds/cells/%s/od6/private/full/R60C15</id>
83     <link rel="edit" type="application/atom+xml"
84       href="https://spreadsheets.google.com/feeds/cells/%s/od6/private/full/R60C15"/>
85     <gs:cell row="60" col="15" inputValue="%s"/>
86   </entry>
87 </feed>''' % (spreadsheet_key, spreadsheet_key, spreadsheet_key, formula.replace('"', '&quot;'), spreadsheet_key, spreadsheet_key, config_formula.replace('"', '&quot;'))
88
89         try:
90             req = urllib2.Request(
91                 'https://spreadsheets.google.com/feeds/cells/%s/od6/private/full/batch?%s' % (spreadsheet_key, urllib.urlencode({'v': 3, 'access_token': access_token})),
92                 data=request,
93                 headers={'content-type': 'application/atom+xml', 'If-Match': '*'})
94             urllib2.urlopen(req)
95         except (urllib2.HTTPError, urllib2.URLError):
96             _logger.warning("An error occured while writting the formula on the Google Spreadsheet.")
97
98         description = '''
99         formula: %s
100         ''' % formula
101         if attachment_id:
102             self.pool['ir.attachment'].write(cr, uid, attachment_id, {'description': description}, context=context)
103         return True
104
105     def set_spreadsheet(self, cr, uid, model, domain, groupbys, view_id, context=None):
106         try:
107             config_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'google_spreadsheet', 'google_spreadsheet_template')[1]
108         except ValueError:
109             raise
110         config = self.browse(cr, uid, config_id, context=context)
111         title = 'Spreadsheet %s' % model
112         res = self.copy_doc(cr, uid, False, config.google_drive_resource_id, title, model, context=context)
113
114         mo = re.search("(key=|/d/)([A-Za-z0-9-_]+)", res['url'])
115         if mo:
116             key = mo.group(2)
117
118         self.write_config_formula(cr, uid, res.get('id'), key, model, domain, groupbys, view_id, context=context)
119         return res