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 osv import fields, osv
25 from tools.translate import _
26 import decimal_precision as dp
28 class account_bank_statement(osv.osv):
30 def create(self, cr, uid, vals, context=None):
32 if 'line_ids' in vals:
33 for line in vals['line_ids']:
35 line[2]['sequence'] = seq
37 return super(account_bank_statement, self).create(cr, uid, vals, context=context)
39 def write(self, cr, uid, ids, vals, context=None):
40 res = super(account_bank_statement, self).write(cr, uid, ids, vals, context=context)
41 account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
42 for statement in self.browse(cr, uid, ids, context):
44 for line in statement.line_ids:
47 account_bank_statement_line_obj.write(cr, uid, [line.id], {'sequence': seq}, context=context)
50 def button_import_invoice(self, cr, uid, ids, context=None):
51 mod_obj = self.pool.get('ir.model.data')
54 model_data_ids = mod_obj.search(cr, uid, [('model','=','ir.ui.view'),('name','=','view_account_statement_from_invoice')], context=context)
55 resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
56 context.update({'statement_id': ids[0]})
59 'name': _('Import Invoice'),
62 'view_mode': 'tree,form',
63 'res_model': 'account.statement.from.invoice',
64 'views': [(resource_id,'form')],
65 'type': 'ir.actions.act_window',
70 def _default_journal_id(self, cr, uid, context={}):
71 journal_pool = self.pool.get('account.journal')
72 journal_type = context.get('journal_type', False)
75 ids = journal_pool.search(cr, uid, [('type', '=', journal_type)])
80 def _default_balance_start(self, cr, uid, context={}):
81 cr.execute('select id from account_bank_statement where journal_id=%s order by date desc limit 1', (1,))
84 return self.browse(cr, uid, [res[0]], context)[0].balance_end
87 def _end_balance(self, cursor, user, ids, name, attr, context=None):
88 res_currency_obj = self.pool.get('res.currency')
89 res_users_obj = self.pool.get('res.users')
92 company_currency_id = res_users_obj.browse(cursor, user, user,
93 context=context).company_id.currency_id.id
95 statements = self.browse(cursor, user, ids, context=context)
96 for statement in statements:
97 res[statement.id] = statement.balance_start
98 currency_id = statement.currency.id
99 for line in statement.move_line_ids:
101 if line.account_id.id == \
102 statement.journal_id.default_debit_account_id.id:
103 res[statement.id] += res_currency_obj.compute(cursor,
104 user, company_currency_id, currency_id,
105 line.debit, context=context)
107 if line.account_id.id == \
108 statement.journal_id.default_credit_account_id.id:
109 res[statement.id] -= res_currency_obj.compute(cursor,
110 user, company_currency_id, currency_id,
111 line.credit, context=context)
112 if statement.state == 'draft':
113 for line in statement.line_ids:
114 res[statement.id] += line.amount
116 res[r] = round(res[r], 2)
119 def _get_period(self, cr, uid, context={}):
120 periods = self.pool.get('account.period').find(cr, uid)
125 def _currency(self, cursor, user, ids, name, args, context=None):
127 res_currency_obj = self.pool.get('res.currency')
128 res_users_obj = self.pool.get('res.users')
129 default_currency = res_users_obj.browse(cursor, user,
130 user, context=context).company_id.currency_id
131 for statement in self.browse(cursor, user, ids, context=context):
132 currency = statement.journal_id.currency
134 currency = default_currency
135 res[statement.id] = currency.id
137 for currency_id, currency_name in res_currency_obj.name_get(cursor,
138 user, [x for x in res.values()], context=context):
139 currency_names[currency_id] = currency_name
140 for statement_id in res.keys():
141 currency_id = res[statement_id]
142 res[statement_id] = (currency_id, currency_names[currency_id])
146 _name = "account.bank.statement"
147 _description = "Bank Statement"
149 'name': fields.char('Name', size=64, required=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', states={'confirm': [('readonly', True)]}),
150 'date': fields.date('Date', required=True, states={'confirm': [('readonly', True)]}),
151 'journal_id': fields.many2one('account.journal', 'Journal', required=True,
152 readonly=True, states={'draft':[('readonly',False)]}),
153 'period_id': fields.many2one('account.period', 'Period', required=True,
154 states={'confirm':[('readonly', True)]}),
155 'balance_start': fields.float('Starting Balance', digits_compute=dp.get_precision('Account'),
156 states={'confirm':[('readonly',True)]}),
157 'balance_end_real': fields.float('Ending Balance', digits_compute=dp.get_precision('Account'),
158 states={'confirm':[('readonly', True)]}),
159 'balance_end': fields.function(_end_balance, method=True, string='Balance'),
160 'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
161 'line_ids': fields.one2many('account.bank.statement.line',
162 'statement_id', 'Statement lines',
163 states={'confirm':[('readonly', True)]}),
164 'move_line_ids': fields.one2many('account.move.line', 'statement_id',
165 'Entry lines', states={'confirm':[('readonly',True)]}),
166 'state': fields.selection([('draft', 'Draft'),('confirm', 'Confirmed')],
167 'State', required=True,
168 states={'confirm': [('readonly', True)]}, readonly="1",
169 help='When new statement is created the state will be \'Draft\'. \
170 \n* And after getting confirmation from the bank it will be in \'Confirmed\' state.'),
171 'currency': fields.function(_currency, method=True, string='Currency',
172 type='many2one', relation='res.currency'),
177 'date': time.strftime('%Y-%m-%d'),
179 'balance_start': _default_balance_start,
180 'journal_id': _default_journal_id,
181 'period_id': _get_period,
184 def onchange_date(self, cr, user, ids, date, context=None):
186 Returns a dict that contains new values and context
187 @param cr: A database cursor
188 @param user: ID of the user currently logged in
189 @param date: latest value from user input for field date
190 @param args: other arguments
191 @param context: context arguments, like lang, time zone
192 @return: Returns a dict which contains new values, and context
195 period_pool = self.pool.get('account.period')
200 pids = period_pool.search(cr, user, [('date_start','<=',date), ('date_stop','>=',date)])
214 def button_dummy(self, cr, uid, ids, context=None):
215 return self.write(cr, uid, ids, {}, context=context)
217 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, st_line_number, context=None):
218 res_currency_obj = self.pool.get('res.currency')
219 account_move_obj = self.pool.get('account.move')
220 account_move_line_obj = self.pool.get('account.move.line')
221 account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
222 st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context)
223 st = st_line.statement_id
225 context.update({'date': st_line.date})
227 move_id = account_move_obj.create(cr, uid, {
228 'journal_id': st.journal_id.id,
229 'period_id': st.period_id.id,
230 'date': st_line.date,
231 'name': st_line_number,
233 account_bank_statement_line_obj.write(cr, uid, [st_line.id], {
234 'move_ids': [(4, move_id, False)]
238 if st_line.amount >= 0:
239 account_id = st.journal_id.default_credit_account_id.id
241 account_id = st.journal_id.default_debit_account_id.id
243 acc_cur = ((st_line.amount<=0) and st.journal_id.default_debit_account_id) or st_line.account_id
244 amount = res_currency_obj.compute(cr, uid, st.currency.id,
245 company_currency_id, st_line.amount, context=context,
249 'name': st_line.name,
250 'date': st_line.date,
253 'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
254 'account_id': (st_line.account_id) and st_line.account_id.id,
255 'credit': ((amount>0) and amount) or 0.0,
256 'debit': ((amount<0) and -amount) or 0.0,
257 'statement_id': st.id,
258 'journal_id': st.journal_id.id,
259 'period_id': st.period_id.id,
260 'currency_id': st.currency.id,
261 'analytic_account_id': st_line.analytic_account_id and st_line.analytic_account_id.id or False
264 amount = res_currency_obj.compute(cr, uid, st.currency.id,
265 company_currency_id, st_line.amount, context=context,
267 if st.currency.id <> company_currency_id:
268 amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
269 st.currency.id, amount, context=context,
271 val['amount_currency'] = -amount_cur
273 if st_line.account_id and st_line.account_id.currency_id and st_line.account_id.currency_id.id <> company_currency_id:
274 val['currency_id'] = st_line.account_id.currency_id.id
275 if company_currency_id==st_line.account_id.currency_id.id:
276 amount_cur = st_line.amount
278 amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
279 st_line.account_id.currency_id.id, amount, context=context,
281 val['amount_currency'] = amount_cur
283 move_line_id = account_move_line_obj.create(cr, uid, val, context=context)
284 torec.append(move_line_id)
286 # Fill the secondary amount/currency
287 # if currency is not the same than the company
288 amount_currency = False
290 if st.currency.id <> company_currency_id:
291 amount_currency = st_line.amount
292 currency_id = st.currency.id
293 account_move_line_obj.create(cr, uid, {
294 'name': st_line.name,
295 'date': st_line.date,
298 'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
299 'account_id': account_id,
300 'credit': ((amount < 0) and -amount) or 0.0,
301 'debit': ((amount > 0) and amount) or 0.0,
302 'statement_id': st.id,
303 'journal_id': st.journal_id.id,
304 'period_id': st.period_id.id,
305 'amount_currency': amount_currency,
306 'currency_id': currency_id,
309 for line in account_move_line_obj.browse(cr, uid, [x.id for x in
310 account_move_obj.browse(cr, uid, move_id,
311 context=context).line_id],
313 if line.state <> 'valid':
314 raise osv.except_osv(_('Error !'),
315 _('Journal Item "%s" is not valid') % line.name)
317 # Bank statements will not consider boolean on journal entry_posted
318 account_move_obj.post(cr, uid, [move_id], context=context)
321 def get_next_st_line_number(self, cr, uid, st_number, st_line, context=None):
322 return st_number + ' - ' + str(st_line.sequence)
324 def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
325 st = self.browse(cr, uid, st_id, context)
326 if not (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001):
327 raise osv.except_osv(_('Error !'),
328 _('The statement balance is incorrect !\n') +
329 _('The expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
332 def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
333 return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
335 def check_status_condition(self, cr, uid, state, journal_type='bank'):
336 return state=='draft'
338 def button_confirm_bank(self, cr, uid, ids, context=None):
340 obj_seq = self.pool.get('ir.sequence')
344 for st in self.browse(cr, uid, ids, context):
345 j_type = st.journal_id.type
346 company_currency_id = st.journal_id.company_id.currency_id.id
347 if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
350 self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
351 if (not st.journal_id.default_credit_account_id) \
352 or (not st.journal_id.default_debit_account_id):
353 raise osv.except_osv(_('Configuration Error !'),
354 _('Please verify that an account is defined in the journal.'))
356 if not st.name == '/':
359 if st.journal_id.sequence_id:
360 c = {'fiscalyear_id': st.period_id.fiscalyear_id.id}
361 st_number = obj_seq.get_id(cr, uid, st.journal_id.sequence_id.id, context=c)
363 st_number = obj_seq.get(cr, uid, 'account.bank.statement')
365 for line in st.move_line_ids:
366 if line.state <> 'valid':
367 raise osv.except_osv(_('Error !'),
368 _('The account entries lines are not in valid state.'))
369 for st_line in st.line_ids:
370 if st_line.analytic_account_id:
371 if not st.journal_id.analytic_journal_id:
372 raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (st.journal_id.name,))
373 if not st_line.amount:
375 st_line_number = self.get_next_st_line_number(cr, uid, st_number, st_line, context)
376 self.create_move_from_st_line(cr, uid, st_line.id, company_currency_id, st_line_number, context)
378 self.write(cr, uid, [st.id], {'name': st_number}, context=context)
379 self.log(cr, uid, st.id, _('Statement %s is confirmed, journal items are created.') % (st_number,))
381 return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
383 def button_cancel(self, cr, uid, ids, context=None):
385 account_move_obj = self.pool.get('account.move')
386 for st in self.browse(cr, uid, ids, context):
387 if st.state=='draft':
390 for line in st.line_ids:
391 ids += [x.id for x in line.move_ids]
392 account_move_obj.unlink(cr, uid, ids, context)
394 return self.write(cr, uid, done, {'state':'draft'}, context=context)
396 def onchange_journal_id(self, cursor, user, statement_id, journal_id, context=None):
397 cursor.execute('SELECT balance_end_real \
398 FROM account_bank_statement \
399 WHERE journal_id = %s AND NOT state = %s \
400 ORDER BY date DESC,id DESC LIMIT 1', (journal_id, 'draft'))
401 res = cursor.fetchone()
402 balance_start = res and res[0] or 0.0
403 return {'value': {'balance_start': balance_start}}
405 def unlink(self, cr, uid, ids, context=None):
406 stat = self.read(cr, uid, ids, ['state'])
409 if t['state'] in ('draft'):
410 unlink_ids.append(t['id'])
412 raise osv.except_osv(_('Invalid action !'), _('Cannot delete bank statement(s) which are already confirmed !'))
413 osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
416 def copy(self, cr, uid, id, default=None, context=None):
421 default = default.copy()
422 default['move_line_ids'] = []
423 return super(account_bank_statement, self).copy(cr, uid, id, default, context=context)
425 account_bank_statement()
427 class account_bank_statement_line(osv.osv):
429 def onchange_partner_id(self, cursor, user, line_id, partner_id, type, currency_id, context=None):
430 res_users_obj = self.pool.get('res.users')
431 res_currency_obj = self.pool.get('res.currency')
433 obj_partner = self.pool.get('res.partner')
439 line = self.browse(cursor, user, line_id)
440 if not line or (line and not line[0].account_id):
441 part = obj_partner.browse(cursor, user, partner_id, context=context)
442 if type == 'supplier':
443 account_id = part.property_account_payable.id
445 account_id = part.property_account_receivable.id
446 res['value']['account_id'] = account_id
448 if account_id and (not line or (line and not line[0].amount)) and not context.get('amount', False):
449 company_currency_id = res_users_obj.browse(cursor, user, user,
450 context=context).company_id.currency_id.id
452 currency_id = company_currency_id
454 cursor.execute('SELECT sum(debit-credit) \
455 FROM account_move_line \
456 WHERE (reconcile_id is null) \
457 AND partner_id = %s \
458 AND account_id=%s', (partner_id, account_id))
459 pgres = cursor.fetchone()
460 balance = pgres and pgres[0] or 0.0
462 balance = res_currency_obj.compute(cursor, user, company_currency_id,
463 currency_id, balance, context=context)
464 res['value']['amount'] = balance
467 _order = "statement_id desc, sequence"
468 _name = "account.bank.statement.line"
469 _description = "Bank Statement Line"
471 'name': fields.char('Name', size=64, required=True),
472 'date': fields.date('Date', required=True),
473 'amount': fields.float('Amount'),
474 'type': fields.selection([
475 ('supplier','Supplier'),
476 ('customer','Customer'),
477 ('general','General')
478 ], 'Type', required=True),
479 'partner_id': fields.many2one('res.partner', 'Partner'),
480 'account_id': fields.many2one('account.account','Account',
482 'statement_id': fields.many2one('account.bank.statement', 'Statement',
483 select=True, required=True, ondelete='cascade'),
484 'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
485 'move_ids': fields.many2many('account.move',
486 'account_bank_statement_line_move_rel', 'move_id','statement_id',
488 'ref': fields.char('Reference', size=32),
489 'note': fields.text('Notes'),
490 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of bank statement lines."),
491 'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
494 'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
495 'date': time.strftime('%Y-%m-%d'),
499 account_bank_statement_line()
501 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: