b402a33ed117c7433007adbb132ef7761e394bef
[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 import time
24
25 from openerp.osv import fields, osv
26 from openerp import api
27
28 class account_fiscal_position(osv.osv):
29     _name = 'account.fiscal.position'
30     _description = 'Fiscal Position'
31     _order = 'sequence'
32     _columns = {
33         'sequence': fields.integer('Sequence'),
34         'name': fields.char('Fiscal Position', required=True),
35         'active': fields.boolean('Active', help="By unchecking the active field, you may hide a fiscal position without deleting it."),
36         'company_id': fields.many2one('res.company', 'Company'),
37         'account_ids': fields.one2many('account.fiscal.position.account', 'position_id', 'Account Mapping', copy=True),
38         'tax_ids': fields.one2many('account.fiscal.position.tax', 'position_id', 'Tax Mapping', copy=True),
39         'note': fields.text('Notes'),
40         'auto_apply': fields.boolean('Automatic', help="Apply automatically this fiscal position."),
41         'vat_required': fields.boolean('VAT required', help="Apply only if partner has a VAT number."),
42         'country_id': fields.many2one('res.country', 'Countries', help="Apply only if delivery or invoicing country match."),
43         'country_group_id': fields.many2one('res.country.group', 'Country Group', help="Apply only if delivery or invocing country match the group."),
44     }
45
46     _defaults = {
47         'active': True,
48     }
49
50     def _check_country(self, cr, uid, ids, context=None):
51         obj = self.browse(cr, uid, ids[0], context=context)
52         if obj.country_id and obj.country_group_id:
53             return False
54         return True
55
56     _constraints = [
57         (_check_country, 'You can not select a country and a group of countries', ['country_id', 'country_group_id']),
58     ]
59
60     @api.v7
61     def map_tax(self, cr, uid, fposition_id, taxes, context=None):
62         if not taxes:
63             return []
64         if not fposition_id:
65             return map(lambda x: x.id, taxes)
66         result = set()
67         for t in taxes:
68             ok = False
69             for tax in fposition_id.tax_ids:
70                 if tax.tax_src_id.id == t.id:
71                     if tax.tax_dest_id:
72                         result.add(tax.tax_dest_id.id)
73                     ok=True
74             if not ok:
75                 result.add(t.id)
76         return list(result)
77
78     @api.v8     # noqa
79     def map_tax(self, taxes):
80         result = self.env['account.tax'].browse()
81         for tax in taxes:
82             for t in self.tax_ids:
83                 if t.tax_src_id == tax:
84                     if t.tax_dest_id:
85                         result |= t.tax_dest_id
86                     break
87             else:
88                 result |= tax
89         return result
90
91     @api.v7
92     def map_account(self, cr, uid, fposition_id, account_id, context=None):
93         if not fposition_id:
94             return account_id
95         for pos in fposition_id.account_ids:
96             if pos.account_src_id.id == account_id:
97                 account_id = pos.account_dest_id.id
98                 break
99         return account_id
100
101     @api.v8
102     def map_account(self, account):
103         for pos in self.account_ids:
104             if pos.account_src_id == account:
105                 return pos.account_dest_id
106         return account
107
108     def get_fiscal_position(self, cr, uid, company_id, partner_id, delivery_id=None, context=None):
109         if not partner_id:
110             return False
111         # This can be easily overriden to apply more complex fiscal rules
112         part_obj = self.pool['res.partner']
113         partner = part_obj.browse(cr, uid, partner_id, context=context)
114
115         # partner manually set fiscal position always win
116         if partner.property_account_position:
117             return partner.property_account_position.id
118
119         # if no delivery use invocing
120         if delivery_id:
121             delivery = part_obj.browse(cr, uid, delivery_id, context=context)
122         else:
123             delivery = partner
124
125         domain = [
126             ('auto_apply', '=', True),
127             '|', ('vat_required', '=', False), ('vat_required', '=', partner.vat_subjected),
128         ]
129
130         fiscal_position_ids = self.search(cr, uid, domain + [('country_id', '=', delivery.country_id.id)], context=context, limit=1)
131         if fiscal_position_ids:
132             return fiscal_position_ids[0]
133
134         fiscal_position_ids = self.search(cr, uid, domain + [('country_group_id.country_ids', '=', delivery.country_id.id)], context=context, limit=1)
135         if fiscal_position_ids:
136             return fiscal_position_ids[0]
137
138         fiscal_position_ids = self.search(cr, uid, domain + [('country_id', '=', None), ('country_group_id', '=', None)], context=context, limit=1)
139         if fiscal_position_ids:
140             return fiscal_position_ids[0]
141         return False
142
143 class account_fiscal_position_tax(osv.osv):
144     _name = 'account.fiscal.position.tax'
145     _description = 'Taxes Fiscal Position'
146     _rec_name = 'position_id'
147     _columns = {
148         'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
149         'tax_src_id': fields.many2one('account.tax', 'Tax Source', required=True),
150         'tax_dest_id': fields.many2one('account.tax', 'Replacement Tax')
151     }
152
153     _sql_constraints = [
154         ('tax_src_dest_uniq',
155          'unique (position_id,tax_src_id,tax_dest_id)',
156          'A tax fiscal position could be defined only once time on same taxes.')
157     ]
158
159
160 class account_fiscal_position_account(osv.osv):
161     _name = 'account.fiscal.position.account'
162     _description = 'Accounts Fiscal Position'
163     _rec_name = 'position_id'
164     _columns = {
165         'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
166         'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type','<>','view')], required=True),
167         'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type','<>','view')], required=True)
168     }
169
170     _sql_constraints = [
171         ('account_src_dest_uniq',
172          'unique (position_id,account_src_id,account_dest_id)',
173          'An account fiscal position could be defined only once time on same accounts.')
174     ]
175
176
177 class res_partner(osv.osv):
178     _name = 'res.partner'
179     _inherit = 'res.partner'
180     _description = 'Partner'
181
182     def _credit_debit_get(self, cr, uid, ids, field_names, arg, context=None):
183         ctx = context.copy()
184         ctx['all_fiscalyear'] = True
185         query = self.pool.get('account.move.line')._query_get(cr, uid, context=ctx)
186         cr.execute("""SELECT l.partner_id, a.type, SUM(l.debit-l.credit)
187                       FROM account_move_line l
188                       LEFT JOIN account_account a ON (l.account_id=a.id)
189                       WHERE a.type IN ('receivable','payable')
190                       AND l.partner_id IN %s
191                       AND l.reconcile_id IS NULL
192                       AND """ + query + """
193                       GROUP BY l.partner_id, a.type
194                       """,
195                    (tuple(ids),))
196         maps = {'receivable':'credit', 'payable':'debit' }
197         res = {}
198         for id in ids:
199             res[id] = {}.fromkeys(field_names, 0)
200         for pid,type,val in cr.fetchall():
201             if val is None: val=0
202             res[pid][maps[type]] = (type=='receivable') and val or -val
203         return res
204
205     def _asset_difference_search(self, cr, uid, obj, name, type, args, context=None):
206         if not args:
207             return []
208         having_values = tuple(map(itemgetter(2), args))
209         where = ' AND '.join(
210             map(lambda x: '(SUM(bal2) %(operator)s %%s)' % {
211                                 'operator':x[1]},args))
212         query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
213         cr.execute(('SELECT pid AS partner_id, SUM(bal2) FROM ' \
214                     '(SELECT CASE WHEN bal IS NOT NULL THEN bal ' \
215                     'ELSE 0.0 END AS bal2, p.id as pid FROM ' \
216                     '(SELECT (debit-credit) AS bal, partner_id ' \
217                     'FROM account_move_line l ' \
218                     'WHERE account_id IN ' \
219                             '(SELECT id FROM account_account '\
220                             'WHERE type=%s AND active) ' \
221                     'AND reconcile_id IS NULL ' \
222                     'AND '+query+') AS l ' \
223                     'RIGHT JOIN res_partner p ' \
224                     'ON p.id = partner_id ) AS pl ' \
225                     'GROUP BY pid HAVING ' + where), 
226                     (type,) + having_values)
227         res = cr.fetchall()
228         if not res:
229             return [('id','=','0')]
230         return [('id','in',map(itemgetter(0), res))]
231
232     def _credit_search(self, cr, uid, obj, name, args, context=None):
233         return self._asset_difference_search(cr, uid, obj, name, 'receivable', args, context=context)
234
235     def _debit_search(self, cr, uid, obj, name, args, context=None):
236         return self._asset_difference_search(cr, uid, obj, name, 'payable', args, context=context)
237
238     def _invoice_total(self, cr, uid, ids, field_name, arg, context=None):
239         result = {}
240         account_invoice_report = self.pool.get('account.invoice.report')
241         for partner in self.browse(cr, uid, ids, context=context):
242             domain = [('partner_id', 'child_of', partner.id)]
243             invoice_ids = account_invoice_report.search(cr, uid, domain, context=context)
244             invoices = account_invoice_report.browse(cr, uid, invoice_ids, context=context)
245             result[partner.id] = sum(inv.user_currency_price_total for inv in invoices)
246         return result
247
248     def _journal_item_count(self, cr, uid, ids, field_name, arg, context=None):
249         MoveLine = self.pool('account.move.line')
250         AnalyticAccount = self.pool('account.analytic.account')
251         return {
252             partner_id: {
253                 'journal_item_count': MoveLine.search_count(cr, uid, [('partner_id', '=', partner_id)], context=context),
254                 'contracts_count': AnalyticAccount.search_count(cr,uid, [('partner_id', '=', partner_id)], context=context)
255             }
256             for partner_id in ids
257         }
258
259     def has_something_to_reconcile(self, cr, uid, partner_id, context=None):
260         '''
261         at least a debit, a credit and a line older than the last reconciliation date of the partner
262         '''
263         cr.execute('''
264             SELECT l.partner_id, SUM(l.debit) AS debit, SUM(l.credit) AS credit
265             FROM account_move_line l
266             RIGHT JOIN account_account a ON (a.id = l.account_id)
267             RIGHT JOIN res_partner p ON (l.partner_id = p.id)
268             WHERE a.reconcile IS TRUE
269             AND p.id = %s
270             AND l.reconcile_id IS NULL
271             AND (p.last_reconciliation_date IS NULL OR l.date > p.last_reconciliation_date)
272             AND l.state <> 'draft'
273             GROUP BY l.partner_id''', (partner_id,))
274         res = cr.dictfetchone()
275         if res:
276             return bool(res['debit'] and res['credit'])
277         return False
278
279     def mark_as_reconciled(self, cr, uid, ids, context=None):
280         return self.write(cr, uid, ids, {'last_reconciliation_date': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
281
282     _columns = {
283         'vat_subjected': fields.boolean('VAT Legal Statement', help="Check this box if the partner is subjected to the VAT. It will be used for the VAT legal statement."),
284         'credit': fields.function(_credit_debit_get,
285             fnct_search=_credit_search, string='Total Receivable', multi='dc', help="Total amount this customer owes you."),
286         '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."),
287         'debit_limit': fields.float('Payable Limit'),
288         'total_invoiced': fields.function(_invoice_total, string="Total Invoiced", type='float', groups='account.group_account_invoice'),
289
290         'contracts_count': fields.function(_journal_item_count, string="Contracts", type='integer', multi="invoice_journal"),
291         'journal_item_count': fields.function(_journal_item_count, string="Journal Items", type="integer", multi="invoice_journal"),
292         'property_account_payable': fields.property(
293             type='many2one',
294             relation='account.account',
295             string="Account Payable",
296             domain="[('type', '=', 'payable')]",
297             help="This account will be used instead of the default one as the payable account for the current partner",
298             required=True),
299         'property_account_receivable': fields.property(
300             type='many2one',
301             relation='account.account',
302             string="Account Receivable",
303             domain="[('type', '=', 'receivable')]",
304             help="This account will be used instead of the default one as the receivable account for the current partner",
305             required=True),
306         'property_account_position': fields.property(
307             type='many2one',
308             relation='account.fiscal.position',
309             string="Fiscal Position",
310             help="The fiscal position will determine taxes and accounts used for the partner.",
311         ),
312         'property_payment_term': fields.property(
313             type='many2one',
314             relation='account.payment.term',
315             string ='Customer Payment Term',
316             help="This payment term will be used instead of the default one for sale orders and customer invoices"),
317         'property_supplier_payment_term': fields.property(
318              type='many2one',
319              relation='account.payment.term',
320              string ='Supplier Payment Term',
321              help="This payment term will be used instead of the default one for purchase orders and supplier invoices"),
322         'ref_companies': fields.one2many('res.company', 'partner_id',
323             'Companies that refers to partner'),
324         'last_reconciliation_date': fields.datetime(
325             'Latest Full Reconciliation Date', copy=False,
326             help='Date on which the partner accounting entries were fully reconciled last time. '
327                  'It differs from the last date where a reconciliation has been made for this partner, '
328                  'as here we depict the fact that nothing more was to be reconciled at this date. '
329                  'This can be achieved in 2 different ways: either the last unreconciled debit/credit '
330                  'entry of this partner was reconciled, either the user pressed the button '
331                  '"Nothing more to reconcile" during the manual reconciliation process.')
332     }
333
334     def _commercial_fields(self, cr, uid, context=None):
335         return super(res_partner, self)._commercial_fields(cr, uid, context=context) + \
336             ['debit_limit', 'property_account_payable', 'property_account_receivable', 'property_account_position',
337              'property_payment_term', 'property_supplier_payment_term', 'last_reconciliation_date']
338
339
340 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: