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.osv import fields, osv
27 class account_fiscal_position(osv.osv):
28 _name = 'account.fiscal.position'
29 _description = 'Fiscal Position'
31 'name': fields.char('Fiscal Position', size=64, required=True),
32 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a fiscal position without deleting it."),
33 'company_id': fields.many2one('res.company', 'Company'),
34 'account_ids': fields.one2many('account.fiscal.position.account', 'position_id', 'Account Mapping'),
35 'tax_ids': fields.one2many('account.fiscal.position.tax', 'position_id', 'Tax Mapping'),
36 'note': fields.text('Notes', translate=True),
43 def map_tax(self, cr, uid, fposition_id, taxes, context=None):
47 return map(lambda x: x.id, taxes)
51 for tax in fposition_id.tax_ids:
52 if tax.tax_src_id.id == t.id:
54 result.add(tax.tax_dest_id.id)
60 def map_account(self, cr, uid, fposition_id, account_id, context=None):
63 for pos in fposition_id.account_ids:
64 if pos.account_src_id.id == account_id:
65 account_id = pos.account_dest_id.id
70 class account_fiscal_position_tax(osv.osv):
71 _name = 'account.fiscal.position.tax'
72 _description = 'Taxes Fiscal Position'
73 _rec_name = 'position_id'
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')
82 'unique (position_id,tax_src_id,tax_dest_id)',
83 'A tax fiscal position could be defined only once time on same taxes.')
87 class account_fiscal_position_account(osv.osv):
88 _name = 'account.fiscal.position.account'
89 _description = 'Accounts Fiscal Position'
90 _rec_name = 'position_id'
92 'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
93 'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type','<>','view')], required=True),
94 'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type','<>','view')], required=True)
98 ('account_src_dest_uniq',
99 'unique (position_id,account_src_id,account_dest_id)',
100 'An account fiscal position could be defined only once time on same accounts.')
104 class res_partner(osv.osv):
105 _name = 'res.partner'
106 _inherit = 'res.partner'
107 _description = 'Partner'
109 def _credit_debit_get(self, cr, uid, ids, field_names, arg, context=None):
111 ctx['all_fiscalyear'] = True
112 query = self.pool.get('account.move.line')._query_get(cr, uid, context=ctx)
113 cr.execute("""SELECT l.partner_id, a.type, SUM(l.debit-l.credit)
114 FROM account_move_line l
115 LEFT JOIN account_account a ON (l.account_id=a.id)
116 WHERE a.type IN ('receivable','payable')
117 AND l.partner_id IN %s
118 AND l.reconcile_id IS NULL
119 AND """ + query + """
120 GROUP BY l.partner_id, a.type
123 maps = {'receivable':'credit', 'payable':'debit' }
126 res[id] = {}.fromkeys(field_names, 0)
127 for pid,type,val in cr.fetchall():
128 if val is None: val=0
129 res[pid][maps[type]] = (type=='receivable') and val or -val
132 def _asset_difference_search(self, cr, uid, obj, name, type, args, context=None):
135 having_values = tuple(map(itemgetter(2), args))
136 where = ' AND '.join(
137 map(lambda x: '(SUM(bal2) %(operator)s %%s)' % {
138 'operator':x[1]},args))
139 query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
140 cr.execute(('SELECT pid AS partner_id, SUM(bal2) FROM ' \
141 '(SELECT CASE WHEN bal IS NOT NULL THEN bal ' \
142 'ELSE 0.0 END AS bal2, p.id as pid FROM ' \
143 '(SELECT (debit-credit) AS bal, partner_id ' \
144 'FROM account_move_line l ' \
145 'WHERE account_id IN ' \
146 '(SELECT id FROM account_account '\
147 'WHERE type=%s AND active) ' \
148 'AND reconcile_id IS NULL ' \
149 'AND '+query+') AS l ' \
150 'RIGHT JOIN res_partner p ' \
151 'ON p.id = partner_id ) AS pl ' \
152 'GROUP BY pid HAVING ' + where),
153 (type,) + having_values)
156 return [('id','=','0')]
157 return [('id','in',map(itemgetter(0), res))]
159 def _credit_search(self, cr, uid, obj, name, args, context=None):
160 return self._asset_difference_search(cr, uid, obj, name, 'receivable', args, context=context)
162 def _debit_search(self, cr, uid, obj, name, args, context=None):
163 return self._asset_difference_search(cr, uid, obj, name, 'payable', args, context=context)
165 def _invoice_total(self, cr, uid, ids, field_name, arg, context=None):
167 account_invoice_report = self.pool.get('account.invoice.report')
168 for partner in self.browse(cr, uid, ids, context=context):
169 invoice_ids = account_invoice_report.search(cr, uid, [('partner_id','child_of',partner.id)], context=context)
170 invoices = account_invoice_report.browse(cr, uid, invoice_ids, context=context)
171 result[partner.id] = sum(inv.user_currency_price_total for inv in invoices)
174 def _journal_item_count(self, cr, uid, ids, field_name, arg, context=None):
175 res = dict(map(lambda x: (x,{'journal_item_count': 0, 'contracts_count': 0 }), ids))
177 # the user may not have access rights
179 for partner in self.browse(cr, uid, ids, context=context):
181 'journal_item_count': len(partner.journal_item_ids),
182 'contracts_count': len(partner.contract_ids)
188 def has_something_to_reconcile(self, cr, uid, partner_id, context=None):
190 at least a debit, a credit and a line older than the last reconciliation date of the partner
193 SELECT l.partner_id, SUM(l.debit) AS debit, SUM(l.credit) AS credit
194 FROM account_move_line l
195 RIGHT JOIN account_account a ON (a.id = l.account_id)
196 RIGHT JOIN res_partner p ON (l.partner_id = p.id)
197 WHERE a.reconcile IS TRUE
199 AND l.reconcile_id IS NULL
200 AND (p.last_reconciliation_date IS NULL OR l.date > p.last_reconciliation_date)
201 AND l.state <> 'draft'
202 GROUP BY l.partner_id''', (partner_id,))
203 res = cr.dictfetchone()
205 return bool(res['debit'] and res['credit'])
208 def mark_as_reconciled(self, cr, uid, ids, context=None):
209 return self.write(cr, uid, ids, {'last_reconciliation_date': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
212 'credit': fields.function(_credit_debit_get,
213 fnct_search=_credit_search, string='Total Receivable', multi='dc', help="Total amount this customer owes you."),
214 '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."),
215 'debit_limit': fields.float('Payable Limit'),
216 'total_invoiced': fields.function(_invoice_total, string="Total Invoiced", type='float'),
217 'contracts_count': fields.function(_journal_item_count, string="Contracts", type='integer', multi="invoice_journal"),
218 'journal_item_ids': fields.one2many('account.move.line', 'partner_id', 'Journal Items'),
219 'journal_item_count': fields.function(_journal_item_count, string="Journal Items", type="integer", multi="invoice_journal"),
220 'property_account_payable': fields.property(
222 relation='account.account',
223 string="Account Payable",
224 domain="[('type', '=', 'payable')]",
225 help="This account will be used instead of the default one as the payable account for the current partner",
227 'property_account_receivable': fields.property(
229 relation='account.account',
230 string="Account Receivable",
231 domain="[('type', '=', 'receivable')]",
232 help="This account will be used instead of the default one as the receivable account for the current partner",
234 'property_account_position': fields.property(
236 relation='account.fiscal.position',
237 string="Fiscal Position",
238 help="The fiscal position will determine taxes and accounts used for the partner.",
240 'property_payment_term': fields.property(
242 relation='account.payment.term',
243 string ='Customer Payment Term',
244 help="This payment term will be used instead of the default one for sale orders and customer invoices"),
245 'property_supplier_payment_term': fields.property(
247 relation='account.payment.term',
248 string ='Supplier Payment Term',
249 help="This payment term will be used instead of the default one for purchase orders and supplier invoices"),
250 'ref_companies': fields.one2many('res.company', 'partner_id',
251 'Companies that refers to partner'),
252 'last_reconciliation_date': fields.datetime('Latest Full Reconciliation Date', help='Date on which the partner accounting entries were fully reconciled last time. It differs from the last date where a reconciliation has been made for this partner, as here we depict the fact that nothing more was to be reconciled at this date. This can be achieved in 2 different ways: either the last unreconciled debit/credit entry of this partner was reconciled, either the user pressed the button "Nothing more to reconcile" during the manual reconciliation process.')
255 def _commercial_fields(self, cr, uid, context=None):
256 return super(res_partner, self)._commercial_fields(cr, uid, context=context) + \
257 ['debit_limit', 'property_account_payable', 'property_account_receivable', 'property_account_position',
258 'property_payment_term', 'property_supplier_payment_term', 'last_reconciliation_date']
261 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: