1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from operator import itemgetter
25 from openerp import SUPERUSER_ID
26 from openerp.osv import fields, osv
27 from openerp import api
29 class account_fiscal_position(osv.osv):
30 _name = 'account.fiscal.position'
31 _description = 'Fiscal Position'
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."),
52 def map_tax(self, cr, uid, fposition_id, taxes, context=None):
56 return map(lambda x: x.id, taxes)
60 for tax in fposition_id.tax_ids:
61 if tax.tax_src_id.id == t.id:
63 result.add(tax.tax_dest_id.id)
70 def map_tax(self, taxes):
71 result = taxes.browse()
74 for t in self.tax_ids:
75 if t.tax_src_id == tax:
76 result |= t.tax_dest_id
83 def map_account(self, cr, uid, fposition_id, account_id, context=None):
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
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
99 def get_fiscal_position(self, cr, uid, company_id, partner_id, delivery_id=None, context=None):
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)
106 # partner manually set fiscal position always win
107 if partner.property_account_position:
108 return partner.property_account_position.id
110 # if no delivery use invocing
112 delivery = part_obj.browse(cr, uid, delivery_id, context=context)
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)
122 fiscal_position_ids = self.search(cr, uid, domain, context=context)
123 if fiscal_position_ids:
124 return fiscal_position_ids[0]
127 class account_fiscal_position_tax(osv.osv):
128 _name = 'account.fiscal.position.tax'
129 _description = 'Taxes Fiscal Position'
130 _rec_name = 'position_id'
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')
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.')
144 class account_fiscal_position_account(osv.osv):
145 _name = 'account.fiscal.position.account'
146 _description = 'Accounts Fiscal Position'
147 _rec_name = 'position_id'
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)
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.')
161 class res_partner(osv.osv):
162 _name = 'res.partner'
163 _inherit = 'res.partner'
164 _description = 'Partner'
166 def _credit_debit_get(self, cr, uid, ids, field_names, arg, context=None):
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
180 maps = {'receivable':'credit', 'payable':'debit' }
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
189 def _asset_difference_search(self, cr, uid, obj, name, type, args, context=None):
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)
213 return [('id','=','0')]
214 return [('id','in',map(itemgetter(0), res))]
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)
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)
222 def _invoice_total(self, cr, uid, ids, field_name, arg, context=None):
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)
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')
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)
240 for partner_id in ids
243 def has_something_to_reconcile(self, cr, uid, partner_id, context=None):
245 at least a debit, a credit and a line older than the last reconciliation date of the partner
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
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()
260 return bool(res['debit'] and res['credit'])
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)
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'),
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(
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",
283 'property_account_receivable': fields.property(
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",
290 'property_account_position': fields.property(
292 relation='account.fiscal.position',
293 string="Fiscal Position",
294 help="The fiscal position will determine taxes and accounts used for the partner.",
296 'property_payment_term': fields.property(
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(
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.')
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']
324 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: