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