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