[MERGE] lp:~xrg/openobject-addons/trunk-patch18
[odoo/odoo.git] / addons / account / partner.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 operator import itemgetter
23
24 from osv import fields, osv
25
26 class account_fiscal_position(osv.osv):
27     _name = 'account.fiscal.position'
28     _description = 'Fiscal Position'
29     _columns = {
30         'name': fields.char('Fiscal Position', size=64, translate=True, required=True),
31         'company_id': fields.many2one('res.company', 'Company'),
32         'account_ids': fields.one2many('account.fiscal.position.account', 'position_id', 'Account Mapping'),
33         'tax_ids': fields.one2many('account.fiscal.position.tax', 'position_id', 'Tax Mapping'),
34         'note': fields.text('Notes', translate=True),
35     }
36
37     def map_tax(self, cr, uid, fposition_id, taxes, context=None):
38         if not taxes:
39             return []
40         if not fposition_id:
41             return map(lambda x: x.id, taxes)
42         result = []
43         for t in taxes:
44             ok = False
45             for tax in fposition_id.tax_ids:
46                 if tax.tax_src_id.id == t.id:
47                     if tax.tax_dest_id:
48                         result.append(tax.tax_dest_id.id)
49                     ok=True
50             if not ok:
51                 result.append(t.id)
52         return result
53
54     def map_account(self, cr, uid, fposition_id, account_id, context=None):
55         if not fposition_id:
56             return account_id
57         for pos in fposition_id.account_ids:
58             if pos.account_src_id.id == account_id:
59                 account_id = pos.account_dest_id.id
60                 break
61         return account_id
62
63 account_fiscal_position()
64
65 class account_fiscal_position_tax(osv.osv):
66     _name = 'account.fiscal.position.tax'
67     _description = 'Taxes Fiscal Position'
68     _rec_name = 'position_id'
69     _columns = {
70         'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
71         'tax_src_id': fields.many2one('account.tax', 'Tax Source', required=True),
72         'tax_dest_id': fields.many2one('account.tax', 'Replacement Tax')
73     }
74
75 account_fiscal_position_tax()
76
77 class account_fiscal_position_account(osv.osv):
78     _name = 'account.fiscal.position.account'
79     _description = 'Accounts Fiscal Position'
80     _rec_name = 'position_id'
81     _columns = {
82         'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
83         'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type','<>','view')], required=True),
84         'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type','<>','view')], required=True)
85     }
86
87 account_fiscal_position_account()
88
89 class res_partner(osv.osv):
90     _name = 'res.partner'
91     _inherit = 'res.partner'
92     _description = 'Partner'
93
94     def _credit_debit_get(self, cr, uid, ids, field_names, arg, context=None):
95         query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
96         cr.execute("""SELECT l.partner_id, a.type, SUM(l.debit-l.credit)
97                       FROM account_move_line l
98                       LEFT JOIN account_account a ON (l.account_id=a.id)
99                       WHERE a.type IN ('receivable','payable')
100                       AND l.partner_id IN %s
101                       AND l.reconcile_id IS NULL
102                       AND """ + query + """
103                       GROUP BY l.partner_id, a.type
104                       """,
105                    (tuple(ids),))
106         maps = {'receivable':'credit', 'payable':'debit' }
107         res = {}
108         for id in ids:
109             res[id] = {}.fromkeys(field_names, 0)
110         for pid,type,val in cr.fetchall():
111             if val is None: val=0
112             res[pid][maps[type]] = (type=='receivable') and val or -val
113         return res
114
115     def _asset_difference_search(self, cr, uid, obj, name, type, args, context=None):
116         if not args:
117             return []
118         having_values = tuple(map(itemgetter(2), args))
119         where = ' AND '.join(
120             map(lambda x: '(SUM(debit-credit) %(operator)s %%s)' % {
121                                 'operator':x[1]},args))
122         query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
123         cr.execute(('SELECT partner_id FROM account_move_line l '\
124                     'WHERE account_id IN '\
125                         '(SELECT id FROM account_account '\
126                         'WHERE type=%s AND active) '\
127                     'AND reconcile_id IS NULL '\
128                     'AND '+query+' '\
129                     'AND partner_id IS NOT NULL '\
130                     'GROUP BY partner_id HAVING '+where),
131                    (type,) + having_values)
132         res = cr.fetchall()
133         if not res:
134             return [('id','=','0')]
135         return [('id','in',map(itemgetter(0), res))]
136
137     def _credit_search(self, cr, uid, obj, name, args, context=None):
138         return self._asset_difference_search(cr, uid, obj, name, 'receivable', args, context=context)
139
140     def _debit_search(self, cr, uid, obj, name, args, context=None):
141         return self._asset_difference_search(cr, uid, obj, name, 'payable', args, context=context)
142
143     _columns = {
144         'credit': fields.function(_credit_debit_get,
145             fnct_search=_credit_search, method=True, string='Total Receivable', multi='dc', help="Total amount this customer owes you."),
146         'debit': fields.function(_credit_debit_get, fnct_search=_debit_search, method=True, string='Total Payable', multi='dc', help="Total amount you have to pay to this supplier."),
147         'debit_limit': fields.float('Payable Limit'),
148         'property_account_payable': fields.property(
149             'account.account',
150             type='many2one',
151             relation='account.account',
152             string="Account Payable",
153             method=True,
154             view_load=True,
155             domain="[('type', '=', 'payable')]",
156             help="This account will be used instead of the default one as the payable account for the current partner",
157             required=True),
158         'property_account_receivable': fields.property(
159             'account.account',
160             type='many2one',
161             relation='account.account',
162             string="Account Receivable",
163             method=True,
164             view_load=True,
165             domain="[('type', '=', 'receivable')]",
166             help="This account will be used instead of the default one as the receivable account for the current partner",
167             required=True),
168         'property_account_position': fields.property(
169             'account.fiscal.position',
170             type='many2one',
171             relation='account.fiscal.position',
172             string="Fiscal Position",
173             method=True,
174             view_load=True,
175             help="The fiscal position will determine taxes and the accounts used for the partner.",
176         ),
177         'property_payment_term': fields.property(
178             'account.payment.term',
179             type='many2one',
180             relation='account.payment.term',
181             string ='Payment Term',
182             method=True,
183             view_load=True,
184             help="This payment term will be used instead of the default one for the current partner"),
185         'ref_companies': fields.one2many('res.company', 'partner_id',
186             'Companies that refers to partner'),
187         'last_reconciliation_date': fields.datetime('Latest Reconciliation Date', help='Date on which the partner accounting entries were reconciled last time')
188     }
189
190 res_partner()
191
192 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: