[IMP] rename the fields
[odoo/odoo.git] / addons / sale / res_config.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 from osv import fields, osv
23 import pooler
24 from tools.translate import _
25
26 MODULE_LIST = [
27                'analytic_user_function', 'analytic_journal_billing_rate', 'import_sugarcrm',
28                'import_google', 'crm_caldav', 'wiki_sale_faq', 'base_contact','sale_layout','warning',
29                'google_map', 'fetchmail_crm', 'plugin_thunderbird', 'plugin_outlook','account_analytic_analysis',
30                'project_timesheet', 'account_analytic_analysis', 'project_mrp', 'delivery',
31                'sale_margin', 'sale_journal'
32 ]
33
34 class sale_configuration(osv.osv_memory):
35     _inherit = 'res.config'
36
37     _columns = {
38         'sale_orders': fields.boolean('Based on Sales Orders',),
39         'deli_orders': fields.boolean('Based on Delivery Orders'),
40         'task_work': fields.boolean('Based on Tasks\' Work',
41                                     help="""
42                                     It installs the project_timesheet and project_mrp module
43                                     project_timesheet :lets you transfer the entries under tasks defined for Project Management to
44                                     the Timesheet line entries for particular date and particular user  with the effect of creating, editing and deleting either ways.
45                                     project_mrp : Automatically creates project tasks from procurement lines"""),
46         'timesheet': fields.boolean('Based on Timesheet',
47                                     help = """for modifying account analytic view to show important data to project manager of services companies,
48                                     You can also view the report of account analytic summary user-wise as well as month wise
49                                     ,It installs the account_analytic_analysis module."""),
50         'order_policy': fields.selection([
51             ('manual', 'Invoice Based on Sales Orders'),
52             ('picking', 'Invoice Based on Deliveries'),
53         ], 'Main Method Based On', required=True, help="You can generate invoices based on sales orders or based on shippings."),
54         'module_delivery': fields.boolean('Do you charge the delivery?',
55                                    help ="""
56                                    Allows you to add delivery methods in sale orders and picking,
57                                    You can define your own carrier and delivery grids for prices.
58                                    It installs the delivery module.
59                                    """),
60         'time_unit': fields.many2one('product.uom','Working Time Unit'),
61         'picking_policy' : fields.boolean("Deliver all products at once?", help = ""),
62         'group_sale_delivery_address':fields.boolean("Multiple Address",help="Group To Allow delivery address different from invoice address"),
63         'group_sale_disc_per_sale_order_line':fields.boolean("Discounts per sale order lines ",help="Group to apply discounts per sale order lines"),
64         'module_sale_layout':fields.boolean("Notes & subtotals per line",help="Allows to format sale order lines using notes, separators, titles and subtotals. It installs the sale_layout module."),
65         'module_warning': fields.boolean("Alerts by products or customers",
66                                   help="""To trigger warnings in OpenERP objects.
67                                   Warning messages can be displayed for objects like sale order, purchase order, picking and invoice. The message is triggered by the form's onchange event.
68                                   It installs the warning module."""),
69         'module_sale_margin': fields.boolean("Display Margin For Users",
70                         help="""This adds the 'Margin' on sales order,
71                         This gives the profitability by calculating the difference between the Unit Price and Cost Price.
72                         .It installs the sale_margin module."""),
73         'module_sale_journal': fields.boolean("Invoice journal?",
74                         help="""This allows you to categorise your sales and deliveries (picking lists) between different journals.
75                         It installs the sale_journal module."""),
76         'module_analytic_user_function' : fields.boolean("User function by contracts",
77                                     help="""This allows you to define what is the default function of a specific user on a given account
78                                     This is mostly used when a user encodes his timesheet: the values are retrieved and the fields are auto-filled. But the possibility to change these values is still available.
79                                     It Installs analytic_user_function module"""),
80         'module_analytic_journal_billing_rate' : fields.boolean("Billing rates by contracts",
81                                     help=""" This allows you to define what is the default invoicing rate for a specific journal on a given account.
82                                     It installs analytic_journal_billing_rate module.
83                                     """),
84         'module_account_analytic_analysis': fields.boolean('Contracts',
85                                     help = """
86                                     For modifying account analytic view to show important data to project manager of services companies,
87                                     You can also view the report of account analytic summary user-wise as well as month wise
88                                     ,It installs the account_analytic_analysis module."""),
89     }
90
91     def get_default_applied_groups(self, cr, uid, ids, context=None):
92         applied_groups = {}
93         user_obj = self.pool.get('res.users')
94         dataobj = self.pool.get('ir.model.data')
95
96         groups = []
97         user_group_ids = user_obj.browse(cr, uid, uid, context=context).groups_id
98
99         for group_id in user_group_ids:
100             groups.append(group_id.id)
101
102         for id in groups:
103             key_id = dataobj.search(cr, uid,[('res_id','=',id),('model','=','res.groups')],context=context)
104             key = dataobj.browse(cr, uid, key_id[0], context=context).name
105             applied_groups[key] = True
106
107         return applied_groups
108
109     def get_default_installed_modules(self, cr, uid, ids, context=None):
110         module_obj = self.pool.get('ir.module.module')
111         module_ids = module_obj.search(cr, uid,
112                            [('name','in',MODULE_LIST),
113                             ('state','in',['to install', 'installed', 'to upgrade'])],
114                            context=context)
115         installed_modules = dict([(mod.name,True) for mod in module_obj.browse(cr, uid, module_ids, context=context)])
116         if installed_modules.get('project_mrp') and installed_modules.get('project_timesheet'):
117             installed_modules['task_work'] = True
118         if installed_modules.get('account_analytic_analysis'):
119             installed_modules['timesheet'] = True
120         return installed_modules
121     
122     def get_default_sale_configs(self, cr, uid, ids, context=None):
123         ir_values_obj = self.pool.get('ir.values')
124         data_obj = self.pool.get('ir.model.data')
125         menu_obj = self.pool.get('ir.ui.menu')
126         result = {}
127         invoicing_groups_id = [gid.id for gid in data_obj.get_object(cr, uid, 'sale', 'menu_invoicing_sales_order_lines').groups_id]
128         picking_groups_id = [gid.id for gid in data_obj.get_object(cr, uid, 'sale', 'menu_action_picking_list_to_invoice').groups_id]
129         group_id = data_obj.get_object(cr, uid, 'base', 'group_sale_salesman').id
130         for menu in ir_values_obj.get(cr, uid, 'default', False, ['ir.ui.menu']):
131             if menu[1] == 'groups_id' and group_id in menu[2][0]:
132                 if group_id in invoicing_groups_id:
133                     result['sale_orders'] = True
134                 if group_id in picking_groups_id:
135                     result['deli_orders'] = True
136         for res in ir_values_obj.get(cr, uid, 'default', False, ['sale.order']):
137             result[res[1]] = res[2]
138         return result
139     
140     def get_default_groups(self, cr, uid, ids, context=None):
141         ir_values_obj = self.pool.get('ir.values')
142         result = {}
143         for res in ir_values_obj.get(cr, uid, 'default', False, ['res.users']):
144             result[res[1]] = res[2]
145         return result
146     
147     def default_get(self, cr, uid, fields_list, context=None):
148         result = super(sale_configuration, self).default_get(
149             cr, uid, fields_list, context=context)
150         for method in dir(self):
151             if method.startswith('get_default_'):
152                 result.update(getattr(self, method)(cr, uid, [], context))
153         return result
154     
155     _defaults = {
156         'order_policy': 'manual',
157         'time_unit': lambda self, cr, uid, c: self.pool.get('product.uom').search(cr, uid, [('name', '=', _('Hour'))], context=c) and self.pool.get('product.uom').search(cr, uid, [('name', '=', _('Hour'))], context=c)[0] or False,
158     }
159
160     def create(self, cr, uid, vals, context=None):
161         ids = super(sale_configuration, self).create(cr, uid, vals, context=context)
162         self.execute(cr, uid, [ids], vals, context=context)
163         return ids
164
165     def write(self, cr, uid, ids, vals, context=None):
166         self.execute(cr, uid, ids, vals, context=context)
167         return super(sale_configuration, self).write(cr, uid, ids, vals, context=context)
168
169     def execute(self, cr, uid, ids, vals, context=None):
170         #TODO: TO BE IMPLEMENTED
171         for method in dir(self):
172             if method.startswith('set_'):
173                 vals['modules'] = MODULE_LIST
174                 getattr(self, method)(cr, uid, ids, vals, context)
175         return True
176
177     def set_modules(self, cr, uid, ids, vals, context=None):
178         module_obj = self.pool.get('ir.module.module')
179         MODULE_LIST = vals.get('modules')
180         if vals.get('task_work'):
181             vals.update({'project_timesheet': True,'project_mrp': True})
182         if vals.get('timesheet'):
183             vals.update({'account_analytic_analysis': True})
184         for k, v in vals.items():
185             if k in MODULE_LIST:
186                 installed = self.get_default_installed_modules(cr, uid, [k], context)
187                 if v == True and not installed.get(k):
188                     module_id = module_obj.search(cr, uid, [('name','=',k)])
189                     module_obj.button_immediate_install(cr, uid, module_id, context)
190                 elif v == False and installed.get(k):
191                     module_id = module_obj.search(cr, uid, [('name','=',k)])
192                     module_obj.button_uninstall(self, cr, uid, module_id, context=None)
193                     module_obj.button_upgrade(self, cr, uid, module_id, context=None)
194
195     def set_sale_defaults(self, cr, uid, ids, vals, context=None):
196         ir_values_obj = self.pool.get('ir.values')
197         data_obj = self.pool.get('ir.model.data')
198         menu_obj = self.pool.get('ir.ui.menu')
199         res = {}
200         wizard = self.browse(cr, uid, ids)[0]
201         group_id = data_obj.get_object(cr, uid, 'base', 'group_sale_salesman').id
202
203         if wizard.sale_orders:
204             menu_id = data_obj.get_object(cr, uid, 'sale', 'menu_invoicing_sales_order_lines').id
205             menu_obj.write(cr, uid, menu_id, {'groups_id':[(4,group_id)]})
206             ir_values_obj.set(cr, uid, 'default', False, 'groups_id', ['ir.ui.menu'], [(4,group_id)])
207
208         if wizard.deli_orders:
209             menu_id = data_obj.get_object(cr, uid, 'sale', 'menu_action_picking_list_to_invoice').id
210             menu_obj.write(cr, uid, menu_id, {'groups_id':[(4,group_id)]})
211             ir_values_obj.set(cr, uid, 'default', False, 'groups_id', ['ir.ui.menu'], [(4,group_id)])
212             
213         if wizard.picking_policy:
214             ir_values_obj.set(cr, uid, 'default', False, 'picking_policy', ['sale.order'], 'one')
215
216         if wizard.time_unit:
217             prod_id = data_obj.get_object(cr, uid, 'product', 'product_consultant').id
218             product_obj = self.pool.get('product.product')
219             product_obj.write(cr, uid, prod_id, {'uom_id': wizard.time_unit.id, 'uom_po_id': wizard.time_unit.id})
220
221         ir_values_obj.set(cr, uid, 'default', False, 'order_policy', ['sale.order'], wizard.order_policy)
222         if wizard.task_work and wizard.time_unit:
223             company_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.id
224             self.pool.get('res.company').write(cr, uid, [company_id], {
225                 'project_time_mode_id': wizard.time_unit.id
226             }, context=context)
227             
228         return res
229
230     def set_groups(self, cr, uid, ids, vals, context=None):
231         data_obj = self.pool.get('ir.model.data')
232         users_obj = self.pool.get('res.users')
233         groups_obj = self.pool.get('res.groups')
234         ir_values_obj = self.pool.get('ir.values')
235         dummy,user_group_id = data_obj.get_object_reference(cr, uid, 'base', 'group_user')
236         for group in vals.keys():
237             if group.startswith('group_'):
238                 dummy,group_id = data_obj.get_object_reference(cr, uid, 'base', group)
239                 if vals[group]:
240                     groups_obj.write(cr, uid, [user_group_id], {'implied_ids': [(4,group_id)]})
241                     users_obj.write(cr, uid, [uid], {'groups_id': [(4,group_id)]})
242                     ir_values_obj.set(cr, uid, 'default', False, 'groups_id', ['res.users'], [(4,group_id)])
243                 else:
244                     groups_obj.write(cr, uid, [user_group_id], {'implied_ids': [(3,group_id)]})
245                     users_obj.write(cr, uid, [uid], {'groups_id': [(3,group_id)]})
246                     ir_values_obj.set(cr, uid, 'default', False, 'groups_id', ['res.users'], [(3,group_id)])
247
248     def onchange_tax_policy(self, cr, uid, ids, tax_policy, tax_value, context=None):
249         res = {'value': {}}
250         if isinstance(tax_value, (int)):
251             self.set_default_taxes(cr, uid, ids, {'tax_value': [tax_value]}, context=context)
252         self.set_tax_policy(cr, uid, ids, {'tax_policy': tax_policy}, context=context)
253         return res
254     
255     def set_default_taxes(self, cr, uid, ids, vals, context=None):
256         ir_values_obj = self.pool.get('ir.values')
257         taxes = self._check_default_tax(cr, uid, context=context)
258         if isinstance(vals.get('tax_value'), list):
259             taxes = vals.get('tax_value')
260         if taxes:
261             ir_values_obj.set(cr, uid, 'default', False, 'tax_id', ['sale.order'], taxes[0])
262             ir_values_obj.set(cr, uid, 'default', False, 'tax_id', ['sale.order.line'], taxes)
263             ir_values_obj.set(cr, uid, 'default', False, 'taxes_id', ['product.product'], taxes)
264
265 sale_configuration()
266
267 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: