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 ##############################################################################
24 from openerp.osv import fields, osv
25 from openerp.tools.translate import _
26 import openerp.addons.decimal_precision as dp
28 class account_bank_statement(osv.osv):
29 def create(self, cr, uid, vals, context=None):
30 if 'line_ids' in vals:
31 for idx, line in enumerate(vals['line_ids']):
32 line[2]['sequence'] = idx + 1
33 return super(account_bank_statement, self).create(cr, uid, vals, context=context)
35 def write(self, cr, uid, ids, vals, context=None):
36 res = super(account_bank_statement, self).write(cr, uid, ids, vals, context=context)
37 account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
38 for statement in self.browse(cr, uid, ids, context):
39 for idx, line in enumerate(statement.line_ids):
40 account_bank_statement_line_obj.write(cr, uid, [line.id], {'sequence': idx + 1}, context=context)
43 def _default_journal_id(self, cr, uid, context=None):
46 journal_pool = self.pool.get('account.journal')
47 journal_type = context.get('journal_type', False)
48 company_id = self.pool.get('res.company')._company_default_get(cr, uid, 'account.bank.statement',context=context)
50 ids = journal_pool.search(cr, uid, [('type', '=', journal_type),('company_id','=',company_id)])
55 def _end_balance(self, cursor, user, ids, name, attr, context=None):
57 for statement in self.browse(cursor, user, ids, context=context):
58 res[statement.id] = statement.balance_start
59 for line in statement.line_ids:
60 res[statement.id] += line.amount
63 def _get_period(self, cr, uid, context=None):
64 periods = self.pool.get('account.period').find(cr, uid,context=context)
69 def _currency(self, cursor, user, ids, name, args, context=None):
71 res_currency_obj = self.pool.get('res.currency')
72 res_users_obj = self.pool.get('res.users')
73 default_currency = res_users_obj.browse(cursor, user,
74 user, context=context).company_id.currency_id
75 for statement in self.browse(cursor, user, ids, context=context):
76 currency = statement.journal_id.currency
78 currency = default_currency
79 res[statement.id] = currency.id
81 for currency_id, currency_name in res_currency_obj.name_get(cursor,
82 user, [x for x in res.values()], context=context):
83 currency_names[currency_id] = currency_name
84 for statement_id in res.keys():
85 currency_id = res[statement_id]
86 res[statement_id] = (currency_id, currency_names[currency_id])
89 def _get_statement(self, cr, uid, ids, context=None):
91 for line in self.pool.get('account.bank.statement.line').browse(cr, uid, ids, context=context):
92 result[line.statement_id.id] = True
95 _order = "date desc, id desc"
96 _name = "account.bank.statement"
97 _description = "Bank Statement"
98 _inherit = ['mail.thread']
100 'name': fields.char('Reference', size=64, required=True, states={'draft': [('readonly', False)]}, readonly=True, help='if you give the Name other then /, its created Accounting Entries Move will be with same name as statement name. This allows the statement entries to have the same references than the statement itself'), # readonly for account_cash_statement
101 'date': fields.date('Date', required=True, states={'confirm': [('readonly', True)]}, select=True),
102 'journal_id': fields.many2one('account.journal', 'Journal', required=True,
103 readonly=True, states={'draft':[('readonly',False)]}),
104 'period_id': fields.many2one('account.period', 'Period', required=True,
105 states={'confirm':[('readonly', True)]}),
106 'balance_start': fields.float('Starting Balance', digits_compute=dp.get_precision('Account'),
107 states={'confirm':[('readonly',True)]}),
108 'balance_end_real': fields.float('Ending Balance', digits_compute=dp.get_precision('Account'),
109 states={'confirm': [('readonly', True)]}),
110 'balance_end': fields.function(_end_balance,
112 'account.bank.statement': (lambda self, cr, uid, ids, c={}: ids, ['line_ids','move_line_ids','balance_start'], 10),
113 'account.bank.statement.line': (_get_statement, ['amount'], 10),
115 string="Computed Balance", help='Balance as calculated based on Starting Balance and transaction lines'),
116 'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
117 'line_ids': fields.one2many('account.bank.statement.line',
118 'statement_id', 'Statement lines',
119 states={'confirm':[('readonly', True)]}),
120 'move_line_ids': fields.one2many('account.move.line', 'statement_id',
121 'Entry lines', states={'confirm':[('readonly',True)]}),
122 'state': fields.selection([('draft', 'New'),
123 ('open','Open'), # used by cash statements
124 ('confirm', 'Closed')],
125 'Status', required=True, readonly="1",
126 help='When new statement is created the status will be \'Draft\'.\n'
127 'And after getting confirmation from the bank it will be in \'Confirmed\' status.'),
128 'currency': fields.function(_currency, string='Currency',
129 type='many2one', relation='res.currency'),
130 'account_id': fields.related('journal_id', 'default_debit_account_id', type='many2one', relation='account.account', string='Account used in this journal', readonly=True, help='used in statement reconciliation domain, but shouldn\'t be used elswhere.'),
135 'date': fields.date.context_today,
137 'journal_id': _default_journal_id,
138 'period_id': _get_period,
139 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.bank.statement',context=c),
142 def _check_company_id(self, cr, uid, ids, context=None):
143 for statement in self.browse(cr, uid, ids, context=context):
144 if statement.company_id.id != statement.period_id.company_id.id:
149 (_check_company_id, 'The journal and period chosen have to belong to the same company.', ['journal_id','period_id']),
152 def onchange_date(self, cr, uid, ids, date, company_id, context=None):
154 Find the correct period to use for the given date and company_id, return it and set it in the context
157 period_pool = self.pool.get('account.period')
162 ctx.update({'company_id': company_id})
163 pids = period_pool.find(cr, uid, dt=date, context=ctx)
165 res.update({'period_id': pids[0]})
166 context.update({'period_id': pids[0]})
173 def button_dummy(self, cr, uid, ids, context=None):
174 return self.write(cr, uid, ids, {}, context=context)
176 def _prepare_move(self, cr, uid, st_line, st_line_number, context=None):
177 """Prepare the dict of values to create the move from a
178 statement line. This method may be overridden to implement custom
179 move generation (making sure to call super() to establish
180 a clean extension chain).
182 :param browse_record st_line: account.bank.statement.line record to
183 create the move from.
184 :param char st_line_number: will be used as the name of the generated account move
185 :return: dict of value to create() the account.move
188 'journal_id': st_line.statement_id.journal_id.id,
189 'period_id': st_line.statement_id.period_id.id,
190 'date': st_line.date,
191 'name': st_line_number,
195 def _prepare_bank_move_line(self, cr, uid, st_line, move_id, amount, company_currency_id,
197 """Compute the args to build the dict of values to create the bank move line from a
198 statement line by calling the _prepare_move_line_vals. This method may be
199 overridden to implement custom move generation (making sure to call super() to
200 establish a clean extension chain).
202 :param browse_record st_line: account.bank.statement.line record to
203 create the move from.
204 :param int/long move_id: ID of the account.move to link the move line
205 :param float amount: amount of the move line
206 :param int/long company_currency_id: ID of currency of the concerned company
207 :return: dict of value to create() the bank account.move.line
209 anl_id = st_line.analytic_account_id and st_line.analytic_account_id.id or False
210 debit = ((amount<0) and -amount) or 0.0
211 credit = ((amount>0) and amount) or 0.0
214 if st_line.statement_id.currency.id <> company_currency_id:
215 cur_id = st_line.statement_id.currency.id
216 if st_line.account_id and st_line.account_id.currency_id and st_line.account_id.currency_id.id <> company_currency_id:
217 cur_id = st_line.account_id.currency_id.id
219 res_currency_obj = self.pool.get('res.currency')
220 amt_cur = -res_currency_obj.compute(cr, uid, company_currency_id, cur_id, amount, context=context)
222 res = self._prepare_move_line_vals(cr, uid, st_line, move_id, debit, credit,
223 amount_currency=amt_cur, currency_id=cur_id, analytic_id=anl_id, context=context)
226 def _get_counter_part_account(sefl, cr, uid, st_line, context=None):
227 """Retrieve the account to use in the counterpart move.
228 This method may be overridden to implement custom move generation (making sure to
229 call super() to establish a clean extension chain).
231 :param browse_record st_line: account.bank.statement.line record to
232 create the move from.
233 :return: int/long of the account.account to use as counterpart
235 if st_line.amount >= 0:
236 return st_line.statement_id.journal_id.default_credit_account_id.id
237 return st_line.statement_id.journal_id.default_debit_account_id.id
239 def _get_counter_part_partner(sefl, cr, uid, st_line, context=None):
240 """Retrieve the partner to use in the counterpart move.
241 This method may be overridden to implement custom move generation (making sure to
242 call super() to establish a clean extension chain).
244 :param browse_record st_line: account.bank.statement.line record to
245 create the move from.
246 :return: int/long of the res.partner to use as counterpart
248 return st_line.partner_id and st_line.partner_id.id or False
250 def _prepare_counterpart_move_line(self, cr, uid, st_line, move_id, amount, company_currency_id,
252 """Compute the args to build the dict of values to create the counter part move line from a
253 statement line by calling the _prepare_move_line_vals. This method may be
254 overridden to implement custom move generation (making sure to call super() to
255 establish a clean extension chain).
257 :param browse_record st_line: account.bank.statement.line record to
258 create the move from.
259 :param int/long move_id: ID of the account.move to link the move line
260 :param float amount: amount of the move line
261 :param int/long account_id: ID of account to use as counter part
262 :param int/long company_currency_id: ID of currency of the concerned company
263 :return: dict of value to create() the bank account.move.line
265 account_id = self._get_counter_part_account(cr, uid, st_line, context=context)
266 partner_id = self._get_counter_part_partner(cr, uid, st_line, context=context)
267 debit = ((amount > 0) and amount) or 0.0
268 credit = ((amount < 0) and -amount) or 0.0
271 if st_line.statement_id.currency.id <> company_currency_id:
272 amt_cur = st_line.amount
273 cur_id = st_line.statement_id.currency.id
274 return self._prepare_move_line_vals(cr, uid, st_line, move_id, debit, credit,
275 amount_currency = amt_cur, currency_id = cur_id, account_id = account_id,
276 partner_id = partner_id, context=context)
278 def _prepare_move_line_vals(self, cr, uid, st_line, move_id, debit, credit, currency_id = False,
279 amount_currency= False, account_id = False, analytic_id = False,
280 partner_id = False, context=None):
281 """Prepare the dict of values to create the move line from a
282 statement line. All non-mandatory args will replace the default computed one.
283 This method may be overridden to implement custom move generation (making sure to
284 call super() to establish a clean extension chain).
286 :param browse_record st_line: account.bank.statement.line record to
287 create the move from.
288 :param int/long move_id: ID of the account.move to link the move line
289 :param float debit: debit amount of the move line
290 :param float credit: credit amount of the move line
291 :param int/long currency_id: ID of currency of the move line to create
292 :param float amount_currency: amount of the debit/credit expressed in the currency_id
293 :param int/long account_id: ID of the account to use in the move line if different
294 from the statement line account ID
295 :param int/long analytic_id: ID of analytic account to put on the move line
296 :param int/long partner_id: ID of the partner to put on the move line
297 :return: dict of value to create() the account.move.line
299 acc_id = account_id or st_line.account_id.id
300 cur_id = currency_id or st_line.statement_id.currency.id
301 par_id = partner_id or (((st_line.partner_id) and st_line.partner_id.id) or False)
303 'name': st_line.name,
304 'date': st_line.date,
307 'partner_id': par_id,
308 'account_id': acc_id,
311 'statement_id': st_line.statement_id.id,
312 'journal_id': st_line.statement_id.journal_id.id,
313 'period_id': st_line.statement_id.period_id.id,
314 'currency_id': amount_currency and cur_id,
315 'amount_currency': amount_currency,
316 'analytic_account_id': analytic_id,
319 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, st_line_number, context=None):
320 """Create the account move from the statement line.
322 :param int/long st_line_id: ID of the account.bank.statement.line to create the move from.
323 :param int/long company_currency_id: ID of the res.currency of the company
324 :param char st_line_number: will be used as the name of the generated account move
325 :return: ID of the account.move created
330 res_currency_obj = self.pool.get('res.currency')
331 account_move_obj = self.pool.get('account.move')
332 account_move_line_obj = self.pool.get('account.move.line')
333 account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
334 st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context=context)
335 st = st_line.statement_id
337 context.update({'date': st_line.date})
339 move_vals = self._prepare_move(cr, uid, st_line, st_line_number, context=context)
340 move_id = account_move_obj.create(cr, uid, move_vals, context=context)
341 account_bank_statement_line_obj.write(cr, uid, [st_line.id], {
342 'move_ids': [(4, move_id, False)]
345 acc_cur = ((st_line.amount<=0) and st.journal_id.default_debit_account_id) or st_line.account_id
348 'res.currency.compute.account': acc_cur,
350 amount = res_currency_obj.compute(cr, uid, st.currency.id,
351 company_currency_id, st_line.amount, context=context)
353 bank_move_vals = self._prepare_bank_move_line(cr, uid, st_line, move_id, amount,
354 company_currency_id, context=context)
355 move_line_id = account_move_line_obj.create(cr, uid, bank_move_vals, context=context)
356 torec.append(move_line_id)
358 counterpart_move_vals = self._prepare_counterpart_move_line(cr, uid, st_line, move_id,
359 amount, company_currency_id, context=context)
360 account_move_line_obj.create(cr, uid, counterpart_move_vals, context=context)
362 for line in account_move_line_obj.browse(cr, uid, [x.id for x in
363 account_move_obj.browse(cr, uid, move_id,
364 context=context).line_id],
366 if line.state <> 'valid':
367 raise osv.except_osv(_('Error!'),
368 _('Journal item "%s" is not valid.') % line.name)
370 # Bank statements will not consider boolean on journal entry_posted
371 account_move_obj.post(cr, uid, [move_id], context=context)
374 def get_next_st_line_number(self, cr, uid, st_number, st_line, context=None):
375 return st_number + '/' + str(st_line.sequence)
377 def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
378 st = self.browse(cr, uid, st_id, context=context)
379 if not ((abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001) or (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001)):
380 raise osv.except_osv(_('Error!'),
381 _('The statement balance is incorrect !\nThe expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
384 def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
385 return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
387 def check_status_condition(self, cr, uid, state, journal_type='bank'):
388 return state in ('draft','open')
390 def button_confirm_bank(self, cr, uid, ids, context=None):
391 obj_seq = self.pool.get('ir.sequence')
395 for st in self.browse(cr, uid, ids, context=context):
396 j_type = st.journal_id.type
397 company_currency_id = st.journal_id.company_id.currency_id.id
398 if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
401 self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
402 if (not st.journal_id.default_credit_account_id) \
403 or (not st.journal_id.default_debit_account_id):
404 raise osv.except_osv(_('Configuration Error!'),
405 _('Please verify that an account is defined in the journal.'))
407 if not st.name == '/':
410 c = {'fiscalyear_id': st.period_id.fiscalyear_id.id}
411 if st.journal_id.sequence_id:
412 st_number = obj_seq.next_by_id(cr, uid, st.journal_id.sequence_id.id, context=c)
414 st_number = obj_seq.next_by_code(cr, uid, 'account.bank.statement', context=c)
416 for line in st.move_line_ids:
417 if line.state <> 'valid':
418 raise osv.except_osv(_('Error!'),
419 _('The account entries lines are not in valid state.'))
420 for st_line in st.line_ids:
421 if st_line.analytic_account_id:
422 if not st.journal_id.analytic_journal_id:
423 raise osv.except_osv(_('No Analytic Journal !'),_("You have to assign an analytic journal on the '%s' journal!") % (st.journal_id.name,))
424 if not st_line.amount:
426 st_line_number = self.get_next_st_line_number(cr, uid, st_number, st_line, context)
427 self.create_move_from_st_line(cr, uid, st_line.id, company_currency_id, st_line_number, context)
429 self.write(cr, uid, [st.id], {
431 'balance_end_real': st.balance_end
433 self.message_post(cr, uid, [st.id], body=_('Statement %s confirmed, journal items were created.') % (st_number,), context=context)
434 return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
436 def button_cancel(self, cr, uid, ids, context=None):
438 account_move_obj = self.pool.get('account.move')
439 for st in self.browse(cr, uid, ids, context=context):
440 if st.state=='draft':
443 for line in st.line_ids:
444 move_ids += [x.id for x in line.move_ids]
445 account_move_obj.button_cancel(cr, uid, move_ids, context=context)
446 account_move_obj.unlink(cr, uid, move_ids, context)
448 return self.write(cr, uid, done, {'state':'draft'}, context=context)
450 def _compute_balance_end_real(self, cr, uid, journal_id, context=None):
453 cr.execute('SELECT balance_end_real \
454 FROM account_bank_statement \
455 WHERE journal_id = %s AND NOT state = %s \
456 ORDER BY date DESC,id DESC LIMIT 1', (journal_id, 'draft'))
458 return res and res[0] or 0.0
460 def onchange_journal_id(self, cr, uid, statement_id, journal_id, context=None):
463 balance_start = self._compute_balance_end_real(cr, uid, journal_id, context=context)
465 journal_data = self.pool.get('account.journal').read(cr, uid, journal_id, ['company_id', 'currency'], context=context)
466 company_id = journal_data['company_id']
467 currency_id = journal_data['currency'] or self.pool.get('res.company').browse(cr, uid, company_id[0], context=context).currency_id.id
468 return {'value': {'balance_start': balance_start, 'company_id': company_id, 'currency': currency_id}}
470 def unlink(self, cr, uid, ids, context=None):
471 stat = self.read(cr, uid, ids, ['state'], context=context)
474 if t['state'] in ('draft'):
475 unlink_ids.append(t['id'])
477 raise osv.except_osv(_('Invalid Action!'), _('In order to delete a bank statement, you must first cancel it to delete related journal items.'))
478 osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
481 def copy(self, cr, uid, id, default=None, context=None):
486 default = default.copy()
487 default['move_line_ids'] = []
488 return super(account_bank_statement, self).copy(cr, uid, id, default, context=context)
490 def button_journal_entries(self, cr, uid, ids, context=None):
491 ctx = (context or {}).copy()
492 ctx['journal_id'] = self.browse(cr, uid, ids[0], context=context).journal_id.id
496 'res_model':'account.move.line',
498 'type':'ir.actions.act_window',
499 'domain':[('statement_id','in',ids)],
503 account_bank_statement()
505 class account_bank_statement_line(osv.osv):
507 def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
508 obj_partner = self.pool.get('res.partner')
513 part = obj_partner.browse(cr, uid, partner_id, context=context)
514 if not part.supplier and not part.customer:
516 elif part.supplier and part.customer:
519 if part.supplier == True:
521 if part.customer == True:
523 res_type = self.onchange_type(cr, uid, ids, partner_id=partner_id, type=type, context=context)
524 if res_type['value'] and res_type['value'].get('account_id', False):
525 return {'value': {'type': type, 'account_id': res_type['value']['account_id']}}
526 return {'value': {'type': type}}
528 def onchange_type(self, cr, uid, line_id, partner_id, type, context=None):
530 obj_partner = self.pool.get('res.partner')
536 line = self.browse(cr, uid, line_id, context=context)
537 if not line or (line and not line[0].account_id):
538 part = obj_partner.browse(cr, uid, partner_id, context=context)
539 if type == 'supplier':
540 account_id = part.property_account_payable.id
542 account_id = part.property_account_receivable.id
543 res['value']['account_id'] = account_id
546 _order = "statement_id desc, sequence"
547 _name = "account.bank.statement.line"
548 _description = "Bank Statement Line"
550 'name': fields.char('OBI', required=True, help="Originator to Beneficiary Information"),
551 'date': fields.date('Date', required=True),
552 'amount': fields.float('Amount', digits_compute=dp.get_precision('Account')),
553 'type': fields.selection([
554 ('supplier','Supplier'),
555 ('customer','Customer'),
556 ('general','General')
557 ], 'Type', required=True),
558 'partner_id': fields.many2one('res.partner', 'Partner'),
559 'account_id': fields.many2one('account.account','Account',
561 'statement_id': fields.many2one('account.bank.statement', 'Statement',
562 select=True, required=True, ondelete='cascade'),
563 'journal_id': fields.related('statement_id', 'journal_id', type='many2one', relation='account.journal', string='Journal', store=True, readonly=True),
564 'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
565 'move_ids': fields.many2many('account.move',
566 'account_bank_statement_line_move_rel', 'statement_line_id','move_id',
568 'ref': fields.char('Reference', size=32),
569 'note': fields.text('Notes'),
570 'sequence': fields.integer('Sequence', select=True, help="Gives the sequence order when displaying a list of bank statement lines."),
571 'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
574 'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
575 'date': lambda self,cr,uid,context={}: context.get('date', fields.date.context_today(self,cr,uid,context=context)),
579 account_bank_statement_line()
581 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: