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