~unifield-team/unifield-wm/us-826

« back to all changes in this revision

Viewing changes to financing_contract/contract.py

  • Committer: jf
  • Date: 2011-05-16 09:55:17 UTC
  • mfrom: (129.1.1 unifield-wm)
  • Revision ID: jf@tempo4-20110516095517-giuzv2mouka39jb8
UF-270 Advance return in a currency that is not the functional currency

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- coding: utf-8 -*-
2
 
##############################################################################
3
 
#
4
 
#    OpenERP, Open Source Management Solution
5
 
#    Copyright (C) 2011 MSF, TeMPO Consulting.
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 datetime
24
 
 
25
 
class financing_contract_funding_pool_line(osv.osv):
26
 
    # 
27
 
    _name = "financing.contract.funding.pool.line"
28
 
    _description = "Funding pool line"
29
 
    
30
 
    _columns = {
31
 
        'contract_id': fields.many2one('financing.contract.format', 'Contract', required=True),
32
 
        'funding_pool_id': fields.many2one('account.analytic.account', 'Funding pool name', required=True),
33
 
        'funded': fields.boolean('Earmarked'),
34
 
        'total_project': fields.boolean('Total project'),
35
 
    }
36
 
        
37
 
    _defaults = {
38
 
        'funded': False,
39
 
        'total_project': True,
40
 
    }
41
 
    
42
 
financing_contract_funding_pool_line()
43
 
 
44
 
class financing_contract_contract(osv.osv):
45
 
    
46
 
    _name = "financing.contract.contract"
47
 
    _inherits = {"financing.contract.format": "format_id"}
48
 
    _trace = True
49
 
 
50
 
    def contract_open(self, cr, uid, ids, *args):
51
 
        self.write(cr, uid, ids, {
52
 
            'state': 'open',
53
 
            'open_date': datetime.date.today().strftime('%Y-%m-%d'),
54
 
            'soft_closed_date': None
55
 
        })
56
 
        return True
57
 
 
58
 
    def contract_soft_closed(self, cr, uid, ids, *args):
59
 
        self.write(cr, uid, ids, {
60
 
            'state': 'soft_closed',
61
 
            'soft_closed_date': datetime.date.today().strftime('%Y-%m-%d')
62
 
        })
63
 
        return True
64
 
 
65
 
    def contract_hard_closed(self, cr, uid, ids, *args):
66
 
        self.write(cr, uid, ids, {
67
 
            'state': 'hard_closed',
68
 
            'hard_closed_date': datetime.date.today().strftime('%Y-%m-%d')
69
 
        })
70
 
        return True
71
 
    
72
 
    def get_contract_domain(self, cr, uid, browse_contract, reporting_type=None, context=None):
73
 
        # we update the context with the contract reporting type and currency
74
 
        format_line_obj = self.pool.get('financing.contract.format.line')
75
 
        # Values to be set
76
 
        account_destination_ids = []
77
 
        if reporting_type is None:
78
 
            reporting_type = browse_contract.reporting_type
79
 
        # general domain
80
 
        general_domain = format_line_obj._get_general_domain(cr,
81
 
                                                             uid,
82
 
                                                             browse_contract.format_id,
83
 
                                                             reporting_type,
84
 
                                                             context=context)
85
 
        
86
 
        # parse parent lines (either value or sum of children's values)
87
 
        for line in browse_contract.actual_line_ids:
88
 
            if not line.parent_id:
89
 
                account_destination_ids += format_line_obj._get_account_destination_ids(line, general_domain['funding_pool_account_destination_ids'])
90
 
                
91
 
        # create the domain
92
 
        analytic_domain = []
93
 
        account_domain = format_line_obj._create_account_destination_domain(account_destination_ids)
94
 
        date_domain = eval(general_domain['date_domain'])
95
 
        if reporting_type == 'allocated':
96
 
            analytic_domain = [date_domain[0],
97
 
                               date_domain[1],
98
 
                               eval(general_domain['funding_pool_domain'])]
99
 
        else: 
100
 
            analytic_domain = [date_domain[0],
101
 
                               date_domain[1],
102
 
                               eval(general_domain['funding_pool_domain']),
103
 
                               eval(general_domain['cost_center_domain'])]
104
 
        analytic_domain += account_domain
105
 
            
106
 
        return analytic_domain
107
 
 
108
 
    def _get_overhead_amount(self, cr, uid, ids, field_name=None, arg=None, context=None):
109
 
        """
110
 
            Method to compute the overhead amount
111
 
        """
112
 
        res = {}
113
 
        for budget in self.browse(cr, uid, ids, context=context):
114
 
            # default value
115
 
            res[budget.id] = 0.0
116
 
            if budget.overhead_type == 'cost_percentage':
117
 
                res[budget.id] = round(budget.grant_amount * budget.overhead_percentage / (100.0 + budget.overhead_percentage))
118
 
            elif budget.overhead_type == 'grant_percentage':
119
 
                res[budget.id] = round(budget.grant_amount * budget.overhead_percentage / 100.0)
120
 
        return res
121
 
    
122
 
    _columns = {
123
 
        'name': fields.char('Financing contract name', size=64, required=True),
124
 
        'code': fields.char('Financing contract code', size=16, required=True),
125
 
        'donor_id': fields.many2one('financing.contract.donor', 'Donor', required=True),
126
 
        'donor_grant_reference': fields.char('Donor grant reference', size=64),
127
 
        'hq_grant_reference': fields.char('HQ grant reference', size=64),
128
 
        'grant_amount': fields.float('Grant amount', required=True),
129
 
        'overhead_amount': fields.function(_get_overhead_amount, method=True, store=False, string="Overhead amount", type="float", readonly=True),
130
 
        'reporting_currency': fields.many2one('res.currency', 'Reporting currency', required=True),
131
 
        'notes': fields.text('Notes'),
132
 
        'open_date': fields.date('Open date'),
133
 
        'soft_closed_date': fields.date('Soft-closed date'),
134
 
        'hard_closed_date': fields.date('Hard-closed date'),
135
 
        'state': fields.selection([('draft','Draft'),
136
 
                                    ('open','Open'),
137
 
                                    ('soft_closed', 'Soft-closed'),
138
 
                                    ('hard_closed', 'Hard-closed')], 'State'),
139
 
        'currency_table_id': fields.many2one('res.currency.table', 'Currency Table'),
140
 
        # Define for _inherits
141
 
        'format_id': fields.many2one('financing.contract.format', 'Format', ondelete="cascade", required=True),
142
 
    }
143
 
    
144
 
    _defaults = {
145
 
        'state': 'draft',
146
 
        'reporting_currency': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.currency_id.id,
147
 
        'format_id': lambda self,cr,uid,context: self.pool.get('financing.contract.format').create(cr, uid, {}, context=context)
148
 
    }
149
 
 
150
 
    def _check_unicity(self, cr, uid, ids, context=None):
151
 
        if not context:
152
 
            context = {}
153
 
        for contract in self.browse(cr, uid, ids, context=context):
154
 
            bad_ids = self.search(cr, uid, [('|'),('name', '=ilike', contract.name),('code', '=ilike', contract.code)])
155
 
            if len(bad_ids) and len(bad_ids) > 1:
156
 
                return False
157
 
        return True
158
 
 
159
 
    _constraints = [
160
 
        (_check_unicity, 'You cannot have the same code or name between contracts!', ['code', 'name']),
161
 
    ]
162
 
 
163
 
    def copy(self, cr, uid, id, default=None, context=None, done_list=[], local=False):
164
 
        contract = self.browse(cr, uid, id, context=context)
165
 
        if not default:
166
 
            default = {}
167
 
        default = default.copy()
168
 
        default['code'] = (contract['code'] or '') + '(copy)'
169
 
        default['name'] = (contract['name'] or '') + '(copy)'
170
 
        # Copy lines manually
171
 
        default['actual_line_ids'] = []
172
 
        copy_id = super(financing_contract_contract, self).copy(cr, uid, id, default, context=context)
173
 
        copy = self.browse(cr, uid, copy_id, context=context)
174
 
        self.pool.get('financing.contract.format').copy_format_lines(cr, uid, contract.format_id.id, copy.format_id.id, context=context)
175
 
        return copy_id
176
 
    
177
 
    def onchange_donor_id(self, cr, uid, ids, donor_id, format_id, actual_line_ids, context=None):
178
 
        res = {}
179
 
        if donor_id and format_id:
180
 
            donor = self.pool.get('financing.contract.donor').browse(cr, uid, donor_id, context=context)
181
 
            if donor.format_id:
182
 
                source_format = donor.format_id
183
 
                format_vals = {
184
 
                    'format_name': source_format.format_name,
185
 
                    'reporting_type': source_format.reporting_type,
186
 
                    'overhead_type': source_format.overhead_type,
187
 
                    'overhead_percentage': source_format.overhead_percentage,
188
 
                }
189
 
                self.pool.get('financing.contract.format').copy_format_lines(cr, uid, donor.format_id.id, format_id, context=context)
190
 
        return {'value': format_vals}
191
 
    
192
 
    def onchange_currency_table(self, cr, uid, ids, currency_table_id, reporting_currency_id, context=None):
193
 
        values = {'reporting_currency': False}
194
 
        if reporting_currency_id:
195
 
            # it can be a currency from another table
196
 
            reporting_currency = self.pool.get('res.currency').browse(cr, uid, reporting_currency_id, context=context)
197
 
            # Search if the currency is in the table, and active
198
 
            if reporting_currency.reference_currency_id:
199
 
                currency_results = self.pool.get('res.currency').search(cr, uid, [('reference_currency_id', '=', reporting_currency.reference_currency_id.id),
200
 
                                                                                  ('currency_table_id', '=', currency_table_id),
201
 
                                                                                  ('active', '=', True)], context=context)
202
 
            else:
203
 
                currency_results = self.pool.get('res.currency').search(cr, uid, [('reference_currency_id', '=', reporting_currency_id),
204
 
                                                                                  ('currency_table_id', '=', currency_table_id),
205
 
                                                                                  ('active', '=', True)], context=context)
206
 
            if len(currency_results) > 0:
207
 
                # it's here, we keep the currency
208
 
                values['reporting_currency'] = reporting_currency_id
209
 
        # Restrain domain to selected table (or None if none selected
210
 
        domains = {'reporting_currency': [('currency_table_id', '=', currency_table_id)]}
211
 
        return {'value': values, 'domain': domains}
212
 
    
213
 
    def create_reporting_line(self, cr, uid, browse_contract, browse_format_line, parent_report_line_id=None, context=None):
214
 
        format_line_obj = self.pool.get('financing.contract.format.line')
215
 
        reporting_line_obj = self.pool.get('financing.contract.donor.reporting.line')
216
 
        analytic_domain = format_line_obj._get_analytic_domain(cr,
217
 
                                                               uid,
218
 
                                                               browse_format_line,
219
 
                                                               browse_contract.reporting_type,
220
 
                                                               context=context)
221
 
        vals = {'name': browse_format_line.name,
222
 
                'code': browse_format_line.code,
223
 
                'line_type': browse_format_line.line_type,
224
 
                'allocated_budget': round(browse_format_line.allocated_budget),
225
 
                'project_budget': round(browse_format_line.project_budget),
226
 
                'allocated_real': round(browse_format_line.allocated_real),
227
 
                'project_real': round(browse_format_line.project_real),
228
 
                'analytic_domain': analytic_domain,
229
 
                'parent_id': parent_report_line_id}
230
 
        reporting_line_id = reporting_line_obj.create(cr,
231
 
                                                      uid,
232
 
                                                      vals,
233
 
                                                      context=context)
234
 
        # create child lines
235
 
        for child_line in browse_format_line.child_ids:
236
 
            self.create_reporting_line(cr, uid, browse_contract, child_line, reporting_line_id, context=context)
237
 
        return reporting_line_id
238
 
    
239
 
    def menu_interactive_report(self, cr, uid, ids, context=None):
240
 
        if context is None:
241
 
            context = {}
242
 
        # we update the context with the contract reporting type
243
 
        contract = self.browse(cr, uid, ids[0], context=context)
244
 
        context.update({'reporting_currency': contract.reporting_currency.id,
245
 
                        'reporting_type': contract.reporting_type,
246
 
                        'currency_table_id': contract.currency_table_id.id,
247
 
                        'active_id': ids[0],
248
 
                        'active_ids': ids,
249
 
                        'display_fp': True})
250
 
        ## INFO: display_fp in context permits to display Funding Pool column and its attached cost center.
251
 
        reporting_line_obj = self.pool.get('financing.contract.donor.reporting.line')
252
 
        # Create reporting lines
253
 
        # Contract line first (we'll fill it later)
254
 
        contract_line_id = reporting_line_obj.create(cr,
255
 
                                                     uid,
256
 
                                                     vals = {'name': contract.name,
257
 
                                                             'code': contract.code,
258
 
                                                             'line_type': 'view'},
259
 
                                                     context=context)
260
 
        
261
 
        # Values to be set
262
 
        allocated_budget = 0
263
 
        project_budget = 0
264
 
        allocated_real = 0
265
 
        project_real = 0
266
 
        
267
 
        # create "real" lines
268
 
        for line in contract.actual_line_ids:
269
 
            if not line.parent_id:
270
 
                allocated_budget += line.allocated_budget
271
 
                project_budget += line.project_budget
272
 
                allocated_real += line.allocated_real
273
 
                project_real += line.project_real
274
 
                reporting_line_id = self.create_reporting_line(cr, uid, contract, line, contract_line_id, context=context)
275
 
        
276
 
        # Refresh contract line with general infos
277
 
        analytic_domain = self.get_contract_domain(cr, uid, contract, context=context)
278
 
        contract_values = {'allocated_budget': allocated_budget,
279
 
                           'project_budget': project_budget,
280
 
                           'allocated_real': allocated_real,
281
 
                           'project_real': project_real,
282
 
                           'analytic_domain': analytic_domain}
283
 
        reporting_line_obj.write(cr, uid, [contract_line_id], vals=contract_values, context=context)
284
 
        
285
 
        # retrieve the corresponding_view
286
 
        model_data_obj = self.pool.get('ir.model.data')
287
 
        view_id = False
288
 
        view_ids = model_data_obj.search(cr, uid, 
289
 
                                        [('module', '=', 'financing_contract'), 
290
 
                                         ('name', '=', 'view_donor_reporting_line_tree_%s' % str(contract.reporting_type))],
291
 
                                        offset=0, limit=1)
292
 
        if len(view_ids) > 0:
293
 
            view_id = model_data_obj.browse(cr, uid, view_ids[0]).res_id
294
 
        return {
295
 
               'type': 'ir.actions.act_window',
296
 
               'res_model': 'financing.contract.donor.reporting.line',
297
 
               'view_type': 'tree',
298
 
               'view_id': [view_id],
299
 
               'target': 'current',
300
 
               'domain': [('id', '=', contract_line_id)],
301
 
               'context': context
302
 
        }
303
 
        
304
 
    def menu_allocated_expense_report(self, cr, uid, ids, context=None):
305
 
        if context is None:
306
 
            context = {}
307
 
        wiz_obj = self.pool.get('wizard.expense.report')
308
 
        wiz_id = wiz_obj.create(cr, uid, {'reporting_type': 'allocated',
309
 
                                          'filename': 'allocated_expenses.csv',
310
 
                                          'contract_id': ids[0]}, context=context)
311
 
        # we open a wizard
312
 
        return {
313
 
                'type': 'ir.actions.act_window',
314
 
                'res_model': 'wizard.expense.report',
315
 
                'view_type': 'form',
316
 
                'view_mode': 'form',
317
 
                'target': 'new',
318
 
                'res_id': [wiz_id],
319
 
                'context': context,
320
 
        }
321
 
        
322
 
    def menu_project_expense_report(self, cr, uid, ids, context=None):
323
 
        if context is None:
324
 
            context = {}
325
 
        wiz_obj = self.pool.get('wizard.expense.report')
326
 
        wiz_id = wiz_obj.create(cr, uid, {'reporting_type': 'project',
327
 
                                          'filename': 'project_expenses.csv',
328
 
                                          'contract_id': ids[0]}, context=context)
329
 
        # we open a wizard
330
 
        return {
331
 
                'type': 'ir.actions.act_window',
332
 
                'res_model': 'wizard.expense.report',
333
 
                'view_type': 'form',
334
 
                'view_mode': 'form',
335
 
                'target': 'new',
336
 
                'res_id': [wiz_id],
337
 
                'context': context,
338
 
        }
339
 
        
340
 
    def menu_csv_interactive_report(self, cr, uid, ids, context=None):
341
 
        if context is None:
342
 
            context = {}
343
 
        wiz_obj = self.pool.get('wizard.interactive.report')
344
 
        wiz_id = wiz_obj.create(cr, uid, {'filename': 'interactive_report.csv',
345
 
                                          'contract_id': ids[0]}, context=context)
346
 
        # we open a wizard
347
 
        return {
348
 
                'type': 'ir.actions.act_window',
349
 
                'res_model': 'wizard.interactive.report',
350
 
                'view_type': 'form',
351
 
                'view_mode': 'form',
352
 
                'target': 'new',
353
 
                'res_id': [wiz_id],
354
 
                'context': context,
355
 
        }
356
 
    
357
 
financing_contract_contract()
358
 
 
359
 
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: