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 _
30 class account_move_line(osv.osv):
31 _inherit = 'account.move.line'
33 def _unreconciled(self, cr, uid, ids, prop, unknow_none, context=None):
35 for line in self.browse(cr, uid, ids, context=context):
36 res[line.id] = line.debit - line.credit
37 if line.reconcile_partial_id:
39 for partial in line.reconcile_partial_id.line_partial_ids:
40 res[line.id] += partial.debit - partial.credit
41 res[line.id] = abs(res[line.id])
45 'amount_unreconciled': fields.function(_unreconciled, method=True, string='Unreconciled Amount'),
50 class account_voucher(osv.osv):
52 def _get_type(self, cr, uid, ids, context=None):
53 if context is None: context = {}
54 return context.get('type', False)
56 def _get_period(self, cr, uid, context=None):
57 if context is None: context = {}
58 if context.get('period_id', False):
59 return context.get('period_id')
60 periods = self.pool.get('account.period').find(cr, uid)
61 return periods and periods[0] or False
63 def _get_journal(self, cr, uid, context=None):
64 if context is None: context = {}
65 journal_pool = self.pool.get('account.journal')
66 if context.get('journal_id', False):
67 return context.get('journal_id')
68 if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
69 return context.get('search_default_journal_id')
71 ttype = context.get('type', 'bank')
72 if ttype in ('payment', 'receipt'):
74 res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
75 return res and res[0] or False
77 def _get_tax(self, cr, uid, context=None):
78 if context is None: context = {}
79 journal_pool = self.pool.get('account.journal')
80 journal_id = context.get('journal_id', False)
82 ttype = context.get('type', 'bank')
83 res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
90 journal = journal_pool.browse(cr, uid, journal_id, context=context)
91 account_id = journal.default_credit_account_id or journal.default_debit_account_id
92 if account_id and account_id.tax_ids:
93 tax_id = account_id.tax_ids[0].id
97 def _get_currency(self, cr, uid, context=None):
98 if context is None: context = {}
99 journal_pool = self.pool.get('account.journal')
100 journal_id = context.get('journal_id', False)
102 journal = journal_pool.browse(cr, uid, journal_id, context=context)
103 # currency_id = journal.company_id.currency_id.id
105 return journal.currency.id
108 def _get_partner(self, cr, uid, context=None):
109 if context is None: context = {}
110 return context.get('partner_id', False)
112 def _get_reference(self, cr, uid, context=None):
113 if context is None: context = {}
114 return context.get('reference', False)
116 def _get_narration(self, cr, uid, context=None):
117 if context is None: context = {}
118 return context.get('narration', False)
120 def _get_amount(self, cr, uid, context=None):
123 return context.get('amount', 0.0)
125 def name_get(self, cr, uid, ids, context=None):
128 if context is None: context = {}
129 return [(r['id'], (str("%.2f" % r['amount']) or '')) for r in self.read(cr, uid, ids, ['amount'], context, load='_classic_write')]
131 def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
132 mod_obj = self.pool.get('ir.model.data')
133 if context is None: context = {}
134 if not view_id and context.get('invoice_type', False):
135 if context.get('invoice_type', False) in ('out_invoice', 'out_refund'):
136 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
138 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
139 result = result and result[1] or False
141 if not view_id and context.get('line_type', False):
142 if context.get('line_type', False) == 'customer':
143 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
145 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
146 result = result and result[1] or False
149 res = super(account_voucher, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
150 doc = etree.XML(res['arch'])
151 nodes = doc.xpath("//field[@name='partner_id']")
152 if context.get('type', 'sale') in ('purchase', 'payment'):
154 node.set('domain', "[('supplier', '=', True)]")
155 res['arch'] = etree.tostring(doc)
158 def _compute_writeoff_amount(self, cr, uid, line_dr_ids, line_cr_ids, amount):
160 for l in line_dr_ids:
162 for l in line_cr_ids:
163 credit += l['amount']
164 return abs(amount - abs(credit - debit))
166 def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount):
167 line_dr_ids = [x[2] for x in line_dr_ids]
168 line_cr_ids = [x[2] for x in line_cr_ids]
169 return {'value': {'writeoff_amount': self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount)}}
171 def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
172 if not ids: return {}
175 for voucher in self.browse(cr, uid, ids, context=context):
176 for l in voucher.line_dr_ids:
178 for l in voucher.line_cr_ids:
180 res[voucher.id] = abs(voucher.amount - abs(credit - debit))
183 _name = 'account.voucher'
184 _description = 'Accounting Voucher'
185 _order = "date desc, id desc"
186 # _rec_name = 'number'
188 'type':fields.selection([
190 ('purchase','Purchase'),
191 ('payment','Payment'),
192 ('receipt','Receipt'),
193 ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
194 'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
195 'date':fields.date('Date', readonly=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
196 'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}),
197 'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
198 'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
199 'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
200 domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
201 'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
202 domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
203 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
204 'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
205 'currency_id':fields.many2one('res.currency', 'Currency', readonly=True, states={'draft':[('readonly',False)]}),
206 # 'currency_id': fields.related('journal_id','currency', type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, states={'draft':[('readonly',False)]}),
207 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft':[('readonly',False)]}),
208 'state':fields.selection(
210 ('proforma','Pro-forma'),
212 ('cancel','Cancelled')
213 ], 'State', readonly=True, size=32,
214 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
215 \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
216 \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
217 \n* The \'Cancelled\' state is used when user cancel voucher.'),
218 'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
219 'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
220 'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
221 'number': fields.char('Number', size=32, readonly=True,),
222 'move_id':fields.many2one('account.move', 'Account Entry'),
223 'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
224 'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
225 'audit': fields.related('move_id','to_check', type='boolean', relation='account.move', string='Audit Complete ?'),
226 'pay_now':fields.selection([
227 ('pay_now','Pay Directly'),
228 ('pay_later','Pay Later or Group Funds'),
229 ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
230 'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
231 'pre_line':fields.boolean('Previous Payments ?', required=False),
232 'date_due': fields.date('Due Date', readonly=True, states={'draft':[('readonly',False)]}),
233 'payment_option':fields.selection([
234 ('without_writeoff', 'Keep Open'),
235 ('with_writeoff', 'Reconcile with Write-Off'),
236 ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
237 'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
238 'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
239 'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
240 'writeoff_amount': fields.function(_get_writeoff_amount, method=True, string='Write-Off Amount', type='float', readonly=True),
243 'period_id': _get_period,
244 'partner_id': _get_partner,
245 'journal_id':_get_journal,
246 'currency_id': _get_currency,
247 'reference': _get_reference,
248 'narration':_get_narration,
249 'amount': _get_amount,
252 'pay_now': 'pay_later',
254 'date': lambda *a: time.strftime('%Y-%m-%d'),
255 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
257 'payment_option': 'without_writeoff',
258 'comment': _('Write-Off'),
261 def compute_tax(self, cr, uid, ids, context=None):
262 tax_pool = self.pool.get('account.tax')
263 partner_pool = self.pool.get('res.partner')
264 position_pool = self.pool.get('account.fiscal.position')
265 voucher_line_pool = self.pool.get('account.voucher.line')
266 voucher_pool = self.pool.get('account.voucher')
267 if context is None: context = {}
269 for voucher in voucher_pool.browse(cr, uid, ids, context=context):
271 for line in voucher.line_ids:
272 voucher_amount += line.untax_amount or line.amount
273 line.amount = line.untax_amount or line.amount
274 voucher_line_pool.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
276 if not voucher.tax_id:
277 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
280 tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
281 partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
282 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
283 tax = tax_pool.browse(cr, uid, taxes, context=context)
285 total = voucher_amount
288 if not tax[0].price_include:
289 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
290 total_tax += tax_line.get('amount', 0.0)
293 for line in voucher.line_ids:
297 for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
298 line_tax += tax_line.get('amount', 0.0)
299 line_total += tax_line.get('price_unit')
300 total_tax += line_tax
301 untax_amount = line.untax_amount or line.amount
302 voucher_line_pool.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
304 self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
307 def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
308 tax_pool = self.pool.get('account.tax')
309 partner_pool = self.pool.get('res.partner')
310 position_pool = self.pool.get('account.fiscal.position')
316 voucher_line_ids = []
320 for line in line_ids:
322 line_amount = line[2] and line[2].get('amount',0.0) or 0.0
323 voucher_line_ids += [line[1]]
324 voucher_total += line_amount
326 total = voucher_total
329 tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
331 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
332 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
333 tax = tax_pool.browse(cr, uid, taxes, context=context)
335 if not tax[0].price_include:
336 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
337 total_tax += tax_line.get('amount')
341 'amount':total or voucher_total,
342 'tax_amount':total_tax
348 def onchange_term_id(self, cr, uid, ids, term_id, amount):
349 term_pool = self.pool.get('account.payment.term')
352 default = {'date_due':False}
353 if term_id and amount:
354 terms = term_pool.compute(cr, uid, term_id, amount)
356 due_date = terms[-1][0]
360 return {'value':default}
362 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):
364 Returns a dict that contains new values and context
366 @param partner_id: latest value from user input for field partner_id
367 @param args: other arguments
368 @param context: context arguments, like lang, time zone
370 @return: Returns a dict which contains new values, and context
376 if not partner_id or not journal_id:
379 partner_pool = self.pool.get('res.partner')
380 journal_pool = self.pool.get('account.journal')
382 journal = journal_pool.browse(cr, uid, journal_id, context=context)
383 partner = partner_pool.browse(cr, uid, partner_id, context=context)
386 if journal.type in ('sale','sale_refund'):
387 account_id = partner.property_account_receivable.id
389 elif journal.type in ('purchase', 'purchase_refund','expense'):
390 account_id = partner.property_account_payable.id
393 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
396 default['value']['account_id'] = account_id
397 default['value']['type'] = ttype or tr_type
399 vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
400 default['value'].update(vals.get('value'))
404 def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
406 Returns a dict that contains new values and context
408 @param partner_id: latest value from user input for field partner_id
409 @param args: other arguments
410 @param context: context arguments, like lang, time zone
412 @return: Returns a dict which contains new values, and context
418 context_multi_currency = context.copy()
420 context_multi_currency.update({'date': date})
422 line_pool = self.pool.get('account.voucher.line')
423 line_ids = ids and line_pool.search(cr, uid, [('voucher_id', '=', ids[0])]) or False
425 line_pool.unlink(cr, uid, line_ids)
427 currency_pool = self.pool.get('res.currency')
428 move_line_pool = self.pool.get('account.move.line')
429 partner_pool = self.pool.get('res.partner')
430 journal_pool = self.pool.get('account.journal')
432 vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context)
433 vals = vals.get('value')
434 currency_id = vals.get('currency_id', currency_id)
436 'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id':currency_id},
442 if not partner_id and ids:
443 line_ids = line_pool.search(cr, uid, [('voucher_id', '=', ids[0])])
445 line_pool.unlink(cr, uid, line_ids)
448 journal = journal_pool.browse(cr, uid, journal_id, context=context)
449 partner = partner_pool.browse(cr, uid, partner_id, context=context)
451 if journal.type in ('sale','sale_refund'):
452 account_id = partner.property_account_receivable.id
453 elif journal.type in ('purchase', 'purchase_refund','expense'):
454 account_id = partner.property_account_payable.id
456 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
458 default['value']['account_id'] = account_id
460 if journal.type not in ('cash', 'bank'):
465 account_type = 'receivable'
466 if ttype == 'payment':
467 account_type = 'payable'
468 total_debit = price or 0.0
470 total_credit = price or 0.0
471 account_type = 'receivable'
473 if not context.get('move_line_ids', False):
474 ids = move_line_pool.search(cr, uid, [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)], context=context)
476 ids = context['move_line_ids']
478 moves = move_line_pool.browse(cr, uid, ids, context=context)
480 company_currency = journal.company_id.currency_id.id
481 if company_currency != currency_id and ttype == 'payment':
482 total_debit = currency_pool.compute(cr, uid, currency_id, company_currency, total_debit, context=context_multi_currency)
483 elif company_currency != currency_id and ttype == 'receipt':
484 total_credit = currency_pool.compute(cr, uid, currency_id, company_currency, total_credit, context=context_multi_currency)
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 total_credit += line.credit or 0.0
492 total_debit += line.debit or 0.0
495 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
497 if line.debit and line.reconcile_partial_id and ttype == 'payment':
500 original_amount = line.credit or line.debit or 0.0
502 'name':line.move_id.name,
503 'type': line.credit and 'dr' or 'cr',
504 'move_line_id':line.id,
505 'account_id':line.account_id.id,
506 'amount_original':currency_pool.compute(cr, uid, company_currency, currency_id, original_amount, context=context_multi_currency),
507 'date_original':line.date,
508 'date_due':line.date_maturity,
509 'amount_unreconciled':currency_pool.compute(cr, uid, company_currency, currency_id, line.amount_unreconciled, context=context_multi_currency)
512 amount = min(line.amount_unreconciled, total_debit)
513 rs['amount'] = currency_pool.compute(cr, uid, company_currency, currency_id, amount, context=context_multi_currency)
514 total_debit -= amount
516 amount = min(line.amount_unreconciled, total_credit)
517 rs['amount'] = currency_pool.compute(cr, uid, company_currency, currency_id, amount, context=context_multi_currency)
518 total_credit -= amount
520 default['value']['line_ids'].append(rs)
521 if rs['type'] == 'cr':
522 default['value']['line_cr_ids'].append(rs)
524 default['value']['line_dr_ids'].append(rs)
526 if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
527 default['value']['pre_line'] = 1
528 elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
529 default['value']['pre_line'] = 1
530 default['value']['writeoff_amount'] = self._compute_writeoff_amount(cr, uid, default['value']['line_dr_ids'], default['value']['line_cr_ids'], price)
534 def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
536 @param date: latest value from user input for field date
537 @param args: other arguments
538 @param context: context arguments, like lang, time zone
539 @return: Returns a dict which contains new values, and context
541 period_pool = self.pool.get('account.period')
542 res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
543 pids = period_pool.search(cr, uid, [('date_start', '<=', date), ('date_stop', '>=', date)])
545 if not 'value' in res:
547 res['value'].update({'period_id':pids[0]})
550 def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
553 journal_pool = self.pool.get('account.journal')
554 journal = journal_pool.browse(cr, uid, journal_id, context=context)
555 account_id = journal.default_credit_account_id or journal.default_debit_account_id
557 if account_id and account_id.tax_ids:
558 tax_id = account_id.tax_ids[0].id
560 vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
561 vals['value'].update({'tax_id':tax_id})
562 currency_id = journal.company_id.currency_id.id
564 currency_id = journal.currency.id
565 vals['value'].update({'currency_id':currency_id})
568 def proforma_voucher(self, cr, uid, ids, context=None):
569 self.action_move_line_create(cr, uid, ids, context=context)
572 def action_cancel_draft(self, cr, uid, ids, context=None):
573 wf_service = netsvc.LocalService("workflow")
574 for voucher_id in ids:
575 wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
576 self.write(cr, uid, ids, {'state':'draft'})
579 def cancel_voucher(self, cr, uid, ids, context=None):
580 reconcile_pool = self.pool.get('account.move.reconcile')
581 move_pool = self.pool.get('account.move')
583 for voucher in self.browse(cr, uid, ids, context=context):
585 for line in voucher.move_ids:
586 if line.reconcile_id:
587 recs += [line.reconcile_id.id]
588 if line.reconcile_partial_id:
589 recs += [line.reconcile_partial_id.id]
591 reconcile_pool.unlink(cr, uid, recs)
594 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
595 move_pool.unlink(cr, uid, [voucher.move_id.id])
600 self.write(cr, uid, ids, res)
603 def unlink(self, cr, uid, ids, context=None):
604 for t in self.read(cr, uid, ids, ['state'], context=context):
605 if t['state'] not in ('draft', 'cancel'):
606 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
607 return super(account_voucher, self).unlink(cr, uid, ids, context=context)
609 # TODO: may be we can remove this method if not used anyware
610 def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
614 res = {'account_id':False}
615 partner_pool = self.pool.get('res.partner')
616 journal_pool = self.pool.get('account.journal')
617 if pay_now == 'pay_later':
618 partner = partner_pool.browse(cr, uid, partner_id)
619 journal = journal_pool.browse(cr, uid, journal_id)
620 if journal.type in ('sale','sale_refund'):
621 account_id = partner.property_account_receivable.id
622 elif journal.type in ('purchase', 'purchase_refund','expense'):
623 account_id = partner.property_account_payable.id
625 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
626 res['account_id'] = account_id
629 def action_move_line_create(self, cr, uid, ids, context=None):
631 def _get_payment_term_lines(term_id, amount):
632 term_pool = self.pool.get('account.payment.term')
633 if term_id and amount:
634 terms = term_pool.compute(cr, uid, term_id, amount)
639 move_pool = self.pool.get('account.move')
640 move_line_pool = self.pool.get('account.move.line')
641 currency_pool = self.pool.get('res.currency')
642 tax_obj = self.pool.get('account.tax')
643 seq_obj = self.pool.get('ir.sequence')
644 for inv in self.browse(cr, uid, ids, context=context):
647 context_multi_currency = context.copy()
648 context_multi_currency.update({'date': inv.date})
652 elif inv.journal_id.sequence_id:
653 name = seq_obj.get_id(cr, uid, inv.journal_id.sequence_id.id)
655 raise osv.except_osv(_('Error !'), _('Please define a sequence on the journal !'))
656 if not inv.reference:
657 ref = name.replace('/','')
663 'journal_id': inv.journal_id.id,
664 'narration': inv.narration,
667 'period_id': inv.period_id and inv.period_id.id or False
669 move_id = move_pool.create(cr, uid, move)
671 #create the first line manually
672 company_currency = inv.journal_id.company_id.currency_id.id
673 current_currency = inv.currency_id.id
676 # TODO: is there any other alternative then the voucher type ??
677 # -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
678 if inv.type in ('purchase', 'payment'):
679 credit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
680 elif inv.type in ('sale', 'receipt'):
681 debit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
688 sign = debit - credit < 0 and -1 or 1
690 'name': inv.name or '/',
693 'account_id': inv.account_id.id,
695 'journal_id': inv.journal_id.id,
696 'period_id': inv.period_id.id,
697 'partner_id': inv.partner_id.id,
698 'currency_id': company_currency <> current_currency and current_currency or False,
699 'amount_currency': company_currency <> current_currency and sign * inv.amount or 0.0,
701 'date_maturity': inv.date_due
703 if (debit == 0.0 or credit == 0.0 or debit+credit > 0) and (debit > 0.0 or credit > 0.0):
704 master_line = move_line_pool.create(cr, uid, move_line)
707 line_total = debit - credit
708 if inv.type == 'sale':
709 line_total = line_total - currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
710 elif inv.type == 'purchase':
711 line_total = line_total + currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
713 for line in inv.line_ids:
716 amount = currency_pool.compute(cr, uid, current_currency, company_currency, line.untax_amount or line.amount, context=context_multi_currency)
718 'journal_id': inv.journal_id.id,
719 'period_id': inv.period_id.id,
720 'name': line.name and line.name or '/',
721 'account_id': line.account_id.id,
723 'partner_id': inv.partner_id.id,
724 'currency_id': company_currency <> current_currency and current_currency or False,
725 'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
733 if line.type == 'dr':
738 if (line.type=='dr'):
740 move_line['debit'] = amount
743 move_line['credit'] = amount
745 if inv.tax_id and inv.type in ('sale', 'purchase'):
747 'account_tax_id': inv.tax_id.id,
749 if move_line.get('account_tax_id', False):
750 tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
751 if not (tax_data.base_code_id and tax_data.tax_code_id):
752 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))
753 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
754 move_line['amount_currency'] = company_currency <> current_currency and sign * line.amount or 0.0
755 master_line = move_line_pool.create(cr, uid, move_line)
756 if line.move_line_id.id:
757 rec_ids = [master_line, line.move_line_id.id]
758 rec_list_ids.append(rec_ids)
760 if not currency_pool.is_zero(cr, uid, inv.currency_id, line_total):
763 if inv.payment_option == 'with_writeoff':
764 account_id = inv.writeoff_acc_id.id
765 elif inv.type in ('sale', 'receipt'):
766 # if inv.journal_id.type in ('sale','sale_refund', 'cash', 'bank'):
767 account_id = inv.partner_id.property_account_receivable.id
769 account_id = inv.partner_id.property_account_payable.id
772 'account_id': account_id,
774 'partner_id': inv.partner_id.id,
776 'credit': diff > 0 and diff or 0.0,
777 'debit': diff < 0 and -diff or 0.0,
778 '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,
779 'currency_id': company_currency <> current_currency and current_currency or False,
780 'analytic_account_id': inv.analytic_id.id,
782 move_line_pool.create(cr, uid, move_line)
784 self.write(cr, uid, [inv.id], {
789 move_pool.post(cr, uid, [move_id], context={})
790 for rec_ids in rec_list_ids:
791 if len(rec_ids) >= 2:
792 move_line_pool.reconcile_partial(cr, uid, rec_ids)
795 def copy(self, cr, uid, id, default={}, context=None):
800 'line_cr_ids': False,
801 'line_dr_ids': False,
804 if 'date' not in default:
805 default['date'] = time.strftime('%Y-%m-%d')
806 return super(account_voucher, self).copy(cr, uid, id, default, context)
810 class account_voucher_line(osv.osv):
811 _name = 'account.voucher.line'
812 _description = 'Voucher Lines'
813 _order = "move_line_id"
815 def _compute_balance(self, cr, uid, ids, name, args, context=None):
816 currency_pool = self.pool.get('res.currency')
818 for line in self.browse(cr, uid, ids, context=context):
820 company_currency = line.voucher_id.journal_id.company_id.currency_id.id
821 voucher_currency = line.voucher_id.currency_id.id
822 move_line = line.move_line_id or False
825 res['amount_original'] = 0.0
826 res['amount_unreconciled'] = 0.0
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)
831 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.debit)
834 res['amount_unreconciled'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.amount_unreconciled)
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')], 'Cr/Dr'),
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),
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 if not (abs(obj.amount) == obj.voucher_id.amount):
990 (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
994 'amount_reconciled': fields.function(_amount_reconciled,
995 string='Amount reconciled', method=True, type='float'),
996 'voucher_id': fields.many2one('account.voucher', 'Payment'),
1000 def unlink(self, cr, uid, ids, context=None):
1001 voucher_obj = self.pool.get('account.voucher')
1002 statement_line = self.browse(cr, uid, ids, context=context)
1004 for st_line in statement_line:
1005 if st_line.voucher_id:
1006 unlink_ids.append(st_line.voucher_id.id)
1007 voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1008 return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1010 account_bank_statement_line()
1012 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: