~julie-w/unifield-wm/UTP-925

« back to all changes in this revision

Viewing changes to account_subscription/account_model.py

  • Committer: Matthieu Dietrich
  • Date: 2012-01-30 16:52:46 UTC
  • mto: This revision was merged to the branch mainline in revision 613.
  • Revision ID: mdietrich@chloups211-20120130165246-mo8ziwn7714ozaqj
UF-687: [IMP] added analytic distribution and period validation to recurring entries

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# -*- coding: utf-8 -*-
 
3
##############################################################################
 
4
#
 
5
#    OpenERP, Open Source Management Solution
 
6
#    Copyright (C) 2011 TeMPO Consulting, MSF. All Rights Reserved
 
7
#
 
8
#    This program is free software: you can redistribute it and/or modify
 
9
#    it under the terms of the GNU Affero General Public License as
 
10
#    published by the Free Software Foundation, either version 3 of the
 
11
#    License, or (at your option) any later version.
 
12
#
 
13
#    This program is distributed in the hope that it will be useful,
 
14
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
15
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
16
#    GNU Affero General Public License for more details.
 
17
#
 
18
#    You should have received a copy of the GNU Affero General Public License
 
19
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
20
#
 
21
##############################################################################
 
22
from osv import fields, osv
 
23
import time
 
24
from datetime import datetime
 
25
from dateutil.relativedelta import relativedelta
 
26
 
 
27
class account_model_line(osv.osv):
 
28
    _name = "account.model.line"
 
29
    _inherit = "account.model.line"
 
30
    
 
31
    _columns = {
 
32
        'analytic_distribution_id': fields.many2one('analytic.distribution', 'Analytic Distribution'),
 
33
        'account_user_type_code': fields.related('account_id', 'user_type_code', type="selection", string="Account User Type Code", store=False)
 
34
    }
 
35
    
 
36
    def button_analytic_distribution(self, cr, uid, ids, context={}):
 
37
        """
 
38
        Launch analytic distribution wizard on an invoice line
 
39
        """
 
40
        # Some verifications
 
41
        if not context:
 
42
            context = {}
 
43
        if isinstance(ids, (int, long)):
 
44
            ids = [ids]
 
45
        if not ids:
 
46
            raise osv.except_osv(_('Error'), _('No model line given. Please save your model line before.'))
 
47
        model_line = self.browse(cr, uid, ids[0], context=context)
 
48
        distrib_id = False
 
49
        amount = abs(model_line.debit - model_line.credit)
 
50
        currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
 
51
        # Get analytic distribution id from this line
 
52
        distrib_id = model_line.analytic_distribution_id and model_line.analytic_distribution_id.id or False
 
53
        # Prepare values for wizard
 
54
        vals = {
 
55
            'total_amount': amount,
 
56
            'model_line_id': model_line.id,
 
57
            'currency_id': currency,
 
58
            'state': 'dispatch',
 
59
            'account_id': model_line.account_id.id,
 
60
        }
 
61
        if distrib_id:
 
62
            vals.update({'distribution_id': distrib_id,})
 
63
        # Create the wizard
 
64
        wiz_obj = self.pool.get('analytic.distribution.wizard')
 
65
        wiz_id = wiz_obj.create(cr, uid, vals, context=context)
 
66
        # Update some context values
 
67
        context.update({
 
68
            'active_id': ids[0],
 
69
            'active_ids': ids,
 
70
        })
 
71
        # Open it!
 
72
        return {
 
73
                'type': 'ir.actions.act_window',
 
74
                'res_model': 'analytic.distribution.wizard',
 
75
                'view_type': 'form',
 
76
                'view_mode': 'form',
 
77
                'target': 'new',
 
78
                'res_id': [wiz_id],
 
79
                'context': context,
 
80
        }
 
81
    
 
82
account_model_line()
 
83
 
 
84
class account_model(osv.osv):
 
85
    _name = "account.model"
 
86
    _inherit = "account.model"
 
87
    
 
88
    # @@@override@account.account_model.generate()
 
89
    def generate(self, cr, uid, ids, datas={}, context=None):
 
90
        move_ids = []
 
91
        entry = {}
 
92
        account_move_obj = self.pool.get('account.move')
 
93
        account_move_line_obj = self.pool.get('account.move.line')
 
94
        pt_obj = self.pool.get('account.payment.term')
 
95
        ana_obj = self.pool.get('analytic.distribution')
 
96
 
 
97
        if context is None:
 
98
            context = {}
 
99
 
 
100
        if datas.get('date', False):
 
101
            context.update({'date': datas['date']})
 
102
 
 
103
        period_id = self.pool.get('account.period').find(cr, uid, dt=context.get('date', False))
 
104
        if not period_id:
 
105
            raise osv.except_osv(_('No period found !'), _('Unable to find a valid period !'))
 
106
        period_id = period_id[0]
 
107
 
 
108
        for model in self.browse(cr, uid, ids, context=context):
 
109
            entry['name'] = model.name%{'year':time.strftime('%Y'), 'month':time.strftime('%m'), 'date':time.strftime('%Y-%m')}
 
110
            move_id = account_move_obj.create(cr, uid, {
 
111
                'ref': entry['name'],
 
112
                'period_id': period_id,
 
113
                'journal_id': model.journal_id.id,
 
114
                'date': context.get('date',time.strftime('%Y-%m-%d'))
 
115
            })
 
116
            move_ids.append(move_id)
 
117
            for line in model.lines_id:
 
118
                val = {
 
119
                    'move_id': move_id,
 
120
                    'journal_id': model.journal_id.id,
 
121
                    'period_id': period_id,
 
122
                }
 
123
                if line.account_id.user_type_code == 'expense':
 
124
                    if not line.analytic_distribution_id:
 
125
                        raise osv.except_osv(_('No Analytic Distribution !'),_("You have to define an analytic distribution on the '%s' line!") % (line.name))
 
126
                    if not model.journal_id.analytic_journal_id:
 
127
                        raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (model.journal_id.name,))
 
128
                    new_distribution_id = ana_obj.copy(cr, uid, line.analytic_distribution_id.id, {}, context=context)
 
129
                    val.update({'analytic_distribution_id': new_distribution_id})
 
130
                    
 
131
                date_maturity = time.strftime('%Y-%m-%d')
 
132
                if line.date_maturity == 'partner':
 
133
                    if not line.partner_id:
 
134
                        raise osv.except_osv(_('Error !'), _("Maturity date of entry line generated by model line '%s' of model '%s' is based on partner payment term!" \
 
135
                                                                "\nPlease define partner on it!")%(line.name, model.name))
 
136
                    if line.partner_id.property_payment_term:
 
137
                        payment_term_id = line.partner_id.property_payment_term.id
 
138
                        pterm_list = pt_obj.compute(cr, uid, payment_term_id, value=1, date_ref=date_maturity)
 
139
                        if pterm_list:
 
140
                            pterm_list = [l[0] for l in pterm_list]
 
141
                            pterm_list.sort()
 
142
                            date_maturity = pterm_list[-1]
 
143
 
 
144
                val.update({
 
145
                    'name': line.name,
 
146
                    'quantity': line.quantity,
 
147
                    'debit': line.debit,
 
148
                    'credit': line.credit,
 
149
                    'account_id': line.account_id.id,
 
150
                    'move_id': move_id,
 
151
                    'partner_id': line.partner_id.id,
 
152
                    'date': context.get('date',time.strftime('%Y-%m-%d')),
 
153
                    'date_maturity': date_maturity
 
154
                })
 
155
                c = context.copy()
 
156
                c.update({'journal_id': model.journal_id.id,'period_id': period_id})
 
157
                account_move_line_obj.create(cr, uid, val, context=c)
 
158
 
 
159
        return move_ids
 
160
 
 
161
account_model()
 
162
 
 
163
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: