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 ##############################################################################
23 from lxml import etree
26 from osv import osv, fields
27 import decimal_precision as dp
28 from tools.translate import _
31 class account_voucher(osv.osv):
33 def _get_type(self, cr, uid, context=None):
36 return context.get('type', False)
38 def _get_period(self, cr, uid, context=None):
39 if context is None: context = {}
40 if context.get('period_id', False):
41 return context.get('period_id')
42 periods = self.pool.get('account.period').find(cr, uid)
43 return periods and periods[0] or False
45 def _get_journal(self, cr, uid, context=None):
46 if context is None: context = {}
47 journal_pool = self.pool.get('account.journal')
48 invoice_pool = self.pool.get('account.invoice')
49 if context.get('invoice_id', False):
50 currency_id = invoice_pool.browse(cr, uid, context['invoice_id'], context=context).currency_id.id
51 journal_id = journal_pool.search(cr, uid, [('currency', '=', currency_id)], limit=1)
52 return journal_id and journal_id[0] or False
53 if context.get('journal_id', False):
54 return context.get('journal_id')
55 if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
56 return context.get('search_default_journal_id')
58 ttype = context.get('type', 'bank')
59 if ttype in ('payment', 'receipt'):
61 res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
62 return res and res[0] or False
64 def _get_tax(self, cr, uid, context=None):
65 if context is None: context = {}
66 journal_pool = self.pool.get('account.journal')
67 journal_id = context.get('journal_id', False)
69 ttype = context.get('type', 'bank')
70 res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
77 journal = journal_pool.browse(cr, uid, journal_id, context=context)
78 account_id = journal.default_credit_account_id or journal.default_debit_account_id
79 if account_id and account_id.tax_ids:
80 tax_id = account_id.tax_ids[0].id
84 def _get_currency(self, cr, uid, context=None):
85 if context is None: context = {}
86 journal_pool = self.pool.get('account.journal')
87 journal_id = context.get('journal_id', False)
89 journal = journal_pool.browse(cr, uid, journal_id, context=context)
90 # currency_id = journal.company_id.currency_id.id
92 return journal.currency.id
95 def _get_partner(self, cr, uid, context=None):
96 if context is None: context = {}
97 return context.get('partner_id', False)
99 def _get_reference(self, cr, uid, context=None):
100 if context is None: context = {}
101 return context.get('reference', False)
103 def _get_narration(self, cr, uid, context=None):
104 if context is None: context = {}
105 return context.get('narration', False)
107 def _get_amount(self, cr, uid, context=None):
110 return context.get('amount', 0.0)
112 def name_get(self, cr, uid, ids, context=None):
115 if context is None: context = {}
116 return [(r['id'], (str("%.2f" % r['amount']) or '')) for r in self.read(cr, uid, ids, ['amount'], context, load='_classic_write')]
118 def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
119 mod_obj = self.pool.get('ir.model.data')
120 if context is None: context = {}
121 if not view_id and context.get('invoice_type', False):
122 if context.get('invoice_type', False) in ('out_invoice', 'out_refund'):
123 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
125 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
126 result = result and result[1] or False
128 if not view_id and view_type == 'form' and context.get('line_type', False):
129 if context.get('line_type', False) == 'customer':
130 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
132 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
133 result = result and result[1] or False
136 res = super(account_voucher, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
137 doc = etree.XML(res['arch'])
138 nodes = doc.xpath("//field[@name='partner_id']")
139 if context.get('type', 'sale') in ('purchase', 'payment'):
141 node.set('domain', "[('supplier', '=', True)]")
142 res['arch'] = etree.tostring(doc)
145 def _compute_writeoff_amount(self, cr, uid, line_dr_ids, line_cr_ids, amount):
147 for l in line_dr_ids:
149 for l in line_cr_ids:
150 credit += l['amount']
151 return abs(amount - abs(credit - debit))
153 def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount):
154 if not line_dr_ids and not line_cr_ids:
156 line_dr_ids = [x[2] for x in line_dr_ids]
157 line_cr_ids = [x[2] for x in line_cr_ids]
158 return {'value': {'writeoff_amount': self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount)}}
160 def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
161 if not ids: return {}
164 for voucher in self.browse(cr, uid, ids, context=context):
165 for l in voucher.line_dr_ids:
167 for l in voucher.line_cr_ids:
169 res[voucher.id] = abs(voucher.amount - abs(credit - debit))
172 _name = 'account.voucher'
173 _description = 'Accounting Voucher'
174 _order = "date desc, id desc"
175 # _rec_name = 'number'
177 'type':fields.selection([
179 ('purchase','Purchase'),
180 ('payment','Payment'),
181 ('receipt','Receipt'),
182 ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
183 'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
184 'date':fields.date('Date', readonly=True, select=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
185 'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}),
186 'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
187 'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
188 'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
189 domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
190 'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
191 domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
192 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
193 'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
194 'currency_id':fields.many2one('res.currency', 'Currency', required=True, readonly=True, states={'draft':[('readonly',False)]}),
195 # 'currency_id': fields.related('journal_id','currency', type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, states={'draft':[('readonly',False)]}),
196 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft':[('readonly',False)]}),
197 'state':fields.selection(
199 ('proforma','Pro-forma'),
201 ('cancel','Cancelled')
202 ], 'State', readonly=True, size=32,
203 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
204 \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
205 \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
206 \n* The \'Cancelled\' state is used when user cancel voucher.'),
207 'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
208 'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
209 'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
210 'number': fields.char('Number', size=32, readonly=True,),
211 'move_id':fields.many2one('account.move', 'Account Entry'),
212 'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
213 'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
214 'audit': fields.related('move_id','to_check', type='boolean', help='Check this box if you are unsure of that journal entry and if you want to note it as \'to be reviewed\' by an accounting expert.', relation='account.move', string='To Review'),
215 'pay_now':fields.selection([
216 ('pay_now','Pay Directly'),
217 ('pay_later','Pay Later or Group Funds'),
218 ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
219 'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
220 'pre_line':fields.boolean('Previous Payments ?', required=False),
221 'date_due': fields.date('Due Date', readonly=True, select=True, states={'draft':[('readonly',False)]}),
222 'payment_option':fields.selection([
223 ('without_writeoff', 'Keep Open'),
224 ('with_writeoff', 'Reconcile with Write-Off'),
225 ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
226 'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
227 'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
228 'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
229 'writeoff_amount': fields.function(_get_writeoff_amount, method=True, string='Write-Off Amount', type='float', readonly=True),
232 'period_id': _get_period,
233 'partner_id': _get_partner,
234 'journal_id':_get_journal,
235 'currency_id': _get_currency,
236 'reference': _get_reference,
237 'narration':_get_narration,
238 'amount': _get_amount,
241 'pay_now': 'pay_later',
243 'date': lambda *a: time.strftime('%Y-%m-%d'),
244 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
246 'payment_option': 'without_writeoff',
247 'comment': _('Write-Off'),
250 def compute_tax(self, cr, uid, ids, context=None):
251 tax_pool = self.pool.get('account.tax')
252 partner_pool = self.pool.get('res.partner')
253 position_pool = self.pool.get('account.fiscal.position')
254 voucher_line_pool = self.pool.get('account.voucher.line')
255 voucher_pool = self.pool.get('account.voucher')
256 if context is None: context = {}
258 for voucher in voucher_pool.browse(cr, uid, ids, context=context):
260 for line in voucher.line_ids:
261 voucher_amount += line.untax_amount or line.amount
262 line.amount = line.untax_amount or line.amount
263 voucher_line_pool.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
265 if not voucher.tax_id:
266 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
269 tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
270 partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
271 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
272 tax = tax_pool.browse(cr, uid, taxes, context=context)
274 total = voucher_amount
277 if not tax[0].price_include:
278 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
279 total_tax += tax_line.get('amount', 0.0)
282 for line in voucher.line_ids:
286 for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
287 line_tax += tax_line.get('amount', 0.0)
288 line_total += tax_line.get('price_unit')
289 total_tax += line_tax
290 untax_amount = line.untax_amount or line.amount
291 voucher_line_pool.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
293 self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
296 def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
297 context = context or {}
298 tax_pool = self.pool.get('account.tax')
299 partner_pool = self.pool.get('res.partner')
300 position_pool = self.pool.get('account.fiscal.position')
301 line_pool = self.pool.get('account.voucher.line')
308 line_ids = resolve_o2m_operations(cr, uid, line_pool, line_ids, ["amount"], context)
312 for line in line_ids:
314 line_amount = line.get('amount',0.0)
315 voucher_total += line_amount
317 total = voucher_total
320 tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
322 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
323 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
324 tax = tax_pool.browse(cr, uid, taxes, context=context)
326 if not tax[0].price_include:
327 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
328 total_tax += tax_line.get('amount')
332 'amount':total or voucher_total,
333 'tax_amount':total_tax
339 def onchange_term_id(self, cr, uid, ids, term_id, amount):
340 term_pool = self.pool.get('account.payment.term')
343 default = {'date_due':False}
344 if term_id and amount:
345 terms = term_pool.compute(cr, uid, term_id, amount)
347 due_date = terms[-1][0]
351 return {'value':default}
353 def onchange_journal_voucher(self, cr, uid, ids, line_ids=False, tax_id=False, price=0.0, partner_id=False, journal_id=False, ttype=False, context=None):
355 Returns a dict that contains new values and context
357 @param partner_id: latest value from user input for field partner_id
358 @param args: other arguments
359 @param context: context arguments, like lang, time zone
361 @return: Returns a dict which contains new values, and context
367 if not partner_id or not journal_id:
370 partner_pool = self.pool.get('res.partner')
371 journal_pool = self.pool.get('account.journal')
373 journal = journal_pool.browse(cr, uid, journal_id, context=context)
374 partner = partner_pool.browse(cr, uid, partner_id, context=context)
377 if journal.type in ('sale','sale_refund'):
378 account_id = partner.property_account_receivable.id
380 elif journal.type in ('purchase', 'purchase_refund','expense'):
381 account_id = partner.property_account_payable.id
384 if not journal.default_credit_account_id or not journal.default_debit_account_id:
385 raise osv.except_osv(_('Error !'), _('Please define default credit/debit account on the %s !') % (journal.name))
386 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
389 default['value']['account_id'] = account_id
390 default['value']['type'] = ttype or tr_type
392 vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
393 default['value'].update(vals.get('value'))
397 def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
399 Returns a dict that contains new values and context
401 @param partner_id: latest value from user input for field partner_id
402 @param args: other arguments
403 @param context: context arguments, like lang, time zone
405 @return: Returns a dict which contains new values, and context
411 context_multi_currency = context.copy()
413 context_multi_currency.update({'date': date})
415 line_pool = self.pool.get('account.voucher.line')
416 line_ids = ids and line_pool.search(cr, uid, [('voucher_id', '=', ids[0])]) or False
418 line_pool.unlink(cr, uid, line_ids)
420 currency_pool = self.pool.get('res.currency')
421 move_line_pool = self.pool.get('account.move.line')
422 partner_pool = self.pool.get('res.partner')
423 journal_pool = self.pool.get('account.journal')
425 vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context)
426 vals = vals.get('value')
427 currency_id = vals.get('currency_id', currency_id)
429 'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id':currency_id},
435 if not partner_id and ids:
436 line_ids = line_pool.search(cr, uid, [('voucher_id', '=', ids[0])])
438 line_pool.unlink(cr, uid, line_ids)
441 journal = journal_pool.browse(cr, uid, journal_id, context=context)
442 partner = partner_pool.browse(cr, uid, partner_id, context=context)
444 if journal.type in ('sale','sale_refund'):
445 account_id = partner.property_account_receivable.id
446 elif journal.type in ('purchase', 'purchase_refund','expense'):
447 account_id = partner.property_account_payable.id
449 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
451 default['value']['account_id'] = account_id
453 if journal.type not in ('cash', 'bank'):
458 account_type = 'receivable'
459 if ttype == 'payment':
460 account_type = 'payable'
461 total_debit = price or 0.0
463 total_credit = price or 0.0
464 account_type = 'receivable'
466 if not context.get('move_line_ids', False):
467 ids = move_line_pool.search(cr, uid, [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)], context=context)
469 ids = context['move_line_ids']
471 moves = move_line_pool.browse(cr, uid, ids, context=context)
473 company_currency = journal.company_id.currency_id.id
474 if company_currency != currency_id and ttype == 'payment':
475 total_debit = currency_pool.compute(cr, uid, currency_id, company_currency, total_debit, context=context_multi_currency)
476 elif company_currency != currency_id and ttype == 'receipt':
477 total_credit = currency_pool.compute(cr, uid, currency_id, company_currency, total_credit, context=context_multi_currency)
480 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
482 if line.debit and line.reconcile_partial_id and ttype == 'payment':
484 total_credit += line.credit or 0.0
485 total_debit += line.debit or 0.0
487 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
489 if line.debit and line.reconcile_partial_id and ttype == 'payment':
491 original_amount = line.credit or line.debit or 0.0
492 amount_unreconciled = currency_pool.compute(cr, uid, line.currency_id and line.currency_id.id or company_currency, currency_id, abs(line.amount_residual_currency), context=context_multi_currency)
494 'name':line.move_id.name,
495 'type': line.credit and 'dr' or 'cr',
496 'move_line_id':line.id,
497 'account_id':line.account_id.id,
498 'amount_original': currency_pool.compute(cr, uid, line.currency_id and line.currency_id.id or company_currency, currency_id, line.currency_id and abs(line.amount_currency) or original_amount, context=context_multi_currency),
499 'date_original':line.date,
500 'date_due':line.date_maturity,
501 'amount_unreconciled': amount_unreconciled,
506 amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_debit), context=context_multi_currency))
507 rs['amount'] = amount
508 total_debit -= amount
510 amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_credit), context=context_multi_currency))
511 rs['amount'] = amount
512 total_credit -= amount
514 default['value']['line_ids'].append(rs)
515 if rs['type'] == 'cr':
516 default['value']['line_cr_ids'].append(rs)
518 default['value']['line_dr_ids'].append(rs)
520 if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
521 default['value']['pre_line'] = 1
522 elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
523 default['value']['pre_line'] = 1
524 default['value']['writeoff_amount'] = self._compute_writeoff_amount(cr, uid, default['value']['line_dr_ids'], default['value']['line_cr_ids'], price)
527 def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
529 @param date: latest value from user input for field date
530 @param args: other arguments
531 @param context: context arguments, like lang, time zone
532 @return: Returns a dict which contains new values, and context
534 period_pool = self.pool.get('account.period')
535 res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
536 pids = period_pool.search(cr, uid, [('date_start', '<=', date), ('date_stop', '>=', date)])
538 if not 'value' in res:
540 res['value'].update({'period_id':pids[0]})
543 def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
546 journal_pool = self.pool.get('account.journal')
547 journal = journal_pool.browse(cr, uid, journal_id, context=context)
548 account_id = journal.default_credit_account_id or journal.default_debit_account_id
550 if account_id and account_id.tax_ids:
551 tax_id = account_id.tax_ids[0].id
553 vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
554 vals['value'].update({'tax_id':tax_id})
555 currency_id = journal.company_id.currency_id.id
557 currency_id = journal.currency.id
558 vals['value'].update({'currency_id':currency_id})
561 def proforma_voucher(self, cr, uid, ids, context=None):
562 self.action_move_line_create(cr, uid, ids, context=context)
565 def action_cancel_draft(self, cr, uid, ids, context=None):
566 wf_service = netsvc.LocalService("workflow")
567 for voucher_id in ids:
568 wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
569 self.write(cr, uid, ids, {'state':'draft'})
572 def cancel_voucher(self, cr, uid, ids, context=None):
573 reconcile_pool = self.pool.get('account.move.reconcile')
574 move_pool = self.pool.get('account.move')
576 for voucher in self.browse(cr, uid, ids, context=context):
578 for line in voucher.move_ids:
579 if line.reconcile_id:
580 recs += [line.reconcile_id.id]
581 if line.reconcile_partial_id:
582 recs += [line.reconcile_partial_id.id]
584 reconcile_pool.unlink(cr, uid, recs)
587 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
588 move_pool.unlink(cr, uid, [voucher.move_id.id])
593 self.write(cr, uid, ids, res)
596 def unlink(self, cr, uid, ids, context=None):
597 for t in self.read(cr, uid, ids, ['state'], context=context):
598 if t['state'] not in ('draft', 'cancel'):
599 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
600 return super(account_voucher, self).unlink(cr, uid, ids, context=context)
602 # TODO: may be we can remove this method if not used anyware
603 def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
607 res = {'account_id':False}
608 partner_pool = self.pool.get('res.partner')
609 journal_pool = self.pool.get('account.journal')
610 if pay_now == 'pay_later':
611 partner = partner_pool.browse(cr, uid, partner_id)
612 journal = journal_pool.browse(cr, uid, journal_id)
613 if journal.type in ('sale','sale_refund'):
614 account_id = partner.property_account_receivable.id
615 elif journal.type in ('purchase', 'purchase_refund','expense'):
616 account_id = partner.property_account_payable.id
618 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
619 res['account_id'] = account_id
622 def action_move_line_create(self, cr, uid, ids, context=None):
624 def _get_payment_term_lines(term_id, amount):
625 term_pool = self.pool.get('account.payment.term')
626 if term_id and amount:
627 terms = term_pool.compute(cr, uid, term_id, amount)
632 move_pool = self.pool.get('account.move')
633 move_line_pool = self.pool.get('account.move.line')
634 currency_pool = self.pool.get('res.currency')
635 tax_obj = self.pool.get('account.tax')
636 seq_obj = self.pool.get('ir.sequence')
637 for inv in self.browse(cr, uid, ids, context=context):
640 context_multi_currency = context.copy()
641 context_multi_currency.update({'date': inv.date})
645 elif inv.journal_id.sequence_id:
646 name = seq_obj.get_id(cr, uid, inv.journal_id.sequence_id.id)
648 raise osv.except_osv(_('Error !'), _('Please define a sequence on the journal !'))
649 if not inv.reference:
650 ref = name.replace('/','')
656 'journal_id': inv.journal_id.id,
657 'narration': inv.narration,
660 'period_id': inv.period_id and inv.period_id.id or False
662 move_id = move_pool.create(cr, uid, move)
664 #create the first line manually
665 company_currency = inv.journal_id.company_id.currency_id.id
666 current_currency = inv.currency_id.id
669 # TODO: is there any other alternative then the voucher type ??
670 # -for sale, purchase we have but for the payment and receipt we do not have as based on the bank/cash journal we can not know its payment or receipt
671 if inv.type in ('purchase', 'payment'):
672 credit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
673 elif inv.type in ('sale', 'receipt'):
674 debit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
681 sign = debit - credit < 0 and -1 or 1
682 #create the first line of the voucher
684 'name': inv.name or '/',
687 'account_id': inv.account_id.id,
689 'journal_id': inv.journal_id.id,
690 'period_id': inv.period_id.id,
691 'partner_id': inv.partner_id.id,
692 'currency_id': company_currency <> current_currency and current_currency or False,
693 'amount_currency': company_currency <> current_currency and sign * inv.amount or 0.0,
695 'date_maturity': inv.date_due
697 move_line_pool.create(cr, uid, move_line)
699 line_total = debit - credit
700 if inv.type == 'sale':
701 line_total = line_total - currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
702 elif inv.type == 'purchase':
703 line_total = line_total + currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
705 for line in inv.line_ids:
706 #create one move line per voucher line where amount is not 0.0
709 #we check if the voucher line is fully paid or not and create a move line to balance the payment and initial invoice if needed
710 if line.amount == line.amount_unreconciled:
711 amount = line.move_line_id.amount_residual #residual amount in company currency
713 amount = currency_pool.compute(cr, uid, current_currency, company_currency, line.untax_amount or line.amount, context=context_multi_currency)
715 'journal_id': inv.journal_id.id,
716 'period_id': inv.period_id.id,
717 'name': line.name or '/',
718 'account_id': line.account_id.id,
720 'partner_id': inv.partner_id.id,
721 'currency_id': company_currency <> current_currency and current_currency or False,
722 'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
730 if line.type == 'dr':
734 if (line.type=='dr'):
736 move_line['debit'] = amount
739 move_line['credit'] = amount
741 if inv.tax_id and inv.type in ('sale', 'purchase'):
743 'account_tax_id': inv.tax_id.id,
745 if move_line.get('account_tax_id', False):
746 tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
747 if not (tax_data.base_code_id and tax_data.tax_code_id):
748 raise osv.except_osv(_('No Account Base Code and Account Tax Code!'),_("You have to configure account base code and account tax code on the '%s' tax!") % (tax_data.name))
749 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
750 move_line['amount_currency'] = company_currency <> current_currency and sign * line.amount or 0.0
751 voucher_line = move_line_pool.create(cr, uid, move_line)
752 if line.move_line_id.id:
753 rec_ids = [voucher_line, line.move_line_id.id]
754 rec_list_ids.append(rec_ids)
756 if not currency_pool.is_zero(cr, uid, inv.currency_id, line_total):
760 if inv.payment_option == 'with_writeoff':
761 account_id = inv.writeoff_acc_id.id
762 write_off_name = inv.comment
763 elif inv.type in ('sale', 'receipt'):
764 account_id = inv.partner_id.property_account_receivable.id
766 account_id = inv.partner_id.property_account_payable.id
768 'name': write_off_name or name,
769 'account_id': account_id,
771 'partner_id': inv.partner_id.id,
773 'credit': diff > 0 and diff or 0.0,
774 'debit': diff < 0 and -diff or 0.0,
775 #'amount_currency': company_currency <> current_currency and currency_pool.compute(cr, uid, company_currency, current_currency, diff * -1, context=context_multi_currency) or 0.0,
776 #'currency_id': company_currency <> current_currency and current_currency or False,
778 move_line_pool.create(cr, uid, move_line)
779 self.write(cr, uid, [inv.id], {
784 if inv.journal_id.entry_posted:
785 move_pool.post(cr, uid, [move_id], context={})
786 for rec_ids in rec_list_ids:
787 if len(rec_ids) >= 2:
788 move_line_pool.reconcile_partial(cr, uid, rec_ids)
791 def copy(self, cr, uid, id, default={}, context=None):
796 'line_cr_ids': False,
797 'line_dr_ids': False,
800 if 'date' not in default:
801 default['date'] = time.strftime('%Y-%m-%d')
802 return super(account_voucher, self).copy(cr, uid, id, default, context)
806 class account_voucher_line(osv.osv):
807 _name = 'account.voucher.line'
808 _description = 'Voucher Lines'
809 _order = "move_line_id"
811 def _compute_balance(self, cr, uid, ids, name, args, context=None):
812 currency_pool = self.pool.get('res.currency')
814 for line in self.browse(cr, uid, ids, context=context):
816 ctx.update({'date': line.voucher_id.date})
818 company_currency = line.voucher_id.journal_id.company_id.currency_id.id
819 voucher_currency = line.voucher_id.currency_id.id
820 move_line = line.move_line_id or False
823 res['amount_original'] = 0.0
824 res['amount_unreconciled'] = 0.0
826 elif move_line.currency_id:
827 res['amount_original'] = currency_pool.compute(cr, uid, move_line.currency_id.id, voucher_currency, move_line.amount_currency, context=ctx)
828 elif move_line and move_line.credit > 0:
829 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.credit, context=ctx)
831 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.debit, context=ctx)
834 res['amount_unreconciled'] = currency_pool.compute(cr, uid, move_line.currency_id and move_line.currency_id.id or company_currency, voucher_currency, abs(move_line.amount_residual_currency), context=ctx)
835 rs_data[line.id] = res
839 'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
840 'name':fields.char('Description', size=256),
841 'account_id':fields.many2one('account.account','Account', required=True),
842 'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
843 'untax_amount':fields.float('Untax Amount'),
844 'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
845 'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Dr/Cr'),
846 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
847 'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
848 'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
849 'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
850 'amount_original': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Original Amount', store=True),
851 'amount_unreconciled': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Open Balance', store=True),
852 'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
858 def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
860 Returns a dict that contains new values and context
862 @param move_line_id: latest value from user input for field move_line_id
863 @param args: other arguments
864 @param context: context arguments, like lang, time zone
866 @return: Returns a dict which contains new values, and context
869 move_line_pool = self.pool.get('account.move.line')
871 move_line = move_line_pool.browse(cr, user, move_line_id, context=context)
876 account_id = move_line.account_id.id
878 'account_id':account_id,
885 def default_get(self, cr, user, fields_list, context=None):
887 Returns default values for fields
888 @param fields_list: list of fields, for which default values are required to be read
889 @param context: context arguments, like lang, time zone
891 @return: Returns a dict that contains default values for fields
895 journal_id = context.get('journal_id', False)
896 partner_id = context.get('partner_id', False)
897 journal_pool = self.pool.get('account.journal')
898 partner_pool = self.pool.get('res.partner')
899 values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
900 if (not journal_id) or ('account_id' not in fields_list):
902 journal = journal_pool.browse(cr, user, journal_id, context=context)
905 if journal.type in ('sale', 'sale_refund'):
906 account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
908 elif journal.type in ('purchase', 'expense', 'purchase_refund'):
909 account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
912 partner = partner_pool.browse(cr, user, partner_id, context=context)
913 if context.get('type') == 'payment':
915 account_id = partner.property_account_payable.id
916 elif context.get('type') == 'receipt':
917 account_id = partner.property_account_receivable.id
920 'account_id':account_id,
924 account_voucher_line()
926 class account_bank_statement(osv.osv):
927 _inherit = 'account.bank.statement'
929 def button_cancel(self, cr, uid, ids, context=None):
930 voucher_obj = self.pool.get('account.voucher')
931 for st in self.browse(cr, uid, ids, context=context):
933 for line in st.line_ids:
935 voucher_ids.append(line.voucher_id.id)
936 voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
937 return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
939 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
940 voucher_obj = self.pool.get('account.voucher')
941 wf_service = netsvc.LocalService("workflow")
942 move_line_obj = self.pool.get('account.move.line')
943 bank_st_line_obj = self.pool.get('account.bank.statement.line')
944 st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
945 if st_line.voucher_id:
946 voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number}, context=context)
947 if st_line.voucher_id.state == 'cancel':
948 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
949 wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
951 v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
952 bank_st_line_obj.write(cr, uid, [st_line_id], {
953 'move_ids': [(4, v.move_id.id, False)]
956 return move_line_obj.write(cr, uid, [x.id for x in v.move_ids], {'statement_id': st_line.statement_id.id}, context=context)
957 return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
959 account_bank_statement()
961 class account_bank_statement_line(osv.osv):
962 _inherit = 'account.bank.statement.line'
964 def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
969 # company_currency_id = False
970 for line in self.browse(cursor, user, ids, context=context):
971 # if not company_currency_id:
972 # company_currency_id = line.company_id.id
974 res[line.id] = line.voucher_id.amount#
975 # res_currency_obj.compute(cursor, user,
976 # company_currency_id, line.statement_id.currency.id,
977 # line.voucher_id.amount, context=context)
982 def _check_amount(self, cr, uid, ids, context=None):
983 for obj in self.browse(cr, uid, ids, context=context):
985 diff = abs(obj.amount) - obj.voucher_id.amount
986 if not self.pool.get('res.currency').is_zero(cr, uid, obj.voucher_id.currency_id, diff):
991 (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
995 'amount_reconciled': fields.function(_amount_reconciled,
996 string='Amount reconciled', method=True, type='float'),
997 'voucher_id': fields.many2one('account.voucher', 'Payment'),
1001 def unlink(self, cr, uid, ids, context=None):
1002 voucher_obj = self.pool.get('account.voucher')
1003 statement_line = self.browse(cr, uid, ids, context=context)
1005 for st_line in statement_line:
1006 if st_line.voucher_id:
1007 unlink_ids.append(st_line.voucher_id.id)
1008 voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1009 return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1011 account_bank_statement_line()
1013 def resolve_o2m_operations(cr, uid, target_osv, operations, fields, context):
1015 for operation in operations:
1017 if not isinstance(operation, (list, tuple)):
1018 result = target_osv.read(cr, uid, operation, fields, context=context)
1019 if operation[0] == 0:
1020 # may be necessary to check if all the fields are here and get the default values?
1021 result = operation[2]
1022 elif operation[0] == 1:
1023 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1024 result.update(operation[2])
1025 elif operation[0] == 4:
1026 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1027 results.append(result)
1030 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: