~openerp-spain-team/openerp-spain/6.0-git

« back to all changes in this revision

Viewing changes to l10n_es_extras/l10n_ES_toponyms/l10n_ES_toponyms.py

  • Committer: Borja L.S.
  • Date: 2010-10-18 10:04:25 UTC
  • Revision ID: git-v1:271c47a993616dbba60585d48b8b98d603199d93
[REF] *: Refactorización para portar a 6.0 - Paso 1.

- Se han renombrado los módulos para usar la nomenclatura propuesta
  por OpenERP: l10n_es para el módulo base de localización (plan de 
  cuentas), l10n_es_* para el resto de módulos.

- Se eliminan los módulos extra_addons/* que deberían moverse a 
  los extra-addons genéricos (no son específicos de España).

- Se renombran los __terp__.py por __openerp__.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- encoding: utf-8 -*-
2
 
##############################################################################
3
 
#
4
 
#    OpenERP, Open Source Management Solution
5
 
#    Copyright (c) 2009 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
6
 
#                       Jordi Esteve <jesteve@zikzakmedia.com>
7
 
#    $Id$
8
 
#
9
 
#    This program is free software: you can redistribute it and/or modify
10
 
#    it under the terms of the GNU General Public License as published by
11
 
#    the Free Software Foundation, either version 3 of the License, or
12
 
#    (at your option) any later version.
13
 
#
14
 
#    This program is distributed in the hope that it will be useful,
15
 
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 
#    GNU General Public License for more details.
18
 
#
19
 
#    You should have received a copy of the GNU General Public License
20
 
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 
#
22
 
##############################################################################
23
 
 
24
 
from osv import fields,osv
25
 
import os
26
 
import ir
27
 
import pooler
28
 
import tools
29
 
import threading
30
 
 
31
 
class config_ES_toponyms(osv.osv_memory):
32
 
    _name='config.ES.toponyms'
33
 
 
34
 
    def _city_module_default(self, cr, uid, context=None):
35
 
        cr.execute('select * from ir_module_module where name=%s and state=%s', ('city','installed'))
36
 
        if cr.fetchone():
37
 
            return 'installed'
38
 
        else:
39
 
            return 'uninstalled'
40
 
 
41
 
    def _city_info_recover_default(self, cr, uid, context=None):
42
 
        # City info can be selected if zip field exists in the database. That will happen only
43
 
        # if module city wasn't installed by the initial profile.
44
 
        cr.execute("select * from information_schema.columns where table_name='res_partner_address' and table_schema='public' and column_name='zip'")
45
 
        if cr.fetchone():
46
 
            return 'yes'
47
 
        else:
48
 
            return 'no'
49
 
 
50
 
    _columns = {
51
 
        'name':fields.char('Name', size=64),
52
 
        'state': fields.selection([('official','Official'),('spanish','Spanish'),('both','Both')], 'State names', required=True, help="Toponym version of the Spanish states. For example: Official (Girona), Spanish (Gerona), Both (Gerona / Girona)"),
53
 
        'city_module': fields.selection([('installed','Installed'),('uninstalled','Uninstalled')], 'City module', readonly=True, help="City module is optional and groups state, city and zip code in one entity."),
54
 
        'city_info': fields.selection([('yes','Yes'),('no','No')], 'City information', required=True, help="Do you want to add city and state information associated to the zip codes for all the Spanish cities? This allows to fill automatically the city and states fields of partner and contact forms from the zip code."),
55
 
        'city_info_recover': fields.selection([('yes','Yes'),('no','No')], 'City information recover', required=True, help="If the city module has been installed, do you want to recover the location data (city information) from the zip code there was in the partner addresses before installing the city module?"),
56
 
    }
57
 
 
58
 
    _defaults={
59
 
        'state': lambda *args: 'official',
60
 
        'city_module': _city_module_default,
61
 
        'city_info': lambda *args: 'yes',
62
 
        'city_info_recover': _city_info_recover_default,
63
 
    }
64
 
 
65
 
    def onchange_city_info(self, cr, uid, ids, city_info, city_module):
66
 
        if city_module == 'uninstalled':
67
 
            v = {'city_info_recover': 'no'}
68
 
        elif city_info == 'yes':
69
 
            v = {
70
 
                'city_info_recover': self._city_info_recover_default(cr, uid)
71
 
            }
72
 
        return {'value':v}
73
 
 
74
 
    def _onchange_city_info(self, cr, uid, ids, city_info, city_module):
75
 
        """onchange_city_info alias for backwards compatibility"""
76
 
        return self.onchange_city_info(cr, uid, ids, city_info, city_module)
77
 
 
78
 
    def _create_defaults(self, cr, uid, context):
79
 
        # Creates default values of state and city res.partner.address fields linked to zip codes
80
 
        from municipios_cpostal import cod_postales
81
 
        pool = pooler.get_pool(cr.dbname)
82
 
        idc = pool.get('res.country').search(cr, uid, [('code', '=', 'ES'),])
83
 
        if not idc:
84
 
            return
85
 
        idc = idc[0]
86
 
        for m in cod_postales:
87
 
            ids = pool.get('res.country.state').search(cr, uid, [('country_id', '=', idc), ('code', '=', m[0][:2]),])
88
 
            if ids:
89
 
                ir.ir_set(cr, uid, 'default', 'zip='+m[0], 'state_id', [('res.partner.address', False)], ids[0])
90
 
            ir.ir_set(cr, uid, 'default', 'zip='+m[0], 'city', [('res.partner.address', False)], m[1])
91
 
        return {}
92
 
 
93
 
 
94
 
    def _recover_zipcodes(self, cr, uid, context):
95
 
        # Recovers the location data (city info) from the zip code there was in the partner addresses before installing the city module
96
 
        cr.execute("select id, zip from res_partner_address where location IS NULL")
97
 
        zipcodes = cr.dictfetchall()
98
 
        cont = 0
99
 
        for zipcode in zipcodes:
100
 
            if zipcode['zip']:
101
 
                cr.execute("select id from city_city where zipcode = '%s'" %zipcode['zip'])
102
 
                city_id = cr.fetchall()
103
 
                if len(city_id) > 0:
104
 
                    cr.execute("update res_partner_address SET location = %i WHERE id = %i" %(city_id[0][0], zipcode['id']))
105
 
                    cont += 1
106
 
        return cont
107
 
 
108
 
 
109
 
    def create_zipcodes(self, db_name, uid, ids, res, context):
110
 
        # Import Spanish cities and zip codes (15000 zip codes can take several minutes)
111
 
        db, pool = pooler.get_db_and_pool(db_name)
112
 
        cr = db.cursor()
113
 
        if res['city_module'] == 'uninstalled': # city module no installed
114
 
            self._create_defaults(cr, uid, context)
115
 
        else:                                   # city module installed
116
 
            try:
117
 
                fp = tools.file_open(os.path.join('l10n_ES_toponyms', 'l10n_ES_toponyms_zipcodes.xml'))
118
 
            except IOError, e:
119
 
                fp = None
120
 
            if fp:
121
 
                idref = {}
122
 
                tools.convert_xml_import(cr, 'l10n_ES_toponyms', fp,  idref, 'init', noupdate=True)
123
 
                if res['city_info_recover'] == 'yes':
124
 
                    res= self._recover_zipcodes(cr, uid, context)
125
 
                    #print res
126
 
        cr.commit()
127
 
        cr.close()
128
 
        return {}
129
 
 
130
 
 
131
 
    def action_set(self, cr, uid, ids, context=None):
132
 
        res = self.read(cr, uid, ids)[0]
133
 
        #print res
134
 
 
135
 
        # Import Spanish states (official, Spanish or both)
136
 
        file_name = 'l10n_ES_toponyms_states_'+res['state']+'.xml'
137
 
        try:
138
 
            fp = tools.file_open(os.path.join('l10n_ES_toponyms', file_name))
139
 
        except IOError, e:
140
 
            fp = None
141
 
        if fp:
142
 
            idref = {}
143
 
            tools.convert_xml_import(cr, 'l10n_ES_toponyms', fp,  idref, 'init', noupdate=True)
144
 
 
145
 
        # Import Spanish cities and zip codes in other thread (15000 zip codes can take several minutes)
146
 
        if res['city_info'] == 'yes':
147
 
            cr.commit()
148
 
            thread1 = threading.Thread(target=self.create_zipcodes, args=(cr.dbname, uid, ids, res, context))
149
 
            thread1.start()
150
 
 
151
 
        return {
152
 
                'view_type': 'form',
153
 
                "view_mode": 'form',
154
 
                'res_model': 'ir.actions.configuration.wizard',
155
 
                'type': 'ir.actions.act_window',
156
 
                'target':'new',
157
 
            }
158
 
 
159
 
 
160
 
    def action_cancel(self, cr, uid, ids, conect=None):
161
 
        return {
162
 
                'view_type': 'form',
163
 
                "view_mode": 'form',
164
 
                'res_model': 'ir.actions.configuration.wizard',
165
 
                'type': 'ir.actions.act_window',
166
 
                'target':'new',
167
 
         }
168
 
 
169
 
config_ES_toponyms()