diff --git a/account_advanced_reconcile/__openerp__.py b/account_advanced_reconcile/__openerp__.py
index b1ede930..5c45353c 100644
--- a/account_advanced_reconcile/__openerp__.py
+++ b/account_advanced_reconcile/__openerp__.py
@@ -64,9 +64,9 @@ The base class to find the reconciliations is built to be as efficient as
possible.
So basically, if you have an invoice with 3 payments (one per month), the first
-month, it will partial reconcile the debit move line with the first payment, the second
-month, it will partial reconcile the debit move line with 2 first payments,
-the third month, it will make the full reconciliation.
+month, it will partial reconcile the debit move line with the first payment, the
+second month, it will partial reconcile the debit move line with 2 first
+payments, the third month, it will make the full reconciliation.
This module is perfectly adapted for E-Commerce business where a big volume of
move lines and so, reconciliations, are involved and payments often come from
@@ -82,4 +82,4 @@ many offices.
'auto_install': False,
'license': 'AGPL-3',
'application': True,
-}
+ }
diff --git a/account_advanced_reconcile/base_advanced_reconciliation.py b/account_advanced_reconcile/base_advanced_reconciliation.py
index 497aee92..e6f8ced9 100644
--- a/account_advanced_reconcile/base_advanced_reconciliation.py
+++ b/account_advanced_reconcile/base_advanced_reconciliation.py
@@ -24,13 +24,13 @@ import logging
from itertools import product
from openerp.osv import orm
from openerp import pooler
+from openerp.tools.translate import _
_logger = logging.getLogger(__name__)
class easy_reconcile_advanced(orm.AbstractModel):
-
_name = 'easy.reconcile.advanced'
_inherit = 'easy.reconcile.base'
@@ -40,11 +40,8 @@ class easy_reconcile_advanced(orm.AbstractModel):
sql_from = self._from(rec)
where, params = self._where(rec)
where += " AND account_move_line.debit > 0 "
-
where2, params2 = self._get_filter(cr, uid, rec, context=context)
-
query = ' '.join((select, sql_from, where, where2))
-
cr.execute(query, params + params2)
return cr.dictfetchall()
@@ -54,11 +51,8 @@ class easy_reconcile_advanced(orm.AbstractModel):
sql_from = self._from(rec)
where, params = self._where(rec)
where += " AND account_move_line.credit > 0 "
-
where2, params2 = self._get_filter(cr, uid, rec, context=context)
-
query = ' '.join((select, sql_from, where, where2))
-
cr.execute(query, params + params2)
return cr.dictfetchall()
@@ -176,14 +170,15 @@ class easy_reconcile_advanced(orm.AbstractModel):
"""
mkey, mvalue = matcher
omkey, omvalue = opposite_matcher
- assert mkey == omkey, ("A matcher %s is compared with a matcher %s, "
- " the _matchers and _opposite_matchers are probably wrong" %
- (mkey, omkey))
+ assert mkey == omkey, \
+ (_("A matcher %s is compared with a matcher %s, the _matchers and "
+ "_opposite_matchers are probably wrong") % (mkey, omkey))
if not isinstance(mvalue, (list, tuple)):
mvalue = mvalue,
if not isinstance(omvalue, (list, tuple)):
omvalue = omvalue,
- return easy_reconcile_advanced._compare_matcher_values(mkey, mvalue, omvalue)
+ return easy_reconcile_advanced._compare_matcher_values(mkey, mvalue,
+ omvalue)
def _compare_opposite(self, cr, uid, rec, move_line, opposite_move_line,
matchers, context=None):
@@ -194,7 +189,7 @@ class easy_reconcile_advanced(orm.AbstractModel):
they are candidate for a reconciliation.
"""
opp_matchers = self._opposite_matchers(cr, uid, rec, opposite_move_line,
- context=context)
+ context=context)
for matcher in matchers:
try:
opp_matcher = opp_matchers.next()
@@ -212,13 +207,13 @@ class easy_reconcile_advanced(orm.AbstractModel):
return True
- def _search_opposites(self, cr, uid, rec, move_line, opposite_move_lines, context=None):
- """
- Search the opposite move lines for a move line
+ def _search_opposites(self, cr, uid, rec, move_line, opposite_move_lines,
+ context=None):
+ """Search the opposite move lines for a move line
:param dict move_line: the move line for which we search opposites
- :param list opposite_move_lines: list of dict of move lines values, the move
- lines we want to search for
+ :param list opposite_move_lines: list of dict of move lines values,
+ the move lines we want to search for
:return: list of matching lines
"""
matchers = self._matchers(cr, uid, rec, move_line, context=context)
@@ -237,7 +232,6 @@ class easy_reconcile_advanced(orm.AbstractModel):
ctx['commit_every'] = (
rec.journal_id.company_id.reconciliation_commit_every
)
-
if ctx['commit_every']:
new_cr = pooler.get_db(cr.dbname).cursor()
else:
@@ -261,27 +255,23 @@ class easy_reconcile_advanced(orm.AbstractModel):
"""
return False
- def _rec_auto_lines_advanced(self, cr, uid, rec, credit_lines, debit_lines, context=None):
+ def _rec_auto_lines_advanced(self, cr, uid, rec, credit_lines, debit_lines,
+ context=None):
""" Advanced reconciliation main loop """
reconciled_ids = []
partial_reconciled_ids = []
reconcile_groups = []
-
_logger.info("%d credit lines to reconcile", len(credit_lines))
-
for idx, credit_line in enumerate(credit_lines, start=1):
if idx % 50 == 0:
_logger.info("... %d/%d credit lines inspected ...", idx,
len(credit_lines))
if self._skip_line(cr, uid, rec, credit_line, context=context):
continue
-
opposite_lines = self._search_opposites(
cr, uid, rec, credit_line, debit_lines, context=context)
-
if not opposite_lines:
continue
-
opposite_ids = [l['id'] for l in opposite_lines]
line_ids = opposite_ids + [credit_line['id']]
for group in reconcile_groups:
@@ -293,18 +283,13 @@ class easy_reconcile_advanced(orm.AbstractModel):
else:
_logger.debug("New group of lines matched %s", line_ids)
reconcile_groups.append(set(line_ids))
-
lines_by_id = dict([(l['id'], l) for l in credit_lines + debit_lines])
-
_logger.info("Found %d groups to reconcile", len(reconcile_groups))
-
for group_count, reconcile_group_ids in enumerate(reconcile_groups,
start=1):
-
_logger.debug("Reconciling group %d/%d with ids %s",
group_count, len(reconcile_groups),
reconcile_group_ids)
-
group_lines = [lines_by_id[lid] for lid in reconcile_group_ids]
reconciled, full = self._reconcile_lines(
cr, uid, rec, group_lines, allow_partial=True, context=context)
@@ -313,15 +298,10 @@ class easy_reconcile_advanced(orm.AbstractModel):
elif reconciled:
partial_reconciled_ids += reconcile_group_ids
- if (
- context['commit_every']
- and group_count % context['commit_every'] == 0
- ):
+ if (context['commit_every'] and
+ group_count % context['commit_every'] == 0):
cr.commit()
-
_logger.info("Commit the reconciliations after %d groups",
group_count)
-
_logger.info("Reconciliation is over")
-
return reconciled_ids, partial_reconciled_ids
diff --git a/account_advanced_reconcile_transaction_ref/__openerp__.py b/account_advanced_reconcile_transaction_ref/__openerp__.py
index d2b0d1cc..16be799a 100644
--- a/account_advanced_reconcile_transaction_ref/__openerp__.py
+++ b/account_advanced_reconcile_transaction_ref/__openerp__.py
@@ -19,7 +19,7 @@
##############################################################################
{'name': 'Advanced Reconcile Transaction Ref',
- 'description': """
+ 'description': """
Advanced reconciliation method for the module account_advanced_reconcile
========================================================================
Reconcile rules with transaction_ref
@@ -32,9 +32,8 @@ Reconcile rules with transaction_ref
'depends': ['account_advanced_reconcile'],
'data': ['easy_reconcile_view.xml'],
'demo': [],
- 'test': [], # To be ported or migrate to unit tests or scenarios
+ 'test': [], # To be ported or migrate to unit tests or scenarios
'auto_install': False,
'installable': True,
'images': []
-}
-# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
+ }
diff --git a/account_advanced_reconcile_transaction_ref/advanced_reconciliation.py b/account_advanced_reconcile_transaction_ref/advanced_reconciliation.py
index c104cbb3..cf875ff4 100644
--- a/account_advanced_reconcile_transaction_ref/advanced_reconciliation.py
+++ b/account_advanced_reconcile_transaction_ref/advanced_reconciliation.py
@@ -19,7 +19,7 @@
##############################################################################
from openerp.osv import orm
-
+
class easy_reconcile_advanced_transaction_ref(orm.TransientModel):
@@ -35,10 +35,10 @@ class easy_reconcile_advanced_transaction_ref(orm.TransientModel):
return not (move_line.get('transaction_ref') and
move_line.get('partner_id'))
- def _matchers(self, cr, uid, rec, move_line, context=None):
+ def _matchers(self, cr, uid, rec, move_line, context=None):
return (('partner_id', move_line['partner_id']),
('ref', move_line['transaction_ref'].lower().strip()))
-
+
def _opposite_matchers(self, cr, uid, rec, move_line, context=None):
yield ('partner_id', move_line['partner_id'])
yield ('ref', (move_line['transaction_ref'] or '').lower().strip())
diff --git a/account_advanced_reconcile_transaction_ref/base_advanced_reconciliation.py b/account_advanced_reconcile_transaction_ref/base_advanced_reconciliation.py
index 25e6c4e9..c5feb2ac 100644
--- a/account_advanced_reconcile_transaction_ref/base_advanced_reconciliation.py
+++ b/account_advanced_reconcile_transaction_ref/base_advanced_reconciliation.py
@@ -19,14 +19,13 @@
#
##############################################################################
-from itertools import product
from openerp.osv import orm
-class easy_reconcile_advanced(orm.AbstractModel):
+class EasyReconcileAdvanced(orm.AbstractModel):
_inherit = 'easy.reconcile.advanced'
-
+
def _base_columns(self, rec):
""" Mandatory columns for move lines queries
An extra column aliased as ``key`` should be defined
@@ -43,4 +42,4 @@ class easy_reconcile_advanced(orm.AbstractModel):
'account_id',
'move_id',
'transaction_ref')
- return ["account_move_line.%s" % col for col in aml_cols]
+ return ["account_move_line.%s" % col for col in aml_cols]
diff --git a/account_advanced_reconcile_transaction_ref/easy_reconcile.py b/account_advanced_reconcile_transaction_ref/easy_reconcile.py
index 92930446..07d43df2 100644
--- a/account_advanced_reconcile_transaction_ref/easy_reconcile.py
+++ b/account_advanced_reconcile_transaction_ref/easy_reconcile.py
@@ -36,4 +36,3 @@ class account_easy_reconcile_method(orm.Model):
'Advanced. Partner and Transaction Ref. vs Ref.'),
]
return methods
-
diff --git a/account_easy_reconcile/base_reconciliation.py b/account_easy_reconcile/base_reconciliation.py
index b5b40542..6145720a 100644
--- a/account_easy_reconcile/base_reconciliation.py
+++ b/account_easy_reconcile/base_reconciliation.py
@@ -23,7 +23,8 @@ from openerp.osv import fields, orm
from operator import itemgetter, attrgetter
-class easy_reconcile_base(orm.AbstractModel):
+class EasyReconcileBase(orm.AbstractModel):
+
"""Abstract Model for reconciliation methods"""
_name = 'easy.reconcile.base'
@@ -87,7 +88,6 @@ class easy_reconcile_base(orm.AbstractModel):
# which returns a list, we have to
# accomodate with that
params = [rec.account_id.id]
-
if rec.partner_ids:
where += " AND account_move_line.partner_id IN %s"
params.append(tuple([l.id for l in rec.partner_ids]))
@@ -112,17 +112,16 @@ class easy_reconcile_base(orm.AbstractModel):
sums = reduce(
lambda line, memo:
dict((key, value + memo[key])
- for key, value
- in line.iteritems()
- if key in keys), lines)
-
+ for key, value
+ in line.iteritems()
+ if key in keys), lines)
debit, credit = sums['debit'], sums['credit']
writeoff_amount = round(debit - credit, precision)
return bool(writeoff_limit >= abs(writeoff_amount)), debit, credit
def _get_rec_date(self, cr, uid, rec, lines,
based_on='end_period_last_credit', context=None):
- period_obj = self.pool.get('account.period')
+ period_obj = self.pool['account.period']
def last_period(mlines):
period_ids = [ml['period_id'] for ml in mlines]
@@ -153,7 +152,8 @@ class easy_reconcile_base(orm.AbstractModel):
# when date is None
return None
- def _reconcile_lines(self, cr, uid, rec, lines, allow_partial=False, context=None):
+ def _reconcile_lines(self, cr, uid, rec, lines, allow_partial=False,
+ context=None):
""" Try to reconcile given lines
:param list lines: list of dict of move lines, they must at least
@@ -168,29 +168,23 @@ class easy_reconcile_base(orm.AbstractModel):
"""
if context is None:
context = {}
-
ml_obj = self.pool.get('account.move.line')
writeoff = rec.write_off
-
line_ids = [l['id'] for l in lines]
below_writeoff, sum_debit, sum_credit = self._below_writeoff_limit(
cr, uid, rec, lines, writeoff, context=context)
date = self._get_rec_date(
cr, uid, rec, lines, rec.date_base_on, context=context)
-
rec_ctx = dict(context, date_p=date)
if below_writeoff:
if sum_credit < sum_debit:
writeoff_account_id = rec.account_profit_id.id
else:
writeoff_account_id = rec.account_lost_id.id
-
period_id = self.pool.get('account.period').find(
cr, uid, dt=date, context=context)[0]
-
if rec.analytic_account_id:
rec_ctx['analytic_id'] = rec.analytic_account_id.id
-
ml_obj.reconcile(
cr, uid,
line_ids,
@@ -207,5 +201,4 @@ class easy_reconcile_base(orm.AbstractModel):
type='manual',
context=rec_ctx)
return True, False
-
return False, False
diff --git a/account_easy_reconcile/easy_reconcile.py b/account_easy_reconcile/easy_reconcile.py
index fd5e4848..99ed960f 100644
--- a/account_easy_reconcile/easy_reconcile.py
+++ b/account_easy_reconcile/easy_reconcile.py
@@ -19,13 +19,11 @@
#
##############################################################################
-from openerp.osv import fields, osv, orm
-from openerp.tools.translate import _
-from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
+from openerp.osv import fields, orm
from openerp.tools.translate import _
-class easy_reconcile_options(orm.AbstractModel):
+class EasyReconcileOptions(orm.AbstractModel):
"""Options of a reconciliation profile
Columns shared by the configuration of methods
@@ -37,29 +35,31 @@ class easy_reconcile_options(orm.AbstractModel):
_name = 'easy.reconcile.options'
def _get_rec_base_date(self, cr, uid, context=None):
- return [('end_period_last_credit', 'End of period of most recent credit'),
- ('newest', 'Most recent move line'),
- ('actual', 'Today'),
- ('end_period', 'End of period of most recent move line'),
- ('newest_credit', 'Date of most recent credit'),
- ('newest_debit', 'Date of most recent debit')]
+ return [
+ ('end_period_last_credit', 'End of period of most recent credit'),
+ ('newest', 'Most recent move line'),
+ ('actual', 'Today'),
+ ('end_period', 'End of period of most recent move line'),
+ ('newest_credit', 'Date of most recent credit'),
+ ('newest_debit', 'Date of most recent debit')
+ ]
_columns = {
- 'write_off': fields.float('Write off allowed'),
- 'account_lost_id': fields.many2one(
- 'account.account', 'Account Lost'),
- 'account_profit_id': fields.many2one(
- 'account.account', 'Account Profit'),
- 'journal_id': fields.many2one(
- 'account.journal', 'Journal'),
- 'date_base_on': fields.selection(
- _get_rec_base_date,
- required=True,
- string='Date of reconciliation'),
- 'filter': fields.char('Filter', size=128),
- 'analytic_account_id': fields.many2one(
- 'account.analytic.account', 'Analytic Account',
- help="Analytic account for the write-off"),
+ 'write_off': fields.float('Write off allowed'),
+ 'account_lost_id': fields.many2one(
+ 'account.account', 'Account Lost'),
+ 'account_profit_id': fields.many2one(
+ 'account.account', 'Account Profit'),
+ 'journal_id': fields.many2one(
+ 'account.journal', 'Journal'),
+ 'date_base_on': fields.selection(
+ _get_rec_base_date,
+ required=True,
+ string='Date of reconciliation'),
+ 'filter': fields.char('Filter', size=128),
+ 'analytic_account_id': fields.many2one(
+ 'account.analytic.account', 'Analytic Account',
+ help="Analytic account for the write-off"),
}
_defaults = {
@@ -68,44 +68,42 @@ class easy_reconcile_options(orm.AbstractModel):
}
-class account_easy_reconcile_method(orm.Model):
-
+class AccountEasyReconcileMethod(orm.Model):
_name = 'account.easy.reconcile.method'
_description = 'reconcile method for account_easy_reconcile'
-
_inherit = 'easy.reconcile.options'
-
_order = 'sequence'
def _get_all_rec_method(self, cr, uid, context=None):
return [
('easy.reconcile.simple.name', 'Simple. Amount and Name'),
('easy.reconcile.simple.partner', 'Simple. Amount and Partner'),
- ('easy.reconcile.simple.reference', 'Simple. Amount and Reference'),
- ]
+ ('easy.reconcile.simple.reference',
+ 'Simple. Amount and Reference'),
+ ]
def _get_rec_method(self, cr, uid, context=None):
return self._get_all_rec_method(cr, uid, context=None)
_columns = {
- 'name': fields.selection(
- _get_rec_method, 'Type', required=True),
- 'sequence': fields.integer(
- 'Sequence',
- required=True,
- help="The sequence field is used to order "
- "the reconcile method"),
- 'task_id': fields.many2one(
- 'account.easy.reconcile',
- string='Task',
- required=True,
- ondelete='cascade'),
- 'company_id': fields.related('task_id','company_id',
- relation='res.company',
- type='many2one',
- string='Company',
- store=True,
- readonly=True),
+ 'name': fields.selection(
+ _get_rec_method, 'Type', required=True),
+ 'sequence': fields.integer(
+ 'Sequence',
+ required=True,
+ help="The sequence field is used to order "
+ "the reconcile method"),
+ 'task_id': fields.many2one(
+ 'account.easy.reconcile',
+ string='Task',
+ required=True,
+ ondelete='cascade'),
+ 'company_id': fields.related('task_id', 'company_id',
+ relation='res.company',
+ type='many2one',
+ string='Company',
+ store=True,
+ readonly=True),
}
_defaults = {
@@ -130,7 +128,7 @@ class account_easy_reconcile_method(orm.Model):
""")
-class account_easy_reconcile(orm.Model):
+class AccountEasyReconcile(orm.Model):
_name = 'account.easy.reconcile'
_description = 'account easy reconcile'
@@ -240,9 +238,9 @@ class account_easy_reconcile(orm.Model):
all_ml_partial_ids += ml_partial_ids
reconcile_ids = find_reconcile_ids(
- 'reconcile_id', all_ml_rec_ids)
+ 'reconcile_id', all_ml_rec_ids)
partial_ids = find_reconcile_ids(
- 'reconcile_partial_id', all_ml_partial_ids)
+ 'reconcile_partial_id', all_ml_partial_ids)
self.pool.get('easy.reconcile.history').create(
cr,
@@ -259,11 +257,11 @@ class account_easy_reconcile(orm.Model):
be called when there is no history on the reconciliation
task.
"""
- raise osv.except_osv(
- _('Error'),
- _('There is no history of reconciled '
- 'items on the task: %s.') % rec.name)
-
+ raise orm.except_orm(
+ _('Error'),
+ _('There is no history of reconciled '
+ 'items on the task: %s.') % rec.name)
+
def _open_move_line_list(sefl, cr, uid, move_line_ids, name, context=None):
return {
'name': name,
@@ -275,19 +273,15 @@ class account_easy_reconcile(orm.Model):
'nodestroy': True,
'target': 'current',
'domain': unicode([('id', 'in', move_line_ids)]),
- }
+ }
def open_unreconcile(self, cr, uid, ids, context=None):
- """ Open the view of move line with the unreconciled move lines
- """
-
- assert len(ids) == 1 , \
- "You can only open entries from one profile at a time"
-
+ """ Open the view of move line with the unreconciled move lines"""
+ assert len(ids) == 1, \
+ "You can only open entries from one profile at a time"
obj_move_line = self.pool.get('account.move.line')
- res = {}
for task in self.browse(cr, uid, ids, context=context):
- line_ids = obj_move_line.search(
+ line_ids = obj_move_line.search(
cr, uid,
[('account_id', '=', task.account.id),
('reconcile_id', '=', False),
@@ -295,26 +289,24 @@ class account_easy_reconcile(orm.Model):
context=context)
name = _('Unreconciled items')
- return self._open_move_line_list(cr, uid, line_ids, name, context=context)
+ return self._open_move_line_list(cr, uid, line_ids, name,
+ context=context)
def open_partial_reconcile(self, cr, uid, ids, context=None):
- """ Open the view of move line with the unreconciled move lines
- """
-
- assert len(ids) == 1 , \
- "You can only open entries from one profile at a time"
-
+ """ Open the view of move line with the unreconciled move lines"""
+ assert len(ids) == 1, \
+ "You can only open entries from one profile at a time"
obj_move_line = self.pool.get('account.move.line')
- res = {}
for task in self.browse(cr, uid, ids, context=context):
- line_ids = obj_move_line.search(
+ line_ids = obj_move_line.search(
cr, uid,
[('account_id', '=', task.account.id),
('reconcile_id', '=', False),
('reconcile_partial_id', '!=', False)],
context=context)
name = _('Partial reconciled items')
- return self._open_move_line_list(cr, uid, line_ids, name, context=context)
+ return self._open_move_line_list(cr, uid, line_ids, name,
+ context=context)
def last_history_reconcile(self, cr, uid, rec_id, context=None):
""" Get the last history record for this reconciliation profile
@@ -322,7 +314,7 @@ class account_easy_reconcile(orm.Model):
"""
if isinstance(rec_id, (tuple, list)):
assert len(rec_id) == 1, \
- "Only 1 id expected"
+ "Only 1 id expected"
rec_id = rec_id[0]
rec = self.browse(cr, uid, rec_id, context=context)
if not rec.last_history:
@@ -335,7 +327,7 @@ class account_easy_reconcile(orm.Model):
"""
if isinstance(rec_id, (tuple, list)):
assert len(rec_id) == 1, \
- "Only 1 id expected"
+ "Only 1 id expected"
rec_id = rec_id[0]
rec = self.browse(cr, uid, rec_id, context=context)
if not rec.last_history:
diff --git a/account_easy_reconcile/easy_reconcile_history.py b/account_easy_reconcile/easy_reconcile_history.py
index b143e9ce..67581cb7 100644
--- a/account_easy_reconcile/easy_reconcile_history.py
+++ b/account_easy_reconcile/easy_reconcile_history.py
@@ -23,7 +23,7 @@ from openerp.osv import orm, fields
from openerp.tools.translate import _
-class easy_reconcile_history(orm.Model):
+class EasyReconcileHistory(orm.Model):
""" Store an history of the runs per profile
Each history stores the list of reconciliations done"""
@@ -33,46 +33,43 @@ class easy_reconcile_history(orm.Model):
def _reconcile_line_ids(self, cr, uid, ids, name, args, context=None):
result = {}
-
for history in self.browse(cr, uid, ids, context=context):
result[history.id] = {}
-
move_line_ids = []
for reconcile in history.reconcile_ids:
move_line_ids += [line.id
- for line
- in reconcile.line_id]
+ for line
+ in reconcile.line_id]
result[history.id]['reconcile_line_ids'] = move_line_ids
move_line_ids = []
for reconcile in history.reconcile_partial_ids:
move_line_ids += [line.id
- for line
- in reconcile.line_partial_ids]
+ for line
+ in reconcile.line_partial_ids]
result[history.id]['partial_line_ids'] = move_line_ids
-
return result
_columns = {
- 'easy_reconcile_id': fields.many2one(
- 'account.easy.reconcile', 'Reconcile Profile', readonly=True),
- 'date': fields.datetime('Run date', readonly=True),
- 'reconcile_ids': fields.many2many(
- 'account.move.reconcile',
- 'account_move_reconcile_history_rel',
- string='Reconciliations', readonly=True),
- 'reconcile_partial_ids': fields.many2many(
- 'account.move.reconcile',
- 'account_move_reconcile_history_partial_rel',
- string='Partial Reconciliations', readonly=True),
- 'reconcile_line_ids':
- fields.function(
- _reconcile_line_ids,
- string='Reconciled Items',
- type='many2many',
- relation='account.move.line',
- readonly=True,
- multi='lines'),
+ 'easy_reconcile_id': fields.many2one(
+ 'account.easy.reconcile', 'Reconcile Profile', readonly=True),
+ 'date': fields.datetime('Run date', readonly=True),
+ 'reconcile_ids': fields.many2many(
+ 'account.move.reconcile',
+ 'account_move_reconcile_history_rel',
+ string='Reconciliations', readonly=True),
+ 'reconcile_partial_ids': fields.many2many(
+ 'account.move.reconcile',
+ 'account_move_reconcile_history_partial_rel',
+ string='Partial Reconciliations', readonly=True),
+ 'reconcile_line_ids':
+ fields.function(
+ _reconcile_line_ids,
+ string='Reconciled Items',
+ type='many2many',
+ relation='account.move.line',
+ readonly=True,
+ multi='lines'),
'partial_line_ids':
fields.function(
_reconcile_line_ids,
@@ -81,16 +78,17 @@ class easy_reconcile_history(orm.Model):
relation='account.move.line',
readonly=True,
multi='lines'),
- 'company_id': fields.related('easy_reconcile_id','company_id',
+ 'company_id': fields.related('easy_reconcile_id', 'company_id',
relation='res.company',
type='many2one',
string='Company',
store=True,
readonly=True),
- }
+ }
- def _open_move_lines(self, cr, uid, history_id, rec_type='full', context=None):
+ def _open_move_lines(self, cr, uid, history_id, rec_type='full',
+ context=None):
""" For an history record, open the view of move line with
the reconciled or partially reconciled move lines
@@ -99,19 +97,15 @@ class easy_reconcile_history(orm.Model):
:return: action to open the move lines
"""
assert rec_type in ('full', 'partial'), \
- "rec_type must be 'full' or 'partial'"
-
+ "rec_type must be 'full' or 'partial'"
history = self.browse(cr, uid, history_id, context=context)
-
if rec_type == 'full':
field = 'reconcile_line_ids'
name = _('Reconciliations')
else:
field = 'partial_line_ids'
name = _('Partial Reconciliations')
-
move_line_ids = [line.id for line in getattr(history, field)]
-
return {
'name': name,
'view_mode': 'tree,form',
@@ -122,7 +116,7 @@ class easy_reconcile_history(orm.Model):
'nodestroy': True,
'target': 'current',
'domain': unicode([('id', 'in', move_line_ids)]),
- }
+ }
def open_reconcile(self, cr, uid, history_ids, context=None):
""" For an history record, open the view of move line
@@ -136,7 +130,7 @@ class easy_reconcile_history(orm.Model):
assert len(history_ids) == 1, "only 1 ID is accepted"
history_ids = history_ids[0]
return self._open_move_lines(
- cr, uid, history_ids, rec_type='full', context=None)
+ cr, uid, history_ids, rec_type='full', context=None)
def open_partial(self, cr, uid, history_ids, context=None):
""" For an history record, open the view of move line
@@ -150,4 +144,4 @@ class easy_reconcile_history(orm.Model):
assert len(history_ids) == 1, "only 1 ID is accepted"
history_ids = history_ids[0]
return self._open_move_lines(
- cr, uid, history_ids, rec_type='partial', context=None)
+ cr, uid, history_ids, rec_type='partial', context=None)
diff --git a/account_easy_reconcile/security/ir.model.access.csv b/account_easy_reconcile/security/ir.model.access.csv
index 96dd3137..616a6217 100644
--- a/account_easy_reconcile/security/ir.model.access.csv
+++ b/account_easy_reconcile/security/ir.model.access.csv
@@ -2,14 +2,8 @@ id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_easy_reconcile_options_acc_user,easy.reconcile.options,model_easy_reconcile_options,account.group_account_user,1,0,0,0
access_account_easy_reconcile_method_acc_user,account.easy.reconcile.method,model_account_easy_reconcile_method,account.group_account_user,1,0,0,0
access_account_easy_reconcile_acc_user,account.easy.reconcile,model_account_easy_reconcile,account.group_account_user,1,1,0,0
-access_easy_reconcile_simple_name_acc_user,easy.reconcile.simple.name,model_easy_reconcile_simple_name,account.group_account_user,1,0,0,0
-access_easy_reconcile_simple_partner_acc_user,easy.reconcile.simple.partner,model_easy_reconcile_simple_partner,account.group_account_user,1,0,0,0
-access_easy_reconcile_simple_reference_acc_user,easy.reconcile.simple.reference,model_easy_reconcile_simple_reference,account.group_account_user,1,0,0,0
access_easy_reconcile_options_acc_mgr,easy.reconcile.options,model_easy_reconcile_options,account.group_account_user,1,0,0,0
access_account_easy_reconcile_method_acc_mgr,account.easy.reconcile.method,model_account_easy_reconcile_method,account.group_account_user,1,1,1,1
access_account_easy_reconcile_acc_mgr,account.easy.reconcile,model_account_easy_reconcile,account.group_account_user,1,1,1,1
-access_easy_reconcile_simple_name_acc_mgr,easy.reconcile.simple.name,model_easy_reconcile_simple_name,account.group_account_user,1,0,0,0
-access_easy_reconcile_simple_partner_acc_mgr,easy.reconcile.simple.partner,model_easy_reconcile_simple_partner,account.group_account_user,1,0,0,0
-access_easy_reconcile_simple_reference_acc_mgr,easy.reconcile.simple.reference,model_easy_reconcile_simple_reference,account.group_account_user,1,0,0,0
access_easy_reconcile_history_acc_user,easy.reconcile.history,model_easy_reconcile_history,account.group_account_user,1,1,1,0
access_easy_reconcile_history_acc_mgr,easy.reconcile.history,model_easy_reconcile_history,account.group_account_manager,1,1,1,1
diff --git a/account_easy_reconcile/simple_reconciliation.py b/account_easy_reconcile/simple_reconciliation.py
index 0a1dcc8c..f108ff4f 100644
--- a/account_easy_reconcile/simple_reconciliation.py
+++ b/account_easy_reconcile/simple_reconciliation.py
@@ -22,8 +22,7 @@
from openerp.osv.orm import AbstractModel, TransientModel
-class easy_reconcile_simple(AbstractModel):
-
+class EasyReconcileSimple(AbstractModel):
_name = 'easy.reconcile.simple'
_inherit = 'easy.reconcile.base'
@@ -32,32 +31,25 @@ class easy_reconcile_simple(AbstractModel):
_key_field = None
def rec_auto_lines_simple(self, cr, uid, rec, lines, context=None):
- if context is None:
- context = {}
-
if self._key_field is None:
raise ValueError("_key_field has to be defined")
-
count = 0
res = []
while (count < len(lines)):
- for i in xrange(count+1, len(lines)):
- writeoff_account_id = False
+ for i in xrange(count + 1, len(lines)):
if lines[count][self._key_field] != lines[i][self._key_field]:
break
-
check = False
if lines[count]['credit'] > 0 and lines[i]['debit'] > 0:
credit_line = lines[count]
debit_line = lines[i]
check = True
- elif lines[i]['credit'] > 0 and lines[count]['debit'] > 0:
+ elif lines[i]['credit'] > 0 and lines[count]['debit'] > 0:
credit_line = lines[i]
debit_line = lines[count]
check = True
if not check:
continue
-
reconciled, dummy = self._reconcile_lines(
cr, uid, rec, [credit_line, debit_line],
allow_partial=False, context=context)
@@ -90,8 +82,7 @@ class easy_reconcile_simple(AbstractModel):
return self.rec_auto_lines_simple(cr, uid, rec, lines, context)
-class easy_reconcile_simple_name(TransientModel):
-
+class EasyReconcileSimpleName(TransientModel):
_name = 'easy.reconcile.simple.name'
_inherit = 'easy.reconcile.simple'
@@ -100,8 +91,7 @@ class easy_reconcile_simple_name(TransientModel):
_key_field = 'name'
-class easy_reconcile_simple_partner(TransientModel):
-
+class EasyReconcileSimplePartner(TransientModel):
_name = 'easy.reconcile.simple.partner'
_inherit = 'easy.reconcile.simple'
@@ -110,8 +100,7 @@ class easy_reconcile_simple_partner(TransientModel):
_key_field = 'partner_id'
-class easy_reconcile_simple_reference(TransientModel):
-
+class EasyReconcileSimpleReference(TransientModel):
_name = 'easy.reconcile.simple.reference'
_inherit = 'easy.reconcile.simple'
diff --git a/account_invoice_reference/__openerp__.py b/account_invoice_reference/__openerp__.py
index ab0f0499..fc12a9ca 100644
--- a/account_invoice_reference/__openerp__.py
+++ b/account_invoice_reference/__openerp__.py
@@ -19,15 +19,15 @@
#
##############################################################################
-{'name' : 'Invoices Reference',
- 'version' : '1.0',
- 'author' : 'Camptocamp',
+{'name': 'Invoices Reference',
+ 'version': '1.0',
+ 'author': 'Camptocamp',
'maintainer': 'Camptocamp',
'license': 'AGPL-3',
'category': 'category',
'complexity': "easy",
- 'depends' : ['account',
- ],
+ 'depends': ['account',
+ ],
'description': """
Invoices Reference
==================
@@ -59,13 +59,15 @@ mandatory fields are:
* Description
* Internal Reference ("our reference")
* External Reference ("customer or supplier reference")
-* Optionally, a technical transaction reference (credit card payment gateways, SEPA, ...)
+* Optionally, a technical transaction reference (credit card payment gateways,
+ SEPA, ...)
Now, on the move lines:
* Name
* Reference
-* Optionally, a technical transaction reference (added by the module `base_transaction_id`)
+* Optionally, a technical transaction reference (added by the module
+ `base_transaction_id`)
Let's see how the information will be organized with this module.
@@ -143,4 +145,4 @@ Information propagated to the move lines:
],
'installable': True,
'auto_install': False,
-}
+ }
diff --git a/account_invoice_reference/account_move.py b/account_invoice_reference/account_move.py
index b33a30e8..b99689b8 100644
--- a/account_invoice_reference/account_move.py
+++ b/account_invoice_reference/account_move.py
@@ -19,10 +19,10 @@
#
##############################################################################
-from openerp.osv import orm, fields
+from openerp.osv import orm
-class account_move(orm.Model):
+class AccountMove(orm.Model):
_inherit = 'account.move'
def create(self, cr, uid, vals, context=None):
@@ -33,15 +33,16 @@ class account_move(orm.Model):
if invoice:
assert isinstance(invoice, orm.browse_record)
invoice_obj = self.pool['account.invoice']
- ref = invoice_obj._ref_from_invoice(cr, uid, invoice, context=context)
+ ref = invoice_obj._ref_from_invoice(
+ cr, uid, invoice, context=context)
vals = vals.copy()
vals['ref'] = ref
- move_id = super(account_move, self).\
- create(cr, uid, vals, context=context)
+ move_id = super(AccountMove, self).create(cr, uid, vals,
+ context=context)
return move_id
-class account_invoice(orm.Model):
+class AccountInvoice(orm.Model):
_inherit = 'account.invoice'
def _ref_from_invoice(self, cr, uid, invoice, context=None):
@@ -69,32 +70,32 @@ class account_invoice(orm.Model):
cr.execute('UPDATE account_move_line SET ref=%s '
'WHERE move_id=%s AND (ref is null OR ref = \'\')',
(ref, move_id))
- cr.execute('UPDATE account_analytic_line SET ref=%s '
- 'FROM account_move_line '
- 'WHERE account_move_line.move_id = %s '
- 'AND account_analytic_line.move_id = account_move_line.id',
- (ref, move_id))
+ cr.execute(
+ 'UPDATE account_analytic_line SET ref=%s '
+ 'FROM account_move_line '
+ 'WHERE account_move_line.move_id = %s '
+ 'AND account_analytic_line.move_id = account_move_line.id',
+ (ref, move_id))
return True
def create(self, cr, uid, vals, context=None):
if (vals.get('supplier_invoice_reference') and not
vals.get('reference')):
vals['reference'] = vals['supplier_invoice_reference']
- return super(account_invoice, self).create(cr, uid, vals,
- context=context)
+ return super(AccountInvoice, self).create(cr, uid, vals,
+ context=context)
def write(self, cr, uid, ids, vals, context=None):
if vals.get('supplier_invoice_reference'):
if isinstance(ids, (int, long)):
ids = [ids]
for invoice in self.browse(cr, uid, ids, context=context):
- local_vals = vals
if not invoice.reference:
locvals = vals.copy()
locvals['reference'] = vals['supplier_invoice_reference']
- super(account_invoice, self).write(cr, uid, [invoice.id],
- locvals, context=context)
+ super(AccountInvoice, self).write(cr, uid, [invoice.id],
+ locvals, context=context)
return True
else:
- return super(account_invoice, self).write(cr, uid, ids, vals,
- context=context)
+ return super(AccountInvoice, self).write(cr, uid, ids, vals,
+ context=context)
diff --git a/account_payment_transaction_id/__openerp__.py b/account_payment_transaction_id/__openerp__.py
index b69c1dd2..a0eec8c5 100644
--- a/account_payment_transaction_id/__openerp__.py
+++ b/account_payment_transaction_id/__openerp__.py
@@ -40,4 +40,4 @@ Needs `statement_voucher_killer`
'test': [],
'installable': True,
'auto_install': True,
-}
+ }
diff --git a/account_statement_base_completion/__openerp__.py b/account_statement_base_completion/__openerp__.py
index feb0cb35..36988cac 100644
--- a/account_statement_base_completion/__openerp__.py
+++ b/account_statement_base_completion/__openerp__.py
@@ -19,59 +19,67 @@
#
##############################################################################
-{'name': "Bank statement base completion",
- 'version': '1.0.3',
- 'author': 'Camptocamp',
- 'maintainer': 'Camptocamp',
- 'category': 'Finance',
- 'complexity': 'normal',
- 'depends': ['account_statement_ext'],
- 'description': """
- The goal of this module is to improve the basic bank statement, help dealing with huge volume of
- reconciliation by providing basic rules to identify the partner of a bank statement line.
- Each bank statement profile can have its own rules to be applied according to a sequence order.
+{
+ 'name': "Bank statement base completion",
+ 'version': '1.0.3',
+ 'author': 'Camptocamp',
+ 'maintainer': 'Camptocamp',
+ 'category': 'Finance',
+ 'complexity': 'normal',
+ 'depends': ['account_statement_ext'],
+ 'description': """
+ The goal of this module is to improve the basic bank statement, help dealing
+ with huge volume of reconciliation by providing basic rules to identify the
+ partner of a bank statement line.
+ Each bank statement profile can have its own rules to be applied according to a
+ sequence order.
Some basic rules are provided in this module:
- 1) Match from statement line label (based on partner field 'Bank Statement Label')
+ 1) Match from statement line label (based on partner field 'Bank Statement
+ Label')
2) Match from statement line label (based on partner name)
3) Match from statement line reference (based on Invoice number)
- You can easily override this module and add your own rules in your own one. The basic rules only
- fill in the partner, but you can use them to fill in any value of the line (in the future, we will
- add a rule to automatically match and reconcile the line).
+ You can easily override this module and add your own rules in your own one. The
+ basic rules only fill in the partner, but you can use them to fill in any
+ value of the line (in the future, we will add a rule to automatically match and
+ reconcile the line).
- It adds as well a label on the bank statement line (on which the pre-define rules can match) and
- a char field on the partner called 'Bank Statement Label'. Using the pre-define rules, you will be
- able to match various labels for a partner.
+ It adds as well a label on the bank statement line (on which the pre-define
+ rules can match) and a char field on the partner called 'Bank Statement Label'.
+ Using the pre-define rules, you will be able to match various labels for a
+ partner.
- The reference of the line is always used by the reconciliation process. We're supposed to copy
- there (or write manually) the matching string. This can be: the order Number or an invoice number,
- or anything that will be found in the invoice accounting entry part to make the match.
+ The reference of the line is always used by the reconciliation process. We're
+ supposed to copy there (or write manually) the matching string. This can be:
+ the order Number or an invoice number, or anything that will be found in the
+ invoice accounting entry part to make the match.
- You can use it with our account_advanced_reconcile module to automatize the reconciliation process.
+ You can use it with our account_advanced_reconcile module to automatize the
+ reconciliation process.
- TODO: The rules that look for invoices to find out the partner should take back the payable / receivable
- account from there directly instead of retrieving it from partner properties !
-
- """,
- 'website': 'http://www.camptocamp.com',
- 'data': [
- 'statement_view.xml',
- 'partner_view.xml',
- 'data.xml',
- 'security/ir.model.access.csv',
- ],
- 'demo': [],
- 'test': [
- 'test/partner.yml',
- 'test/invoice.yml',
- 'test/supplier_invoice.yml',
- 'test/completion_test.yml'
- ],
- 'installable': True,
- 'images': [],
- 'auto_install': False,
- 'license': 'AGPL-3',
+ TODO: The rules that look for invoices to find out the partner should take back
+ the payable / receivable account from there directly instead of retrieving it
+ from partner properties !
+ """,
+ 'website': 'http://www.camptocamp.com',
+ 'data': [
+ 'statement_view.xml',
+ 'partner_view.xml',
+ 'data.xml',
+ 'security/ir.model.access.csv',
+ ],
+ 'demo': [],
+ 'test': [
+ 'test/partner.yml',
+ 'test/invoice.yml',
+ 'test/supplier_invoice.yml',
+ 'test/completion_test.yml'
+ ],
+ 'installable': True,
+ 'images': [],
+ 'auto_install': False,
+ 'license': 'AGPL-3',
}
diff --git a/account_statement_base_completion/partner.py b/account_statement_base_completion/partner.py
index 4d3a452e..2670d8aa 100644
--- a/account_statement_base_completion/partner.py
+++ b/account_statement_base_completion/partner.py
@@ -1,38 +1,39 @@
# -*- coding: utf-8 -*-
-#################################################################################
-# #
+##########################################################################
+#
# Copyright (C) 2011 Akretion & Camptocamp
-# Author : Sébastien BEAU, Joel Grand-Guillaume #
-# #
-# This program is free software: you can redistribute it and/or modify #
-# it under the terms of the GNU Affero General Public License as #
-# published by the Free Software Foundation, either version 3 of the #
-# License, or (at your option) any later version. #
-# #
-# This program is distributed in the hope that it will be useful, #
-# but WITHOUT ANY WARRANTY; without even the implied warranty of #
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
-# GNU Affero General Public License for more details. #
-# #
-# You should have received a copy of the GNU Affero General Public License #
-# along with this program. If not, see . #
-# #
-#################################################################################
+# Author : Sébastien BEAU, Joel Grand-Guillaume
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+#
+##########################################################################
-from openerp.osv.orm import Model
-from openerp.osv import fields
+from openerp.osv import orm, fields
-class res_partner(Model):
- """
- Add a bank label on the partner so that we can use it to match
+class ResPartner(orm.Model):
+ """Add a bank label on the partner so that we can use it to match
this partner when we found this in a statement line.
"""
_inherit = 'res.partner'
_columns = {
- 'bank_statement_label': fields.char('Bank Statement Label', size=100,
- help="Enter the various label found on your bank statement separated by a ; If "
- "one of this label is include in the bank statement line, the partner will be automatically "
- "filled (as long as you use this method/rules in your statement profile)."),
- }
+ 'bank_statement_label': fields.char(
+ 'Bank Statement Label', size=100,
+ help="Enter the various label found on your bank statement "
+ "separated by a ; If one of this label is include in the bank "
+ "statement line, the partner will be automatically filled (as "
+ "long as you use this method/rules in your statement "
+ "profile)."),
+ }
diff --git a/account_statement_base_completion/partner_view.xml b/account_statement_base_completion/partner_view.xml
index c7ec3f1a..94be85c3 100644
--- a/account_statement_base_completion/partner_view.xml
+++ b/account_statement_base_completion/partner_view.xml
@@ -7,7 +7,6 @@
account_bank_statement_import.view.partner.form
res.partner
- form
20
@@ -17,6 +16,6 @@
-
+
diff --git a/account_statement_base_completion/statement.py b/account_statement_base_completion/statement.py
index 34c6d272..ba1771f5 100644
--- a/account_statement_base_completion/statement.py
+++ b/account_statement_base_completion/statement.py
@@ -31,7 +31,7 @@ import psycopg2
from collections import defaultdict
import re
from openerp.tools.translate import _
-from openerp.osv import osv, orm, fields
+from openerp.osv import orm, fields
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from operator import attrgetter
@@ -40,10 +40,10 @@ _logger = logging.getLogger(__name__)
class ErrorTooManyPartner(Exception):
+ """ New Exception definition that is raised when more than one partner is
+ matched by the completion rule.
"""
- New Exception definition that is raised when more than one partner is matched by
- the completion rule.
- """
+
def __init__(self, value):
self.value = value
@@ -55,19 +55,18 @@ class ErrorTooManyPartner(Exception):
class AccountStatementProfil(orm.Model):
+ """Extend the class to add rules per profile that will match at least the
+ partner, but it could also be used to match other values as well.
"""
- Extend the class to add rules per profile that will match at least the partner,
- but it could also be used to match other values as well.
- """
-
_inherit = "account.statement.profile"
_columns = {
- # @Akretion: For now, we don't implement this features, but this would probably be there:
- # 'auto_completion': fields.text('Auto Completion'),
- # 'transferts_account_id':fields.many2one('account.account', 'Transferts Account'),
- # => You can implement it in a module easily, we design it with your needs in mind
- # as well!
+ # @Akretion: For now, we don't implement this features, but this would
+ # probably be there: 'auto_completion': fields.text('Auto Completion'),
+ # 'transferts_account_id':fields.many2one('account.account',
+ # 'Transferts Account'),
+ # => You can implement it in a module easily, we design it with your
+ # needs in mind as well!
'rule_ids': fields.many2many(
'account.statement.completion.rule',
@@ -84,8 +83,7 @@ class AccountStatementProfil(orm.Model):
return sorted(prof.rule_ids, key=attrgetter('sequence'))
def _find_values_from_rules(self, cr, uid, calls, line, context=None):
- """
- This method will execute all related rules, in their sequence order,
+ """This method will execute all related rules, in their sequence order,
to retrieve all the values returned by the first rules that will match.
:param calls: list of lookup function name available in rules
:param dict line: read of the concerned account.bank.statement.line
@@ -97,12 +95,10 @@ class AccountStatementProfil(orm.Model):
...}
"""
- if context is None:
- context = {}
if not calls:
- calls = self._get_rules(cr, uid, line['profile_id'], context=context)
+ calls = self._get_rules(
+ cr, uid, line['profile_id'], context=context)
rule_obj = self.pool.get('account.statement.completion.rule')
-
for call in calls:
method_to_call = getattr(rule_obj, call.function_to_call)
if len(inspect.getargspec(method_to_call).args) == 6:
@@ -116,35 +112,37 @@ class AccountStatementProfil(orm.Model):
class AccountStatementCompletionRule(orm.Model):
- """
- This will represent all the completion method that we can have to
- fullfill the bank statement lines. You'll be able to extend them in you own module
- and choose those to apply for every statement profile.
+ """This will represent all the completion method that we can have to
+ fullfill the bank statement lines. You'll be able to extend them in you own
+ module and choose those to apply for every statement profile.
The goal of a rule is to fullfill at least the partner of the line, but
if possible also the reference because we'll use it in the reconciliation
process. The reference should contain the invoice number or the SO number
or any reference that will be matched by the invoice accounting move.
"""
-
_name = "account.statement.completion.rule"
_order = "sequence asc"
def _get_functions(self, cr, uid, context=None):
- """
- List of available methods for rules. Override this to add you own.
- """
+ """List of available methods for rules. Override this to add you own."""
return [
- ('get_from_ref_and_invoice', 'From line reference (based on customer invoice number)'),
- ('get_from_ref_and_supplier_invoice', 'From line reference (based on supplier invoice number)'),
- ('get_from_label_and_partner_field', 'From line label (based on partner field)'),
- ('get_from_label_and_partner_name', 'From line label (based on partner name)')]
+ ('get_from_ref_and_invoice',
+ 'From line reference (based on customer invoice number)'),
+ ('get_from_ref_and_supplier_invoice',
+ 'From line reference (based on supplier invoice number)'),
+ ('get_from_label_and_partner_field',
+ 'From line label (based on partner field)'),
+ ('get_from_label_and_partner_name',
+ 'From line label (based on partner name)')
+ ]
def __get_functions(self, cr, uid, context=None):
""" Call method which can be inherited """
return self._get_functions(cr, uid, context=context)
_columns = {
- 'sequence': fields.integer('Sequence', help="Lower means parsed first."),
+ 'sequence': fields.integer('Sequence',
+ help="Lower means parsed first."),
'name': fields.char('Name', size=128),
'profile_ids': fields.many2many(
'account.statement.profile',
@@ -163,8 +161,9 @@ class AccountStatementCompletionRule(orm.Model):
type_domain = ('out_invoice', 'out_refund')
number_field = 'number'
else:
- raise osv.except_osv(_('System error'),
- _('Invalid invoice type for completion: %') % inv_type)
+ raise orm.except_orm(
+ _('System error'),
+ _('Invalid invoice type for completion: %') % inv_type)
inv_id = inv_obj.search(cr, uid,
[(number_field, '=', st_line['ref'].strip()),
@@ -174,17 +173,19 @@ class AccountStatementCompletionRule(orm.Model):
if len(inv_id) == 1:
inv = inv_obj.browse(cr, uid, inv_id[0], context=context)
else:
- raise ErrorTooManyPartner(_('Line named "%s" (Ref:%s) was matched by more '
- 'than one partner while looking on %s invoices') %
- (st_line['name'], st_line['ref'], inv_type))
+ raise ErrorTooManyPartner(
+ _('Line named "%s" (Ref:%s) was matched by more than one '
+ 'partner while looking on %s invoices') %
+ (st_line['name'], st_line['ref'], inv_type))
return inv
return False
def _from_invoice(self, cr, uid, line, inv_type, context):
"""Populate statement line values"""
- if not inv_type in ('supplier', 'customer'):
- raise osv.except_osv(_('System error'),
- _('Invalid invoice type for completion: %') % inv_type)
+ if inv_type not in ('supplier', 'customer'):
+ raise orm.except_orm(_('System error'),
+ _('Invalid invoice type for completion: %') %
+ inv_type)
res = {}
inv = self._find_invoice(cr, uid, line, inv_type, context=context)
if inv:
@@ -195,7 +196,6 @@ class AccountStatementCompletionRule(orm.Model):
partner_id = inv.commercial_partner_id.id
else:
partner_id = inv.partner_id.id
-
res = {'partner_id': partner_id,
'account_id': inv.account_id.id,
'type': inv_type}
@@ -206,10 +206,10 @@ class AccountStatementCompletionRule(orm.Model):
# Should be private but data are initialised with no update XML
def get_from_ref_and_supplier_invoice(self, cr, uid, line, context=None):
- """
- Match the partner based on the invoice supplier invoice number and the reference of the statement
- line. Then, call the generic get_values_for_line method to complete other values.
- If more than one partner matched, raise the ErrorTooManyPartner error.
+ """Match the partner based on the invoice supplier invoice number and
+ the reference of the statement line. Then, call the generic
+ get_values_for_line method to complete other values. If more than one
+ partner matched, raise the ErrorTooManyPartner error.
:param dict line: read of the concerned account.bank.statement.line
:return:
@@ -224,10 +224,10 @@ class AccountStatementCompletionRule(orm.Model):
# Should be private but data are initialised with no update XML
def get_from_ref_and_invoice(self, cr, uid, line, context=None):
- """
- Match the partner based on the invoice number and the reference of the statement
- line. Then, call the generic get_values_for_line method to complete other values.
- If more than one partner matched, raise the ErrorTooManyPartner error.
+ """Match the partner based on the invoice number and the reference of
+ the statement line. Then, call the generic get_values_for_line method to
+ complete other values. If more than one partner matched, raise the
+ ErrorTooManyPartner error.
:param dict line: read of the concerned account.bank.statement.line
:return:
@@ -257,7 +257,7 @@ class AccountStatementCompletionRule(orm.Model):
...}
"""
- partner_obj = self.pool.get('res.partner')
+ partner_obj = self.pool['res.partner']
st_obj = self.pool.get('account.bank.statement.line')
res = {}
# As we have to iterate on each partner for each line,
@@ -267,12 +267,15 @@ class AccountStatementCompletionRule(orm.Model):
# but this option is not really maintanable
if not context.get('label_memoizer'):
context['label_memoizer'] = defaultdict(list)
- partner_ids = partner_obj.search(cr,
- uid,
- [('bank_statement_label', '!=', False)])
+ partner_ids = partner_obj.search(
+ cr, uid, [('bank_statement_label', '!=', False)],
+ context=context)
line_ids = context.get('line_ids', [])
- for partner in partner_obj.browse(cr, uid, partner_ids, context=context):
- vals = '|'.join(re.escape(x.strip()) for x in partner.bank_statement_label.split(';'))
+ for partner in partner_obj.browse(cr, uid, partner_ids,
+ context=context):
+ vals = '|'.join(
+ re.escape(x.strip())
+ for x in partner.bank_statement_label.split(';'))
or_regex = ".*%s.*" % vals
sql = ("SELECT id from account_bank_statement_line"
" WHERE id in %s"
@@ -281,32 +284,29 @@ class AccountStatementCompletionRule(orm.Model):
pairs = cr.fetchall()
for pair in pairs:
context['label_memoizer'][pair[0]].append(partner)
-
if st_line['id'] in context['label_memoizer']:
found_partner = context['label_memoizer'][st_line['id']]
if len(found_partner) > 1:
- msg = (_('Line named "%s" (Ref:%s) was matched by '
- 'more than one partner while looking on partner label: %s') %
- (st_line['name'], st_line['ref'], ','.join([x.name for x in found_partner])))
+ msg = (_('Line named "%s" (Ref:%s) was matched by more than '
+ 'one partner while looking on partner label: %s') %
+ (st_line['name'], st_line['ref'],
+ ','.join([x.name for x in found_partner])))
raise ErrorTooManyPartner(msg)
res['partner_id'] = found_partner[0].id
- st_vals = st_obj.get_values_for_line(cr,
- uid,
- profile_id=st_line['profile_id'],
- master_account_id=st_line['master_account_id'],
- partner_id=found_partner[0].id,
- line_type=False,
- amount=st_line['amount'] if st_line['amount'] else 0.0,
- context=context)
+ st_vals = st_obj.get_values_for_line(
+ cr, uid, profile_id=st_line['profile_id'],
+ master_account_id=st_line['master_account_id'],
+ partner_id=found_partner[0].id, line_type=False,
+ amount=st_line['amount'] if st_line['amount'] else 0.0,
+ context=context)
res.update(st_vals)
return res
def get_from_label_and_partner_name(self, cr, uid, st_line, context=None):
- """
- Match the partner based on the label field of the statement line
- and the name of the partner.
- Then, call the generic get_values_for_line method to complete other values.
- If more than one partner matched, raise the ErrorTooManyPartner error.
+ """Match the partner based on the label field of the statement line
+ and the name of the partner. Then, call the generic get_values_for_line
+ method to complete other values. If more than one partner matched, raise
+ the ErrorTooManyPartner error.
:param dict st_line: read of the concerned account.bank.statement.line
:return:
@@ -320,7 +320,8 @@ class AccountStatementCompletionRule(orm.Model):
res = {}
# We memoize allowed partner
if not context.get('partner_memoizer'):
- context['partner_memoizer'] = tuple(self.pool['res.partner'].search(cr, uid, []))
+ context['partner_memoizer'] = tuple(
+ self.pool['res.partner'].search(cr, uid, []))
if not context['partner_memoizer']:
return res
st_obj = self.pool.get('account.bank.statement.line')
@@ -328,33 +329,41 @@ class AccountStatementCompletionRule(orm.Model):
# example: 'John J. Doe (No 1)' is escaped to 'John J\. Doe \(No 1\)'
# See http://stackoverflow.com/a/400316/1504003 for a list of
# chars to escape. Postgres is POSIX-ARE, compatible with
- # POSIX-ERE excepted that '\' must be escaped inside brackets according to:
- # http://www.postgresql.org/docs/9.0/static/functions-matching.html
+ # POSIX-ERE excepted that '\' must be escaped inside brackets according
+ # to:
+ # http://www.postgresql.org/docs/9.0/static/functions-matching.html
# in chapter 9.7.3.6. Limits and Compatibility
- sql = """SELECT id FROM (
- SELECT id, regexp_matches(%s, regexp_replace(name,'([\.\^\$\*\+\?\(\)\[\{\\\|])', %s, 'g'), 'i') AS name_match FROM res_partner
- WHERE id IN %s) AS res_patner_matcher
- WHERE name_match IS NOT NULL"""
- cr.execute(sql, (st_line['name'], r"\\\1", context['partner_memoizer']))
+ sql = """
+ SELECT id FROM (
+ SELECT id,
+ regexp_matches(%s,
+ regexp_replace(name,'([\.\^\$\*\+\?\(\)\[\{\\\|])', %s,
+ 'g'), 'i') AS name_match
+ FROM res_partner
+ WHERE id IN %s)
+ AS res_patner_matcher
+ WHERE name_match IS NOT NULL"""
+ cr.execute(
+ sql, (st_line['name'], r"\\\1", context['partner_memoizer']))
result = cr.fetchall()
if not result:
return res
if len(result) > 1:
- raise ErrorTooManyPartner(_('Line named "%s" (Ref:%s) was matched by more '
- 'than one partner while looking on partner by name') %
- (st_line['name'], st_line['ref']))
+ raise ErrorTooManyPartner(
+ _('Line named "%s" (Ref:%s) was matched by more than one '
+ 'partner while looking on partner by name') %
+ (st_line['name'], st_line['ref']))
res['partner_id'] = result[0][0]
- st_vals = st_obj.get_values_for_line(cr,
- uid,
- profile_id=st_line['profile_id'],
- master_account_id=st_line['master_account_id'],
- partner_id=res['partner_id'],
- line_type=False,
- amount=st_line['amount'] if st_line['amount'] else 0.0,
- context=context)
+ st_vals = st_obj.get_values_for_line(
+ cr, uid, profile_id=st_line['profile_id'],
+ master_account_id=st_line['master_account_id'],
+ partner_id=res['partner_id'], line_type=False,
+ amount=st_line['amount'] if st_line['amount'] else 0.0,
+ context=context)
res.update(st_vals)
return res
+
class AccountStatement(orm.Model):
_inherit = "account.bank.statement"
@@ -364,24 +373,26 @@ class AccountStatement(orm.Model):
line_without_account = line_obj.search(cr, uid, [
['statement_id', '=', stat_id],
['account_id', '=', False],
- ], context=context)
+ ], context=context)
if line_without_account:
stat = self.browse(cr, uid, stat_id, context=context)
- raise orm.except_orm(_('User error'),
- _('You should fill all account on the line of the'
- ' statement %s')%stat.name)
+ raise orm.except_orm(
+ _('User error'),
+ _('You should fill all account on the line of the'
+ ' statement %s') % stat.name)
return super(AccountStatement, self).button_confirm_bank(
- cr, uid, ids, context=context)
+ cr, uid, ids, context=context)
class AccountStatementLine(orm.Model):
"""
Add sparse field on the statement line to allow to store all the
bank infos that are given by a bank/office. You can then add you own in your
- module. The idea here is to store all bank/office infos in the additionnal_bank_fields
- serialized field when importing the file. If many values, add a tab in the bank
- statement line to store your specific one. Have a look in account_statement_base_import
- module to see how we've done it.
+ module. The idea here is to store all bank/office infos in the
+ additionnal_bank_fields serialized field when importing the file. If many
+ values, add a tab in the bank statement line to store your specific one.
+ Have a look in account_statement_base_import module to see how we've done
+ it.
"""
_inherit = "account.bank.statement.line"
_order = "already_completed desc, date asc"
@@ -411,38 +422,42 @@ class AccountStatementLine(orm.Model):
}
def _get_line_values_from_rules(self, cr, uid, line, rules, context=None):
- """
- We'll try to find out the values related to the line based on rules setted on
- the profile.. We will ignore line for which already_completed is ticked.
+ """We'll try to find out the values related to the line based on rules
+ setted on the profile.. We will ignore line for which already_completed
+ is ticked.
:return:
- A dict of dict value that can be passed directly to the write method of
- the statement line or {}. The first dict has statement line ID as a key:
- {117009: {'partner_id': 100997, 'account_id': 489L}}
+ A dict of dict value that can be passed directly to the write
+ method of the statement line or {}. The first dict has statement
+ line ID as a key: {117009: {'partner_id': 100997,
+ 'account_id': 489L}}
"""
- profile_obj = self.pool.get('account.statement.profile')
+ profile_obj = self.pool['account.statement.profile']
if line.get('already_completed'):
return {}
# Ask the rule
- vals = profile_obj._find_values_from_rules(cr, uid, rules, line, context)
+ vals = profile_obj._find_values_from_rules(
+ cr, uid, rules, line, context)
if vals:
vals['id'] = line['id']
return vals
return {}
- def _get_available_columns(self, statement_store, include_serializable=False):
+ def _get_available_columns(self, statement_store,
+ include_serializable=False):
"""Return writeable by SQL columns"""
statement_line_obj = self.pool['account.bank.statement.line']
model_cols = statement_line_obj._columns
- avail = [k for k, col in model_cols.iteritems() if not hasattr(col, '_fnct')]
+ avail = [
+ k for k, col in model_cols.iteritems() if not hasattr(col, '_fnct')]
keys = [k for k in statement_store[0].keys() if k in avail]
# add sparse fields..
if include_serializable:
for k, col in model_cols.iteritems():
- if k in statement_store[0].keys() and \
- isinstance(col, fields.sparse) and \
- col.serialization_field not in keys and \
- col._type == 'char':
+ if k in statement_store[0].keys() and \
+ isinstance(col, fields.sparse) and \
+ col.serialization_field not in keys and \
+ col._type == 'char':
keys.append(col.serialization_field)
keys.sort()
return keys
@@ -472,7 +487,9 @@ class AccountStatementLine(orm.Model):
"""
statement_line_obj = self.pool['account.bank.statement.line']
model_cols = statement_line_obj._columns
- sparse_fields = dict([(k, col) for k, col in model_cols.iteritems() if isinstance(col, fields.sparse) and col._type == 'char'])
+ sparse_fields = dict(
+ [(k, col) for k, col in model_cols.iteritems() if isinstance(
+ col, fields.sparse) and col._type == 'char'])
values = []
for statement in statement_store:
to_json_k = set()
@@ -480,7 +497,8 @@ class AccountStatementLine(orm.Model):
for k, col in sparse_fields.iteritems():
if k in st_copy:
to_json_k.add(col.serialization_field)
- serialized = st_copy.setdefault(col.serialization_field, {})
+ serialized = st_copy.setdefault(
+ col.serialization_field, {})
serialized[k] = st_copy[k]
for k in to_json_k:
st_copy[k] = simplejson.dumps(st_copy[k])
@@ -493,16 +511,21 @@ class AccountStatementLine(orm.Model):
does not exist"""
statement_line_obj = self.pool['account.bank.statement.line']
statement_line_obj.check_access_rule(cr, uid, [], 'create')
- statement_line_obj.check_access_rights(cr, uid, 'create', raise_exception=True)
- cols = self._get_available_columns(statement_store, include_serializable=True)
+ statement_line_obj.check_access_rights(
+ cr, uid, 'create', raise_exception=True)
+ cols = self._get_available_columns(
+ statement_store, include_serializable=True)
statement_store = self._prepare_manyinsert(statement_store, cols)
tmp_vals = (', '.join(cols), ', '.join(['%%(%s)s' % i for i in cols]))
- sql = "INSERT INTO account_bank_statement_line (%s) VALUES (%s);" % tmp_vals
+ sql = "INSERT INTO account_bank_statement_line (%s) " \
+ "VALUES (%s);" % tmp_vals
try:
- cr.executemany(sql, tuple(self._serialize_sparse_fields(cols, statement_store)))
+ cr.executemany(
+ sql, tuple(self._serialize_sparse_fields(cols,
+ statement_store)))
except psycopg2.Error as sql_err:
cr.rollback()
- raise osv.except_osv(_("ORM bypass error"),
+ raise orm.except_orm(_("ORM bypass error"),
sql_err.pgerror)
def _update_line(self, cr, uid, vals, context=None):
@@ -516,18 +539,18 @@ class AccountStatementLine(orm.Model):
cols = self._get_available_columns([vals])
vals = self._prepare_insert(vals, cols)
tmp_vals = (', '.join(['%s = %%(%s)s' % (i, i) for i in cols]))
- sql = "UPDATE account_bank_statement_line SET %s where id = %%(id)s;" % tmp_vals
+ sql = "UPDATE account_bank_statement_line " \
+ "SET %s where id = %%(id)s;" % tmp_vals
try:
cr.execute(sql, vals)
except psycopg2.Error as sql_err:
cr.rollback()
- raise osv.except_osv(_("ORM bypass error"),
+ raise orm.except_orm(_("ORM bypass error"),
sql_err.pgerror)
class AccountBankStatement(orm.Model):
- """
- We add a basic button and stuff to support the auto-completion
+ """We add a basic button and stuff to support the auto-completion
of the bank statement once line have been imported or manually fullfill.
"""
_inherit = "account.bank.statement"
@@ -536,44 +559,42 @@ class AccountBankStatement(orm.Model):
'completion_logs': fields.text('Completion Log', readonly=True),
}
- def write_completion_log(self, cr, uid, stat_id, error_msg, number_imported, context=None):
- """
- Write the log in the completion_logs field of the bank statement to let the user
- know what have been done. This is an append mode, so we don't overwrite what
- already recoded.
+ def write_completion_log(self, cr, uid, stat_id, error_msg,
+ number_imported, context=None):
+ """Write the log in the completion_logs field of the bank statement to
+ let the user know what have been done. This is an append mode, so we
+ don't overwrite what already recoded.
:param int/long stat_id: ID of the account.bank.statement
:param char error_msg: Message to add
:number_imported int/long: Number of lines that have been completed
:return True
"""
- user_name = self.pool.get('res.users').read(cr, uid, uid,
- ['name'], context=context)['name']
+ user_name = self.pool.get('res.users').read(
+ cr, uid, uid, ['name'], context=context)['name']
statement = self.browse(cr, uid, stat_id, context=context)
number_line = len(statement.line_ids)
-
log = self.read(cr, uid, stat_id, ['completion_logs'],
context=context)['completion_logs']
log = log if log else ""
-
- completion_date = datetime.datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT)
- message = (_("%s Bank Statement ID %s has %s/%s lines completed by %s \n%s\n%s\n") %
- (completion_date, stat_id, number_imported, number_line, user_name,
- error_msg, log))
- self.write(cr, uid, [stat_id], {'completion_logs': message}, context=context)
+ completion_date = datetime.datetime.now().strftime(
+ DEFAULT_SERVER_DATETIME_FORMAT)
+ message = (_("%s Bank Statement ID %s has %s/%s lines completed by "
+ "%s \n%s\n%s\n") % (completion_date, stat_id,
+ number_imported, number_line,
+ user_name, error_msg, log))
+ self.write(
+ cr, uid, [stat_id], {'completion_logs': message}, context=context)
body = (_('Statement ID %s auto-completed for %s/%s lines completed') %
(stat_id, number_imported, number_line)),
- self.message_post(cr, uid,
- [stat_id],
- body=body,
- context=context)
+ self.message_post(cr, uid, [stat_id], body=body, context=context)
return True
def button_auto_completion(self, cr, uid, ids, context=None):
- """
- Complete line with values given by rules and tic the already_completed
- checkbox so we won't compute them again unless the user untick them!
+ """Complete line with values given by rules and tic the
+ already_completed checkbox so we won't compute them again unless the
+ user untick them!
"""
if context is None:
context = {}
@@ -581,24 +602,27 @@ class AccountBankStatement(orm.Model):
profile_obj = self.pool.get('account.statement.profile')
compl_lines = 0
stat_line_obj.check_access_rule(cr, uid, [], 'create')
- stat_line_obj.check_access_rights(cr, uid, 'create', raise_exception=True)
+ stat_line_obj.check_access_rights(
+ cr, uid, 'create', raise_exception=True)
for stat in self.browse(cr, uid, ids, context=context):
msg_lines = []
ctx = context.copy()
ctx['line_ids'] = tuple((x.id for x in stat.line_ids))
b_profile = stat.profile_id
rules = profile_obj._get_rules(cr, uid, b_profile, context=context)
- profile_id = b_profile.id # Only for perfo even it gains almost nothing
+ # Only for perfo even it gains almost nothing
+ profile_id = b_profile.id
master_account_id = b_profile.receivable_account_id
- master_account_id = master_account_id.id if master_account_id else False
+ master_account_id = master_account_id.id if \
+ master_account_id else False
res = False
for line in stat_line_obj.read(cr, uid, ctx['line_ids']):
try:
# performance trick
line['master_account_id'] = master_account_id
line['profile_id'] = profile_id
- res = stat_line_obj._get_line_values_from_rules(cr, uid, line,
- rules, context=ctx)
+ res = stat_line_obj._get_line_values_from_rules(
+ cr, uid, line, rules, context=ctx)
if res:
compl_lines += 1
except ErrorTooManyPartner, exc:
@@ -606,17 +630,20 @@ class AccountBankStatement(orm.Model):
except Exception, exc:
msg_lines.append(repr(exc))
error_type, error_value, trbk = sys.exc_info()
- st = "Error: %s\nDescription: %s\nTraceback:" % (error_type.__name__, error_value)
+ st = "Error: %s\nDescription: %s\nTraceback:" % (
+ error_type.__name__, error_value)
st += ''.join(traceback.format_tb(trbk, 30))
_logger.error(st)
if res:
# stat_line_obj.write(cr, uid, [line.id], vals, context=ctx)
try:
- stat_line_obj._update_line(cr, uid, res, context=context)
+ stat_line_obj._update_line(
+ cr, uid, res, context=context)
except Exception as exc:
msg_lines.append(repr(exc))
error_type, error_value, trbk = sys.exc_info()
- st = "Error: %s\nDescription: %s\nTraceback:" % (error_type.__name__, error_value)
+ st = "Error: %s\nDescription: %s\nTraceback:" % (
+ error_type.__name__, error_value)
st += ''.join(traceback.format_tb(trbk, 30))
_logger.error(st)
# we can commit as it is not needed to be atomic
diff --git a/account_statement_base_completion/statement_view.xml b/account_statement_base_completion/statement_view.xml
index d5adaddc..f5d07bd5 100644
--- a/account_statement_base_completion/statement_view.xml
+++ b/account_statement_base_completion/statement_view.xml
@@ -7,7 +7,6 @@
account.bank.statement
- form
@@ -37,7 +36,6 @@
account_bank_statement_import_base.bank_statement.auto_cmpl
account.bank.statement
- form
@@ -51,7 +49,6 @@
account.statement.profile.view
account.statement.profile
- form
@@ -59,12 +56,11 @@
-
-
+
+
account.statement.completion.rule.view
account.statement.completion.rule
- form
diff --git a/account_statement_base_import/__openerp__.py b/account_statement_base_import/__openerp__.py
index 46653551..4826ae28 100644
--- a/account_statement_base_import/__openerp__.py
+++ b/account_statement_base_import/__openerp__.py
@@ -28,42 +28,46 @@
'depends': [
'account_statement_ext',
'account_statement_base_completion'
- ],
+ ],
'description': """
This module brings basic methods and fields on bank statement to deal with
- the importation of different bank and offices. A generic abstract method is defined and an
- example that gives you a basic way of importing bank statement through a standard file is provided.
+ the importation of different bank and offices. A generic abstract method is
+ defined and an example that gives you a basic way of importing bank statement
+ through a standard file is provided.
- This module improves the bank statement and allows you to import your bank transactions with
- a standard .csv or .xls file (you'll find it in the 'data' folder). It respects the profile
- (provided by the accouhnt_statement_ext module) to pass the entries. That means,
- you'll have to choose a file format for each profile.
- In order to achieve this it uses the `xlrd` Python module which you will need to install
- separately in your environment.
+ This module improves the bank statement and allows you to import your bank
+ transactions with a standard .csv or .xls file (you'll find it in the 'data'
+ folder). It respects the profile (provided by the accouhnt_statement_ext
+ module) to pass the entries. That means, you'll have to choose a file format
+ for each profile.
+ In order to achieve this it uses the `xlrd` Python module which you will need
+ to install separately in your environment.
- This module can handle a commission taken by the payment office and has the following format:
+ This module can handle a commission taken by the payment office and has the
+ following format:
- * ref : the SO number, INV number or any matching ref found. It'll be used as reference
- in the generated entries and will be useful for reconciliation process
- * date : date of the payment
- * amount : amount paid in the currency of the journal used in the importation profile
- * label : the comunication given by the payment office, used as communication in the
- generated entries.
-
- The goal is here to populate the statement lines of a bank statement with the infos that the
- bank or office give you. Fell free to inherit from this module to add your own format.Then,
- if you need to complete data from there, add your own account_statement_*_completion module and implement
- the needed rules.
+ * __ref__: the SO number, INV number or any matching ref found. It'll be used
+ as reference in the generated entries and will be useful for reconciliation
+ process
+ * __date__: date of the payment
+ * __amount__: amount paid in the currency of the journal used in the
+ importation profile
+ * __label__: the comunication given by the payment office, used as
+ communication in the generated entries.
+ The goal is here to populate the statement lines of a bank statement with the
+ infos that the bank or office give you. Fell free to inherit from this module
+ to add your own format. Then, if you need to complete data from there, add your
+ own account_statement_*_completion module and implement the needed rules.
""",
'website': 'http://www.camptocamp.com',
'data': [
- "wizard/import_statement_view.xml",
- "statement_view.xml",
+ "wizard/import_statement_view.xml",
+ "statement_view.xml",
],
'test': [],
'installable': True,
'images': [],
'auto_install': False,
'license': 'AGPL-3',
-}
+ }
diff --git a/account_statement_base_import/parser/file_parser.py b/account_statement_base_import/parser/file_parser.py
index 125605f2..e7d050a6 100644
--- a/account_statement_base_import/parser/file_parser.py
+++ b/account_statement_base_import/parser/file_parser.py
@@ -18,7 +18,7 @@
#
##############################################################################
from openerp.tools.translate import _
-from openerp.osv.osv import except_osv
+from openerp.osv.orm import except_orm
import tempfile
import datetime
from parser import BankStatementImportParser
@@ -28,31 +28,36 @@ try:
except:
raise Exception(_('Please install python lib xlrd'))
+
def float_or_zero(val):
""" Conversion function used to manage
empty string into float usecase"""
return float(val) if val else 0.0
+
class FileParser(BankStatementImportParser):
- """
- Generic abstract class for defining parser for .csv, .xls or .xlsx file format.
+ """Generic abstract class for defining parser for .csv, .xls or .xlsx file
+ format.
"""
- def __init__(self, parse_name, ftype='csv', extra_fields=None, header=None, **kwargs):
+ def __init__(self, parse_name, ftype='csv', extra_fields=None, header=None,
+ **kwargs):
"""
:param char: parse_name: The name of the parser
- :param char: ftype: extension of the file (could be csv, xls or xlsx)
- :param dict: extra_fields: extra fields to add to the conversion dict. In the format
- {fieldname: fieldtype}
- :param list: header : specify header fields if the csv file has no header
+ :param char: ftype: extension of the file (could be csv, xls or
+ xlsx)
+ :param dict: extra_fields: extra fields to add to the conversion
+ dict. In the format {fieldname: fieldtype}
+ :param list: header : specify header fields if the csv file has no
+ header
"""
-
super(FileParser, self).__init__(parse_name, **kwargs)
- if ftype in ('csv', 'xls' ,'xlsx'):
+ if ftype in ('csv', 'xls', 'xlsx'):
self.ftype = ftype[0:3]
else:
- raise except_osv(_('User Error'),
- _('Invalid file type %s. Please use csv, xls or xlsx') % ftype)
+ raise except_orm(
+ _('User Error'),
+ _('Invalid file type %s. Please use csv, xls or xlsx') % ftype)
self.conversion_dict = {
'ref': unicode,
'label': unicode,
@@ -64,27 +69,21 @@ class FileParser(BankStatementImportParser):
self.keys_to_validate = self.conversion_dict.keys()
self.fieldnames = header
self._datemode = 0 # used only for xls documents,
- # 0 means Windows mode (1900 based dates).
- # Set in _parse_xls, from the contents of the file
+ # 0 means Windows mode (1900 based dates).
+ # Set in _parse_xls, from the contents of the file
def _custom_format(self, *args, **kwargs):
- """
- No other work on data are needed in this parser.
- """
+ """No other work on data are needed in this parser."""
return True
def _pre(self, *args, **kwargs):
- """
- No pre-treatment needed for this parser.
- """
+ """No pre-treatment needed for this parser."""
return True
def _parse(self, *args, **kwargs):
- """
- Launch the parsing through .csv, .xls or .xlsx depending on the
+ """Launch the parsing through .csv, .xls or .xlsx depending on the
given ftype
"""
-
res = None
if self.ftype == 'csv':
res = self._parse_csv()
@@ -94,31 +93,27 @@ class FileParser(BankStatementImportParser):
return True
def _validate(self, *args, **kwargs):
- """
- We check that all the key of the given file (means header) are present
- in the validation key provided. Otherwise, we raise an Exception.
- We skip the validation step if the file header is provided separately
- (in the field: fieldnames).
+ """We check that all the key of the given file (means header) are
+ present in the validation key provided. Otherwise, we raise an
+ Exception. We skip the validation step if the file header is provided
+ separately (in the field: fieldnames).
"""
if self.fieldnames is None:
parsed_cols = self.result_row_list[0].keys()
for col in self.keys_to_validate:
if col not in parsed_cols:
- raise except_osv(_('Invalid data'),
+ raise except_orm(_('Invalid data'),
_('Column %s not present in file') % col)
return True
def _post(self, *args, **kwargs):
- """
- Cast row type depending on the file format .csv or .xls after parsing the file.
- """
+ """Cast row type depending on the file format .csv or .xls after
+ parsing the file."""
self.result_row_list = self._cast_rows(*args, **kwargs)
return True
def _parse_csv(self):
- """
- :return: list of dict from csv file (line/rows)
- """
+ """:return: list of dict from csv file (line/rows)"""
csv_file = tempfile.NamedTemporaryFile()
csv_file.write(self.filebuffer)
csv_file.flush()
@@ -127,9 +122,7 @@ class FileParser(BankStatementImportParser):
return list(reader)
def _parse_xls(self):
- """
- :return: dict of dict from xls/xlsx file (line/rows)
- """
+ """:return: dict of dict from xls/xlsx file (line/rows)"""
wb_file = tempfile.NamedTemporaryFile()
wb_file.write(self.filebuffer)
# We ensure that cursor is at beginig of file
@@ -144,8 +137,7 @@ class FileParser(BankStatementImportParser):
return res
def _from_csv(self, result_set, conversion_rules):
- """
- Handle the converstion from the dict and handle date format from
+ """Handle the converstion from the dict and handle date format from
an .csv file.
"""
for line in result_set:
@@ -156,65 +148,60 @@ class FileParser(BankStatementImportParser):
line[rule] = datetime.datetime.strptime(date_string,
'%Y-%m-%d')
except ValueError as err:
- raise except_osv(_("Date format is not valid."),
- _(" It should be YYYY-MM-DD for column: %s"
- " value: %s \n \n"
- " \n Please check the line with ref: %s"
- " \n \n Detail: %s") % (rule,
- line.get(rule, _('Missing')),
- line.get('ref', line),
- repr(err)))
+ raise except_orm(
+ _("Date format is not valid."),
+ _(" It should be YYYY-MM-DD for column: %s"
+ " value: %s \n \n \n Please check the line with "
+ "ref: %s \n \n Detail: %s") %
+ (rule, line.get(rule, _('Missing')),
+ line.get('ref', line), repr(err)))
else:
try:
line[rule] = conversion_rules[rule](line[rule])
except Exception as err:
- raise except_osv(_('Invalid data'),
- _("Value %s of column %s is not valid."
- "\n Please check the line with ref %s:"
- "\n \n Detail: %s") % (line.get(rule, _('Missing')),
- rule,
- line.get('ref', line),
- repr(err)))
+ raise except_orm(
+ _('Invalid data'),
+ _("Value %s of column %s is not valid.\n Please "
+ "check the line with ref %s:\n \n Detail: %s") %
+ (line.get(rule, _('Missing')), rule,
+ line.get('ref', line), repr(err)))
return result_set
def _from_xls(self, result_set, conversion_rules):
- """
- Handle the converstion from the dict and handle date format from
+ """Handle the converstion from the dict and handle date format from
an .csv, .xls or .xlsx file.
"""
for line in result_set:
for rule in conversion_rules:
if conversion_rules[rule] == datetime.datetime:
try:
- t_tuple = xlrd.xldate_as_tuple(line[rule], self._datemode)
+ t_tuple = xlrd.xldate_as_tuple(line[rule],
+ self._datemode)
line[rule] = datetime.datetime(*t_tuple)
except Exception as err:
- raise except_osv(_("Date format is not valid"),
- _("Please modify the cell formatting to date format"
- " for column: %s"
- " value: %s"
- "\n Please check the line with ref: %s"
- "\n \n Detail: %s") % (rule,
- line.get(rule, _('Missing')),
- line.get('ref', line),
- repr(err)))
+ raise except_orm(
+ _("Date format is not valid"),
+ _("Please modify the cell formatting to date format"
+ " for column: %s value: %s\n Please check the "
+ "line with ref: %s\n \n Detail: %s") %
+ (rule, line.get(rule, _('Missing')),
+ line.get('ref', line), repr(err)))
else:
try:
line[rule] = conversion_rules[rule](line[rule])
except Exception as err:
- raise except_osv(_('Invalid data'),
- _("Value %s of column %s is not valid."
- "\n Please check the line with ref %s:"
- "\n \n Detail: %s") % (line.get(rule, _('Missing')),
- rule,
- line.get('ref', line),
- repr(err)))
+ raise except_orm(
+ _('Invalid data'),
+ _("Value %s of column %s is not valid.\n Please "
+ "check the line with ref %s:\n \n Detail: %s") %
+ (line.get(rule, _('Missing')), rule,
+ line.get('ref', line), repr(err)))
return result_set
def _cast_rows(self, *args, **kwargs):
- """
- Convert the self.result_row_list using the self.conversion_dict providen.
- We call here _from_xls or _from_csv depending on the self.ftype variable.
+ """Convert the self.result_row_list using the self.conversion_dict
+ providen. We call here _from_xls or _from_csv depending on the
+ self.ftype variable.
"""
func = getattr(self, '_from_%s' % self.ftype)
res = func(self.result_row_list, self.conversion_dict)
diff --git a/account_statement_base_import/parser/generic_file_parser.py b/account_statement_base_import/parser/generic_file_parser.py
index 81e51c8c..710c5595 100644
--- a/account_statement_base_import/parser/generic_file_parser.py
+++ b/account_statement_base_import/parser/generic_file_parser.py
@@ -18,32 +18,23 @@
#
##############################################################################
-from openerp.tools.translate import _
-import base64
-import csv
-import tempfile
import datetime
from file_parser import FileParser
-try:
- import xlrd
-except:
- raise Exception(_('Please install python lib xlrd'))
class GenericFileParser(FileParser):
- """
- Standard parser that use a define format in csv or xls to import into a
+ """Standard parser that use a define format in csv or xls to import into a
bank statement. This is mostely an example of how to proceed to create a new
parser, but will also be useful as it allow to import a basic flat file.
"""
def __init__(self, parse_name, ftype='csv', **kwargs):
- super(GenericFileParser, self).__init__(parse_name, ftype=ftype, **kwargs)
+ super(GenericFileParser, self).__init__(
+ parse_name, ftype=ftype, **kwargs)
@classmethod
def parser_for(cls, parser_name):
- """
- Used by the new_bank_statement_parser class factory. Return true if
+ """Used by the new_bank_statement_parser class factory. Return true if
the providen name is generic_csvxls_so
"""
return parser_name == 'generic_csvxls_so'
@@ -54,9 +45,10 @@ class GenericFileParser(FileParser):
method of statement line in order to record it. It is the responsibility
of every parser to give this dict of vals, so each one can implement his
own way of recording the lines.
- :param: line: a dict of vals that represent a line of result_row_list
- :return: dict of values to give to the create method of statement line,
- it MUST contain at least:
+ :param: line: a dict of vals that represent a line of
+ result_row_list
+ :return: dict of values to give to the create method of statement
+ line, it MUST contain at least:
{
'name':value,
'date':value,
diff --git a/account_statement_base_import/parser/parser.py b/account_statement_base_import/parser/parser.py
index 929799c7..6a9be611 100644
--- a/account_statement_base_import/parser/parser.py
+++ b/account_statement_base_import/parser/parser.py
@@ -21,6 +21,7 @@
import base64
import csv
from datetime import datetime
+from openerp.tools.translate import _
def UnicodeDictReader(utf8_data, **kwargs):
@@ -31,10 +32,12 @@ def UnicodeDictReader(utf8_data, **kwargs):
dialect = sniffer.sniff(sample_data, delimiters=',;\t')
csv_reader = csv.DictReader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
- yield dict([(key, unicode(value, 'utf-8')) for key, value in row.iteritems()])
+ yield dict([(key, unicode(value, 'utf-8')) for key, value in
+ row.iteritems()])
class BankStatementImportParser(object):
+
"""
Generic abstract class for defining parser for different files and
format to import in a bank statement. Inherit from it to create your
@@ -60,23 +63,19 @@ class BankStatementImportParser(object):
@classmethod
def parser_for(cls, parser_name):
- """
- Override this method for every new parser, so that new_bank_statement_parser can
- return the good class from his name.
+ """Override this method for every new parser, so that
+ new_bank_statement_parser can return the good class from his name.
"""
return False
def _decode_64b_stream(self):
- """
- Decode self.filebuffer in base 64 and override it
- """
+ """Decode self.filebuffer in base 64 and override it"""
self.filebuffer = base64.b64decode(self.filebuffer)
return True
def _format(self, decode_base_64=True, **kwargs):
- """
- Decode into base 64 if asked and Format the given filebuffer by calling
- _custom_format method.
+ """Decode into base 64 if asked and Format the given filebuffer by
+ calling _custom_format method.
"""
if decode_base_64:
self._decode_64b_stream()
@@ -84,81 +83,76 @@ class BankStatementImportParser(object):
return True
def _custom_format(self, *args, **kwargs):
- """
- Implement a method in your parser to convert format, encoding and so on before
- starting to work on datas. Work on self.filebuffer
+ """Implement a method in your parser to convert format, encoding and so
+ on before starting to work on datas. Work on self.filebuffer
"""
return NotImplementedError
def _pre(self, *args, **kwargs):
- """
- Implement a method in your parser to make a pre-treatment on datas before parsing
- them, like concatenate stuff, and so... Work on self.filebuffer
+ """Implement a method in your parser to make a pre-treatment on datas
+ before parsing them, like concatenate stuff, and so... Work on
+ self.filebuffer
"""
return NotImplementedError
def _parse(self, *args, **kwargs):
- """
- Implement a method in your parser to save the result of parsing self.filebuffer
- in self.result_row_list instance property.
+ """Implement a method in your parser to save the result of parsing
+ self.filebuffer in self.result_row_list instance property.
"""
return NotImplementedError
def _validate(self, *args, **kwargs):
- """
- Implement a method in your parser to validate the self.result_row_list instance
- property and raise an error if not valid.
+ """Implement a method in your parser to validate the
+ self.result_row_list instance property and raise an error if not valid.
"""
return NotImplementedError
def _post(self, *args, **kwargs):
- """
- Implement a method in your parser to make some last changes on the result of parsing
- the datas, like converting dates, computing commission, ...
+ """Implement a method in your parser to make some last changes on the
+ result of parsing the datas, like converting dates, computing
+ commission, ...
"""
return NotImplementedError
def get_st_vals(self):
- """
- This method return a dict of vals that ca be passed to
- create method of statement.
+ """This method return a dict of vals that ca be passed to create method
+ of statement.
:return: dict of vals that represent additional infos for the statement
"""
return {
- 'name': self.statement_name or '/',
- 'balance_start': self.balance_start,
- 'balance_end_real': self.balance_end,
- 'date': self.statement_date or datetime.now()
+ 'name': self.statement_name or '/',
+ 'balance_start': self.balance_start,
+ 'balance_end_real': self.balance_end,
+ 'date': self.statement_date or datetime.now()
}
def get_st_line_vals(self, line, *args, **kwargs):
- """
- Implement a method in your parser that must return a dict of vals that can be
- passed to create method of statement line in order to record it. It is the responsibility
- of every parser to give this dict of vals, so each one can implement his
- own way of recording the lines.
- :param: line: a dict of vals that represent a line of result_row_list
- :return: dict of values to give to the create method of statement line,
- it MUST contain at least:
- {
- 'name':value,
- 'date':value,
- 'amount':value,
- 'ref':value,
- }
+ """Implement a method in your parser that must return a dict of vals
+ that can be passed to create method of statement line in order to record
+ it. It is the responsibility of every parser to give this dict of vals,
+ so each one can implement his own way of recording the lines.
+
+ :param: line: a dict of vals that represent a line of result_row_list
+ :return: dict of values to give to the create method of statement line,
+ it MUST contain at least:
+ {
+ 'name':value,
+ 'date':value,
+ 'amount':value,
+ 'ref':value,
+ }
"""
return NotImplementedError
def parse(self, filebuffer, *args, **kwargs):
- """
- This will be the method that will be called by wizard, button and so
+ """This will be the method that will be called by wizard, button and so
to parse a filebuffer by calling successively all the private method
that need to be define for each parser.
Return:
[] of rows as {'key':value}
- Note: The row_list must contain only value that are present in the account.
- bank.statement.line object !!!
+ Note: The row_list must contain only value that are present in the
+ account.bank.statement.line object !!!
"""
if filebuffer:
self.filebuffer = filebuffer
@@ -221,7 +215,7 @@ def itersubclasses(cls, _seen=None):
def new_bank_statement_parser(profile, *args, **kwargs):
"""Return an instance of the good parser class based on the given profile.
-
+
:param profile: browse_record of import profile.
:return: class instance for given profile import type.
"""
diff --git a/account_statement_base_import/statement.py b/account_statement_base_import/statement.py
index eb89c64b..2bacb45c 100644
--- a/account_statement_base_import/statement.py
+++ b/account_statement_base_import/statement.py
@@ -20,16 +20,14 @@
##############################################################################
import sys
import traceback
-
from openerp.tools.translate import _
import datetime
-from openerp.osv.orm import Model
-from openerp.osv import fields, osv
+from openerp.osv import fields, orm
from parser import new_bank_statement_parser
from openerp.tools.config import config
-class AccountStatementProfil(Model):
+class AccountStatementProfil(orm.Model):
_inherit = "account.statement.profile"
def _get_import_type_selection(self, cr, uid, context=None):
@@ -46,7 +44,8 @@ class AccountStatementProfil(Model):
help="Tic that box to automatically launch the completion "
"on each imported file using this profile."),
'last_import_date': fields.datetime("Last Import Date"),
- # we remove deprecated as it floods logs in standard/warning level sob...
+ # we remove deprecated as it floods logs in standard/warning level
+ # sob...
'rec_log': fields.text('log', readonly=True), # Deprecated
'import_type': fields.selection(
__get_import_type_selection,
@@ -57,56 +56,55 @@ class AccountStatementProfil(Model):
}
_defaults = {
- 'import_type': 'generic_csvxls_so'
- }
+ 'import_type': 'generic_csvxls_so'
+ }
def _write_extra_statement_lines(
- self, cr, uid, parser, result_row_list, profile, statement_id, context):
+ self, cr, uid, parser, result_row_list, profile, statement_id,
+ context):
"""Insert extra lines after the main statement lines.
- After the main statement lines have been created, you can override this method to create
- extra statement lines.
+ After the main statement lines have been created, you can override this
+ method to create extra statement lines.
:param: browse_record of the current parser
:param: result_row_list: [{'key':value}]
:param: profile: browserecord of account.statement.profile
- :param: statement_id: int/long of the current importing statement ID
+ :param: statement_id: int/long of the current importing
+ statement ID
:param: context: global context
"""
pass
- def write_logs_after_import(self, cr, uid, ids, statement_id, num_lines, context):
- """
- Write the log in the logger
+ def write_logs_after_import(self, cr, uid, ids, statement_id, num_lines,
+ context):
+ """Write the log in the logger
:param int/long statement_id: ID of the concerned account.bank.statement
:param int/long num_lines: Number of line that have been parsed
:return: True
"""
- self.message_post(cr,
- uid,
- ids,
- body=_('Statement ID %s have been imported with %s lines.') %
- (statement_id, num_lines),
- context=context)
+ self.message_post(
+ cr, uid, ids,
+ body=_('Statement ID %s have been imported with %s '
+ 'lines.') % (statement_id, num_lines), context=context)
return True
- #Deprecated remove on V8
+ # Deprecated remove on V8
def prepare_statetement_lines_vals(self, *args, **kwargs):
return self.prepare_statement_lines_vals(*args, **kwargs)
- def prepare_statement_lines_vals(
- self, cr, uid, parser_vals,
- statement_id, context):
- """
- Hook to build the values of a line from the parser returned values. At
- least it fullfill the statement_id. Overide it to add your
- own completion if needed.
+ def prepare_statement_lines_vals(self, cr, uid, parser_vals,
+ statement_id, context):
+ """Hook to build the values of a line from the parser returned values.
+ At least it fullfill the statement_id. Overide it to add your own
+ completion if needed.
- :param dict of vals from parser for account.bank.statement.line (called by
- parser.get_st_line_vals)
+ :param dict of vals from parser for account.bank.statement.line
+ (called by parser.get_st_line_vals)
:param int/long statement_id: ID of the concerned account.bank.statement
- :return: dict of vals that will be passed to create method of statement line.
+ :return: dict of vals that will be passed to create method of
+ statement line.
"""
statement_line_obj = self.pool['account.bank.statement.line']
values = parser_vals
@@ -120,18 +118,17 @@ class AccountStatementProfil(Model):
values['period_id'] = period_memoizer[date]
else:
# This is awfully slow...
- periods = self.pool.get('account.period').find(cr, uid,
- dt=values.get('date'),
- context=context)
+ periods = self.pool.get('account.period').find(
+ cr, uid, dt=values.get('date'), context=context)
values['period_id'] = periods[0]
period_memoizer[date] = periods[0]
- values = statement_line_obj._add_missing_default_values(cr, uid, values, context)
+ values = statement_line_obj._add_missing_default_values(
+ cr, uid, values, context)
return values
def prepare_statement_vals(self, cr, uid, profile_id, result_row_list,
parser, context=None):
- """
- Hook to build the values of the statement from the parser and
+ """Hook to build the values of the statement from the parser and
the profile.
"""
vals = {'profile_id': profile_id}
@@ -148,9 +145,8 @@ class AccountStatementProfil(Model):
def multi_statement_import(self, cr, uid, ids, profile_id, file_stream,
ftype="csv", context=None):
- """
- Create multiple bank statements from values given by the parser for the
- givenprofile.
+ """Create multiple bank statements from values given by the parser for
+ the given profile.
:param int/long profile_id: ID of the profile used to import the file
:param filebuffer file_stream: binary of the providen file
@@ -159,23 +155,26 @@ class AccountStatementProfil(Model):
"""
prof_obj = self.pool['account.statement.profile']
if not profile_id:
- raise osv.except_osv(_("No Profile!"),
- _("You must provide a valid profile to import a bank statement!"))
+ raise orm.except_orm(
+ _("No Profile!"),
+ _("You must provide a valid profile to import a bank "
+ "statement!"))
prof = prof_obj.browse(cr, uid, profile_id, context=context)
-
parser = new_bank_statement_parser(prof, ftype=ftype)
res = []
for result_row_list in parser.parse(file_stream):
- statement_id = self._statement_import(cr, uid, ids, prof, parser,
- file_stream, ftype=ftype, context=context)
+ statement_id = self._statement_import(
+ cr, uid, ids, prof, parser, file_stream, ftype=ftype,
+ context=context)
res.append(statement_id)
return res
- def _statement_import(self, cr, uid, ids, prof, parser, file_stream, ftype="csv", context=None):
- """
- Create a bank statement with the given profile and parser. It will fullfill the bank statement
- with the values of the file providen, but will not complete data (like finding the partner, or
- the right account). This will be done in a second step with the completion rules.
+ def _statement_import(self, cr, uid, ids, prof, parser, file_stream,
+ ftype="csv", context=None):
+ """Create a bank statement with the given profile and parser. It will
+ fullfill the bank statement with the values of the file providen, but
+ will not complete data (like finding the partner, or the right account).
+ This will be done in a second step with the completion rules.
:param prof : The profile used to import the file
:param parser: the parser
@@ -183,27 +182,25 @@ class AccountStatementProfil(Model):
:param char: ftype represent the file exstension (csv by default)
:return: ID of the created account.bank.statemênt
"""
- statement_obj = self.pool.get('account.bank.statement')
- statement_line_obj = self.pool.get('account.bank.statement.line')
- attachment_obj = self.pool.get('ir.attachment')
-
+ statement_obj = self.pool['account.bank.statement']
+ statement_line_obj = self.pool['account.bank.statement.line']
+ attachment_obj = self.pool['ir.attachment']
result_row_list = parser.result_row_list
# Check all key are present in account.bank.statement.line!!
if not result_row_list:
- raise osv.except_osv(_("Nothing to import"),
+ raise orm.except_orm(_("Nothing to import"),
_("The file is empty"))
parsed_cols = parser.get_st_line_vals(result_row_list[0]).keys()
for col in parsed_cols:
if col not in statement_line_obj._columns:
- raise osv.except_osv(_("Missing column!"),
- _("Column %s you try to import is not "
- "present in the bank statement line!") % col)
-
- statement_vals = self.prepare_statement_vals(cr, uid, prof.id, result_row_list, parser, context)
- statement_id = statement_obj.create(cr, uid,
- statement_vals,
- context=context)
-
+ raise orm.except_orm(
+ _("Missing column!"),
+ _("Column %s you try to import is not present in the bank "
+ "statement line!") % col)
+ statement_vals = self.prepare_statement_vals(
+ cr, uid, prof.id, result_row_list, parser, context)
+ statement_id = statement_obj.create(
+ cr, uid, statement_vals, context=context)
try:
# Record every line in the bank statement
statement_store = []
@@ -214,44 +211,44 @@ class AccountStatementProfil(Model):
context)
statement_store.append(values)
# Hack to bypass ORM poor perfomance. Sob...
- statement_line_obj._insert_lines(cr, uid, statement_store, context=context)
-
+ statement_line_obj._insert_lines(
+ cr, uid, statement_store, context=context)
self._write_extra_statement_lines(
cr, uid, parser, result_row_list, prof, statement_id, context)
# Trigger store field computation if someone has better idea
start_bal = statement_obj.read(
cr, uid, statement_id, ['balance_start'], context=context)
start_bal = start_bal['balance_start']
- statement_obj.write(cr, uid, [statement_id], {'balance_start': start_bal})
-
+ statement_obj.write(
+ cr, uid, [statement_id], {'balance_start': start_bal})
attachment_data = {
'name': 'statement file',
'datas': file_stream,
- 'datas_fname': "%s.%s" % (datetime.datetime.now().date(), ftype),
+ 'datas_fname': "%s.%s" % (datetime.datetime.now().date(),
+ ftype),
'res_model': 'account.bank.statement',
'res_id': statement_id,
}
attachment_obj.create(cr, uid, attachment_data, context=context)
-
# If user ask to launch completion at end of import, do it!
if prof.launch_import_completion:
- statement_obj.button_auto_completion(cr, uid, [statement_id], context)
-
+ statement_obj.button_auto_completion(
+ cr, uid, [statement_id], context)
# Write the needed log infos on profile
self.write_logs_after_import(cr, uid, prof.id,
statement_id,
len(result_row_list),
context)
-
except Exception:
error_type, error_value, trbk = sys.exc_info()
- st = "Error: %s\nDescription: %s\nTraceback:" % (error_type.__name__, error_value)
+ st = "Error: %s\nDescription: %s\nTraceback:" % (
+ error_type.__name__, error_value)
st += ''.join(traceback.format_tb(trbk, 30))
- #TODO we should catch correctly the exception with a python
- #Exception and only re-catch some special exception.
- #For now we avoid re-catching error in debug mode
+ # TODO we should catch correctly the exception with a python
+ # Exception and only re-catch some special exception.
+ # For now we avoid re-catching error in debug mode
if config['debug_mode']:
raise
- raise osv.except_osv(_("Statement import error"),
+ raise orm.except_orm(_("Statement import error"),
_("The statement cannot be created: %s") % st)
return statement_id
diff --git a/account_statement_base_import/statement_view.xml b/account_statement_base_import/statement_view.xml
index ded05b28..b73e0dc7 100644
--- a/account_statement_base_import/statement_view.xml
+++ b/account_statement_base_import/statement_view.xml
@@ -7,7 +7,6 @@
account.statement.profile.view
account.statement.profile
- form
@@ -31,7 +30,6 @@
account_bank_statement.bank_statement.view_form
account.bank.statement
- form
diff --git a/account_statement_base_import/tests/test_base_import.py b/account_statement_base_import/tests/test_base_import.py
index f48aea66..eea31069 100644
--- a/account_statement_base_import/tests/test_base_import.py
+++ b/account_statement_base_import/tests/test_base_import.py
@@ -22,19 +22,19 @@
import base64
import inspect
import os
-
from openerp.tests import common
-class test_coda_import(common.TransactionCase):
+class TestCodaImport(common.TransactionCase):
def prepare(self):
self.company_a = self.browse_ref('base.main_company')
self.profile_obj = self.registry("account.statement.profile")
- self.account_bank_statement_obj = self.registry("account.bank.statement")
- # create the 2009 fiscal year since imported coda file reference statement lines in 2009
+ self.account_bank_statement_obj = self.registry(
+ "account.bank.statement")
+ # create the 2009 fiscal year since imported coda file reference
+ # statement lines in 2009
self.fiscalyear_id = self._create_fiscalyear("2011", self.company_a.id)
-
self.account_id = self.ref("account.a_recv")
self.journal_id = self.ref("account.bank_journal")
self.import_wizard_obj = self.registry('credit.statement.import')
@@ -71,15 +71,19 @@ class test_coda_import(common.TransactionCase):
'input_statement': base64.b64encode(content),
'file_name': os.path.basename(file_name),
})
- res = self.import_wizard_obj.import_statement(self.cr, self.uid, wizard_id)
- statement_id = self.account_bank_statement_obj.search(self.cr, self.uid, eval(res['domain']))
- return self.account_bank_statement_obj.browse(self.cr, self.uid, statement_id)[0]
+ res = self.import_wizard_obj.import_statement(
+ self.cr, self.uid, wizard_id)
+ statement_id = self.account_bank_statement_obj.search(
+ self.cr, self.uid, eval(res['domain']))
+ return self.account_bank_statement_obj.browse(
+ self.cr, self.uid, statement_id)[0]
def test_simple_xls(self):
"""Test import from xls
"""
self.prepare()
- file_name = self._filename_to_abs_filename(os.path.join("..", "data", "statement.xls"))
+ file_name = self._filename_to_abs_filename(
+ os.path.join("..", "data", "statement.xls"))
statement = self._import_file(file_name)
self._validate_imported_satement(statement)
@@ -87,7 +91,8 @@ class test_coda_import(common.TransactionCase):
"""Test import from csv
"""
self.prepare()
- file_name = self._filename_to_abs_filename(os.path.join("..", "data", "statement.csv"))
+ file_name = self._filename_to_abs_filename(
+ os.path.join("..", "data", "statement.csv"))
statement = self._import_file(file_name)
self._validate_imported_satement(statement)
diff --git a/account_statement_base_import/wizard/import_statement.py b/account_statement_base_import/wizard/import_statement.py
index 83fa6ffb..e030d5ff 100644
--- a/account_statement_base_import/wizard/import_statement.py
+++ b/account_statement_base_import/wizard/import_statement.py
@@ -36,12 +36,15 @@ class CreditPartnerStatementImporter(orm.TransientModel):
if context is None:
context = {}
res = {}
- if (context.get('active_model', False) == 'account.statement.profile' and
- context.get('active_ids', False)):
+ if (context.get('active_model', False) ==
+ 'account.statement.profile' and
+ context.get('active_ids', False)):
ids = context['active_ids']
- assert len(ids) == 1, 'You cannot use this on more than one profile !'
+ assert len(
+ ids) == 1, 'You cannot use this on more than one profile !'
res['profile_id'] = ids[0]
- other_vals = self.onchange_profile_id(cr, uid, [], res['profile_id'], context=context)
+ other_vals = self.onchange_profile_id(
+ cr, uid, [], res['profile_id'], context=context)
res.update(other_vals.get('value', {}))
return res
@@ -55,8 +58,8 @@ class CreditPartnerStatementImporter(orm.TransientModel):
'journal_id': fields.many2one('account.journal',
'Financial journal to use transaction'),
'file_name': fields.char('File Name', size=128),
- 'receivable_account_id': fields.many2one('account.account',
- 'Force Receivable/Payable Account'),
+ 'receivable_account_id': fields.many2one(
+ 'account.account', 'Force Receivable/Payable Account'),
'force_partner_on_bank': fields.boolean(
'Force partner on bank move',
help="Tic that box if you want to use the credit insitute partner "
@@ -71,22 +74,22 @@ class CreditPartnerStatementImporter(orm.TransientModel):
def onchange_profile_id(self, cr, uid, ids, profile_id, context=None):
res = {}
if profile_id:
- c = self.pool.get("account.statement.profile").browse(
- cr, uid, profile_id, context=context)
+ c = self.pool["account.statement.profile"].browse(
+ cr, uid, profile_id, context=context)
res = {'value':
- {'partner_id': c.partner_id and c.partner_id.id or False,
- 'journal_id': c.journal_id and c.journal_id.id or False,
- 'receivable_account_id': c.receivable_account_id and c.receivable_account_id.id or False,
- 'force_partner_on_bank': c.force_partner_on_bank,
- 'balance_check': c.balance_check,
- }
- }
+ {'partner_id': c.partner_id and c.partner_id.id or False,
+ 'journal_id': c.journal_id and c.journal_id.id or False,
+ 'receivable_account_id': c.receivable_account_id.id,
+ 'force_partner_on_bank': c.force_partner_on_bank,
+ 'balance_check': c.balance_check,
+ }
+ }
return res
def _check_extension(self, filename):
(__, ftype) = os.path.splitext(filename)
if not ftype:
- #We do not use osv exception we do not want to have it logged
+ # We do not use osv exception we do not want to have it logged
raise Exception(_('Please use a file with an extention'))
return ftype
@@ -99,18 +102,19 @@ class CreditPartnerStatementImporter(orm.TransientModel):
ftype = self._check_extension(importer.file_name)
context['file_name'] = importer.file_name
sid = self.pool.get(
- 'account.statement.profile').multi_statement_import(
- cr,
- uid,
- False,
- importer.profile_id.id,
- importer.input_statement,
- ftype.replace('.', ''),
- context=context
- )
+ 'account.statement.profile').multi_statement_import(
+ cr,
+ uid,
+ False,
+ importer.profile_id.id,
+ importer.input_statement,
+ ftype.replace('.', ''),
+ context=context
+ )
model_obj = self.pool.get('ir.model.data')
action_obj = self.pool.get('ir.actions.act_window')
- action_id = model_obj.get_object_reference(cr, uid, 'account', 'action_bank_statement_tree')[1]
+ action_id = model_obj.get_object_reference(
+ cr, uid, 'account', 'action_bank_statement_tree')[1]
res = action_obj.read(cr, uid, action_id)
res['domain'] = res['domain'][:-1] + ",('id', 'in', %s)]" % sid
return res
diff --git a/account_statement_base_import/wizard/import_statement_view.xml b/account_statement_base_import/wizard/import_statement_view.xml
index 51ec4740..7654e934 100644
--- a/account_statement_base_import/wizard/import_statement_view.xml
+++ b/account_statement_base_import/wizard/import_statement_view.xml
@@ -4,7 +4,6 @@
credit.statement.import.config.view
credit.statement.import
- form
diff --git a/account_statement_completion_label/statement.py b/account_statement_completion_label/statement.py
index 0d50ae56..aef6cb36 100644
--- a/account_statement_completion_label/statement.py
+++ b/account_statement_completion_label/statement.py
@@ -22,14 +22,16 @@
from openerp.osv import fields, orm
from collections import defaultdict
-from openerp.addons.account_statement_base_completion.statement import ErrorTooManyPartner
+from openerp.tools.translate import _
+from openerp.addons.account_statement_base_completion.statement import \
+ ErrorTooManyPartner
class ErrorTooManyLabel(Exception):
+ """New Exception definition that is raised when more than one label is
+ matched by the completion rule.
"""
- New Exception definition that is raised when more than one label is matched
- by the completion rule.
- """
+
def __init__(self, value):
self.value = value
@@ -38,8 +40,7 @@ class ErrorTooManyLabel(Exception):
class AccountBankSatement(orm.Model):
- """
- We add a basic button and stuff to support the auto-completion
+ """We add a basic button and stuff to support the auto-completion
of the bank statement once line have been imported or manually fullfill.
"""
_inherit = "account.bank.statement"
@@ -60,8 +61,7 @@ class AccountStatementCompletionRule(orm.Model):
_inherit = "account.statement.completion.rule"
def get_from_label_and_partner_field(self, cr, uid, st_line, context=None):
- """
- Match the partner and the account based on the name field of the
+ """Match the partner and the account based on the name field of the
statement line and the table account.statement.label.
If more than one statement label matched, raise the ErrorTooManylabel
error.
@@ -75,14 +75,14 @@ class AccountStatementCompletionRule(orm.Model):
...}
"""
- st_obj = self.pool.get('account.bank.statement')
- statement = st_obj.browse(cr, uid, st_line['statement_id'][0],
+ st_obj = self.pool['account.bank.statement']
+ statement = st_obj.browse(cr, uid, st_line['statement_id'][0],
context=context)
res = {}
if not context.get('label_memorizer'):
context['label_memorizer'] = defaultdict(list)
for line in statement.line_ids:
- cr.execute("""
+ cr.execute("""
SELECT l.partner_id,
l.account_id
FROM account_statement_label as l,
@@ -99,14 +99,14 @@ class AccountStatementCompletionRule(orm.Model):
st_l.id = %s
""", (line.id,))
for partner, account in cr.fetchall():
- context['label_memorizer'][line.id].append({'partner_id': partner,
- 'account_id': account})
+ context['label_memorizer'][line.id].append(
+ {'partner_id': partner, 'account_id': account})
if st_line['id'] in context['label_memorizer']:
label_info = context['label_memorizer'][st_line['id']]
if len(label_info) > 1:
- raise ErrorTooManyPartner(_('Line named "%s" (Ref:%s) was matched by '
- 'more than one statement label.') %
- (st_line['name'], st_line['ref']))
+ raise ErrorTooManyPartner(
+ _('Line named "%s" (Ref:%s) was matched by more than one '
+ 'statement label.') % (st_line['name'], st_line['ref']))
if label_info[0]['partner_id']:
res['partner_id'] = label_info[0]['partner_id']
res['account_id'] = label_info[0]['account_id']
@@ -118,14 +118,13 @@ class AccountStatementLabel(orm.Model):
and a specific account
"""
_name = "account.statement.label"
-
_description = "Account Statement Label"
_columns = {
'partner_id': fields.many2one('res.partner', 'Partner'),
'label': fields.char('Bank Statement Label', size=100),
'account_id': fields.many2one('account.account', 'Account',
- required = True,
+ required=True,
help='Account corresponding to the label '
'for a given partner'),
'company_id': fields.related('account_id', 'company_id',
@@ -139,10 +138,9 @@ class AccountStatementLabel(orm.Model):
}
_defaults = {
- 'company_id': lambda s,cr,uid,c:
- s.pool.get('res.company')._company_default_get(cr, uid,
- 'account.statement.label',
- context=c),
+ 'company_id': lambda s, cr, uid, c:
+ s.pool.get('res.company')._company_default_get(
+ cr, uid, 'account.statement.label', context=c),
}
_sql_constraints = [
diff --git a/account_statement_completion_voucher/__openerp__.py b/account_statement_completion_voucher/__openerp__.py
index b8337a80..ef6ec980 100644
--- a/account_statement_completion_voucher/__openerp__.py
+++ b/account_statement_completion_voucher/__openerp__.py
@@ -28,14 +28,15 @@
'depends': [
'account_statement_base_completion',
'account_voucher'
- ],
+ ],
'description': """
- This module is only needed when using account_statement_base_completion with voucher in order adapt the view correctly.
+ This module is only needed when using account_statement_base_completion with
+ voucher in order adapt the view correctly.
""",
'website': 'http://www.camptocamp.com',
'init_xml': [],
'update_xml': [
- "statement_view.xml",
+ "statement_view.xml",
],
'demo_xml': [],
'test': [],
@@ -43,4 +44,4 @@
'images': [],
'auto_install': False,
'license': 'AGPL-3',
-}
+ }
diff --git a/account_statement_ext/__init__.py b/account_statement_ext/__init__.py
index 7194652a..7bf22aa2 100644
--- a/account_statement_ext/__init__.py
+++ b/account_statement_ext/__init__.py
@@ -22,4 +22,4 @@
import statement
import report
import account
-import voucher
\ No newline at end of file
+import voucher
diff --git a/account_statement_ext/__openerp__.py b/account_statement_ext/__openerp__.py
index abf83d87..1cd090c6 100644
--- a/account_statement_ext/__openerp__.py
+++ b/account_statement_ext/__openerp__.py
@@ -29,14 +29,14 @@
'report_webkit',
'account_voucher'],
'description': """
- Improve the basic bank statement, by adding various new features,
- and help dealing with huge volume of reconciliation through payment offices such as Paypal, Lazer,
- Visa, Amazon...
+ Improve the basic bank statement, by adding various new features, and help
+ dealing with huge volume of reconciliation through payment offices such as
+ Paypal, Lazer, Visa, Amazon...
- It is mostly used for E-commerce but can be useful for other use cases as it introduces a
- notion of profile on the bank statement to have more control on the generated entries. It serves as
- a base for all new features developped to improve the reconciliation process (see our other
- set of modules:
+ It is mostly used for E-commerce but can be useful for other use cases as it
+ introduces a notion of profile on the bank statement to have more control on
+ the generated entries. It serves as a base for all new features developped to
+ improve the reconciliation process (see our other set of modules:
* account_statement_base_completion
* account_statement_base_import
@@ -44,33 +44,38 @@
Features:
- 1) Improve the bank statement: allows to define profiles (for each
- Office or Bank). The bank statement will then generate the entries based on some criteria chosen
- in the selected profile. You can setup on the profile:
+ 1) Improve the bank statement: allows to define profiles (for each Office or
+ Bank). The bank statement will then generate the entries based on some criteria
+ chosen in the selected profile. You can setup on the profile:
- the journal to use
- use balance check or not
- account commission and Analytic account for commission
- - partner concerned by the profile (used in commission and optionaly on generated credit move)
- - use a specific credit account (instead of the receivalble/payable default one)
- - force Partner on the counter-part move (e.g. 100.- debit, Partner: M.Martin; 100.- credit, Partner: HSBC)
+ - partner concerned by the profile (used in commission and optionaly on
+ generated credit move)
+ - use a specific credit account (instead of the receivalble/payable default
+ one)
+ - force Partner on the counter-part move (e.g. 100.- debit, Partner: M.
+ Martin; 100.- credit, Partner: HSBC)
2) Add a report on bank statement that can be used for checks remittance
- 3) When an error occurs in a bank statement confirmation, go through all line anyway and summarize
- all the erronous line in a same popup instead of raising and crashing on every step.
+ 3) When an error occurs in a bank statement confirmation, go through all line
+ anyway and summarize all the erronous line in a same popup instead of
+ raising and crashing on every step.
- 4) Remove the period on the bank statement, and compute it for each line based on their date instead.
- It also adds this feature in the voucher in order to compute the period correctly.
+ 4) Remove the period on the bank statement, and compute it for each line based
+ on their date instead. It also adds this feature in the voucher in order to
+ compute the period correctly.
- 5) Cancelling a bank statement is much more easy and will cancel all related entries, unreconcile them,
- and finally delete them.
-
- 6) Add the ID in entries view so that you can easily filter on a statement ID to reconcile all related
- entries at once (e.g. one statement (ID 100) for paypal on an intermediate account, and then another for
- the bank on the bank account. You can then manually reconcile all the line from the first one with
- one line of the second by finding them through the statement ID.)
+ 5) Cancelling a bank statement is much more easy and will cancel all related
+ entries, unreconcile them, and finally delete them.
+ 6) Add the ID in entries view so that you can easily filter on a statement ID
+ to reconcile all related entries at once (e.g. one statement (ID 100) for
+ Paypal on an intermediate account, and then another for the bank on the
+ bank account. You can then manually reconcile all the line from the first
+ one with one line of the second by finding them through the statement ID.)
""",
'website': 'http://www.camptocamp.com',
'data': ['statement_view.xml',
diff --git a/account_statement_ext/account.py b/account_statement_ext/account.py
index ecd1853c..ac8fefd2 100644
--- a/account_statement_ext/account.py
+++ b/account_statement_ext/account.py
@@ -19,23 +19,21 @@
#
##############################################################################
-from openerp.osv.orm import Model
-from openerp.osv import fields
+from openerp.osv import orm
-class account_move(Model):
+class AccountMove(orm.Model):
_inherit = 'account.move'
def unlink(self, cr, uid, ids, context=None):
- """
- Delete the reconciliation when we delete the moves. This
+ """Delete the reconciliation when we delete the moves. This
allow an easier way of cancelling the bank statement.
"""
reconcile_to_delete = []
- reconcile_obj = self.pool.get('account.move.reconcile')
+ reconcile_obj = self.pool['account.move.reconcile']
for move in self.browse(cr, uid, ids, context=context):
for move_line in move.line_id:
if move_line.reconcile_id:
reconcile_to_delete.append(move_line.reconcile_id.id)
reconcile_obj.unlink(cr, uid, reconcile_to_delete, context=context)
- return super(account_move, self).unlink(cr, uid, ids, context=context)
+ return super(AccountMove, self).unlink(cr, uid, ids, context=context)
diff --git a/account_statement_ext/report/bank_statement_report.py b/account_statement_ext/report/bank_statement_report.py
index 80e6af65..1d9c60cd 100644
--- a/account_statement_ext/report/bank_statement_report.py
+++ b/account_statement_ext/report/bank_statement_report.py
@@ -28,15 +28,18 @@ from openerp.addons.report_webkit import webkit_report
class BankStatementWebkit(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
- super(BankStatementWebkit, self).__init__(cr, uid, name, context=context)
+ super(BankStatementWebkit, self).__init__(
+ cr, uid, name, context=context)
self.pool = pooler.get_pool(self.cr.dbname)
self.cursor = self.cr
company = self.pool.get('res.users').browse(
- self.cr, uid, uid, context=context).company_id
- header_report_name = ' - '.join((_('BORDEREAU DE REMISE DE CHEQUES'),
- company.name, company.currency_id.name))
- footer_date_time = self.formatLang(str(datetime.today())[:19], date_time=True)
+ self.cr, uid, uid, context=context).company_id
+ header_report_name = ' - '.join((
+ _('BORDEREAU DE REMISE DE CHEQUES'),
+ company.name, company.currency_id.name))
+ footer_date_time = self.formatLang(
+ str(datetime.today())[:19], date_time=True)
self.localcontext.update({
'cr': cr,
'uid': uid,
@@ -50,7 +53,8 @@ class BankStatementWebkit(report_sxw.rml_parse):
('--header-left', header_report_name),
('--header-spacing', '2'),
('--footer-left', footer_date_time),
- ('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
+ ('--footer-right',
+ ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-line',),
],
})
@@ -58,14 +62,14 @@ class BankStatementWebkit(report_sxw.rml_parse):
def _get_bank_statement_data(self, statement):
statement_obj = self.pool.get('account.bank.statement.line')
statement_line_ids = statement_obj.search(
- self.cr,
- self.uid,
- [('statement_id', '=', statement.id)])
+ self.cr,
+ self.uid,
+ [('statement_id', '=', statement.id)])
statement_lines = statement_obj.browse(
- self.cr, self.uid, statement_line_ids)
+ self.cr, self.uid, statement_line_ids)
return statement_lines
-webkit_report.WebKitParser('report.bank_statement_webkit',
- 'account.bank.statement',
- 'addons/account_statement_ext/report/bank_statement_report.mako',
- parser=BankStatementWebkit)
+webkit_report.WebKitParser(
+ 'report.bank_statement_webkit', 'account.bank.statement',
+ 'addons/account_statement_ext/report/bank_statement_report.mako',
+ parser=BankStatementWebkit)
diff --git a/account_statement_ext/statement.py b/account_statement_ext/statement.py
index cce5a0b4..68d2eb72 100644
--- a/account_statement_ext/statement.py
+++ b/account_statement_ext/statement.py
@@ -19,8 +19,7 @@
#
##############################################################################
import openerp.addons.account.account_bank_statement as stat_mod
-from openerp.osv.orm import Model
-from openerp.osv import fields, osv
+from openerp.osv import fields, orm
from openerp.tools.translate import _
@@ -29,9 +28,9 @@ def fixed_write(self, cr, uid, ids, vals, context=None):
""" Fix performance desing of original function
Ideally we should use a real PostgreSQL sequence or serial fields.
I will do it when I have time."""
- res = super(stat_mod.account_bank_statement, self).write(cr, uid, ids,
- vals, context=context)
- if ids: # will be false for an new empty bank statement
+ res = super(stat_mod.account_bank_statement, self).write(
+ cr, uid, ids, vals, context=context)
+ if ids: # will be false for an new empty bank statement
cr.execute("UPDATE account_bank_statement_line"
" SET sequence = account_bank_statement_line.id + 1"
" where statement_id in %s", (tuple(ids),))
@@ -39,64 +38,56 @@ def fixed_write(self, cr, uid, ids, vals, context=None):
stat_mod.account_bank_statement.write = fixed_write
-class AccountStatementProfile(Model):
- """
- A Profile will contain all infos related to the type of
+class AccountStatementProfile(orm.Model):
+ """A Profile will contain all infos related to the type of
bank statement, and related generated entries. It defines the
journal to use, the partner and commision account and so on.
"""
_name = "account.statement.profile"
_inherit = ['mail.thread']
-
_description = "Statement Profile"
_order = 'sequence'
_columns = {
'name': fields.char('Name', required=True),
- 'sequence': fields.integer('Sequence', help="Gives a sequence in lists, the first profile will be used as default"),
+ 'sequence': fields.integer(
+ 'Sequence',
+ help="Gives a sequence in lists, the first profile will be used as "
+ "default"),
'partner_id': fields.many2one(
'res.partner',
'Bank/Payment Office partner',
- help="Put a partner if you want to have it on the "
- "commission move (and optionaly on the counterpart "
- "of the intermediate/banking move if you tick the "
- "corresponding checkbox)."),
-
+ help="Put a partner if you want to have it on the commission move "
+ "(and optionaly on the counterpart of the intermediate/"
+ "banking move if you tick the corresponding checkbox)."),
'journal_id': fields.many2one(
'account.journal',
- 'Financial journal to use for transaction',
- required=True),
-
+ 'Financial journal to use for transaction',
+ required=True),
'commission_account_id': fields.many2one(
'account.account',
- 'Commission account',
- required=True),
-
+ 'Commission account',
+ required=True),
'commission_analytic_id': fields.many2one(
'account.analytic.account',
'Commission analytic account'),
-
'receivable_account_id': fields.many2one(
'account.account',
'Force Receivable/Payable Account',
help="Choose a receivable account to force the default "
"debit/credit account (eg. an intermediat bank account "
"instead of default debitors)."),
-
'force_partner_on_bank': fields.boolean(
'Force partner on bank move',
help="Tick that box if you want to use the credit "
"institute partner in the counterpart of the "
"intermediate/banking move."),
-
'balance_check': fields.boolean(
'Balance check',
help="Tick that box if you want OpenERP to control "
"the start/end balance before confirming a bank statement. "
"If don't ticked, no balance control will be done."),
-
'bank_statement_prefix': fields.char('Bank Statement Prefix', size=32),
-
'bank_statement_ids': fields.one2many('account.bank.statement',
'profile_id',
'Bank Statement Imported'),
@@ -110,53 +101,50 @@ class AccountStatementProfile(Model):
return True
_constraints = [
- (_check_partner, "You need to put a partner if you tic the 'Force partner on bank move'!", []),
+ (_check_partner,
+ "You need to put a partner if you tic the 'Force partner on bank "
+ "move'!", []),
]
_sql_constraints = [
- ('name_uniq', 'unique (name, company_id)', 'The name of the bank statement must be unique !')
+ ('name_uniq', 'unique (name, company_id)',
+ 'The name of the bank statement must be unique !')
]
-
-class AccountBankStatement(Model):
- """
- We improve the bank statement class mostly for :
+class AccountBankStatement(orm.Model):
+ """We improve the bank statement class mostly for :
- Removing the period and compute it from the date of each line.
- Allow to remove the balance check depending on the chosen profile
- Report errors on confirmation all at once instead of crashing onr by one
- Add a profile notion that can change the generated entries on statement
confirmation.
- For this, we had to override quite some long method and we'll need to maintain
- them up to date. Changes are point up by '#Chg' comment.
+ For this, we had to override quite some long method and we'll need to
+ maintain them up to date. Changes are point up by '#Chg' comment.
"""
_inherit = "account.bank.statement"
def _default_period(self, cr, uid, context=None):
- """
- Statement default period
- """
+ """Statement default period"""
if context is None:
context = {}
period_obj = self.pool.get('account.period')
- periods = period_obj.find(cr, uid, dt=context.get('date'), context=context)
+ periods = period_obj.find(
+ cr, uid, dt=context.get('date'), context=context)
return periods and periods[0] or False
def _default_profile(self, cr, uid, context=None):
- """
- Returns the default statement profile
+ """Returns the default statement profile
Default profile is the one with the lowest sequence of user's company
:return profile_id or False
"""
- if context is None:
- context = {}
- user_obj = self.pool.get('res.users')
- profile_obj = self.pool.get('account.statement.profile')
+ user_obj = self.pool['res.users']
+ profile_obj = self.pool['account.statement.profile']
user = user_obj.browse(cr, uid, uid, context=context)
- profile_ids = profile_obj.search(cr, uid, [('company_id', '=', user.company_id.id)], context=context)
-
+ profile_ids = profile_obj.search(
+ cr, uid, [('company_id', '=', user.company_id.id)], context=context)
return profile_ids[0] if profile_ids else False
def _get_statement_from_profile(self, cr, uid, profile_ids, context=None):
@@ -166,7 +154,6 @@ class AccountBankStatement(Model):
when the ORM calls this, self is an account.statement.profile.
Returns a list of account.bank.statement ids to recompute.
-
"""
triggered = []
for profile in self.browse(cr, uid, profile_ids, context=context):
@@ -219,11 +206,11 @@ class AccountBankStatement(Model):
},
readonly=True),
'period_id': fields.many2one(
- 'account.period',
- 'Period',
- required=False,
- readonly=False,
- invisible=True),
+ 'account.period',
+ 'Period',
+ required=False,
+ readonly=False,
+ invisible=True),
}
_defaults = {
@@ -232,28 +219,28 @@ class AccountBankStatement(Model):
}
def create(self, cr, uid, vals, context=None):
- """Need to pass the journal_id in vals anytime because of account.cash.statement
- need it."""
+ """Need to pass the journal_id in vals anytime because of
+ account.cash.statement need it."""
if 'profile_id' in vals:
- profile_obj = self.pool.get('account.statement.profile')
- profile = profile_obj.browse(cr, uid, vals['profile_id'], context=context)
+ profile_obj = self.pool['account.statement.profile']
+ profile = profile_obj.browse(
+ cr, uid, vals['profile_id'], context=context)
vals['journal_id'] = profile.journal_id.id
- return super(AccountBankStatement, self
- ).create(cr, uid, vals, context=context)
+ return super(AccountBankStatement, self).create(
+ cr, uid, vals, context=context)
def _get_period(self, cr, uid, date, context=None):
"""Return matching period for a date."""
if context is None:
context = {}
- period_obj = self.pool.get('account.period')
+ period_obj = self.pool['account.period']
local_context = context.copy()
local_context['account_period_prefer_normal'] = True
periods = period_obj.find(cr, uid, dt=date, context=local_context)
return periods and periods[0] or False
def _check_company_id(self, cr, uid, ids, context=None):
- """
- Adapt this constraint method from the account module to reflect the
+ """Adapt this constraint method from the account module to reflect the
move of period_id to the statement line
"""
for statement in self.browse(cr, uid, ids, context=context):
@@ -278,18 +265,18 @@ class AccountBankStatement(Model):
]
def _prepare_move(self, cr, uid, st_line, st_line_number, context=None):
- """Add the period_id from the statement line date to the move preparation.
- Originaly, it was taken from the statement period_id
- :param browse_record st_line: account.bank.statement.line record to
- create the move from.
- :param char st_line_number: will be used as the name of the generated account move
+ """Add the period_id from the statement line date to the move
+ preparation. Originaly, it was taken from the statement period_id
+ :param browse_record st_line: account.bank.statement.line record
+ to create the move from.
+ :param char st_line_number: will be used as the name of the
+ generated account move
:return: dict of value to create() the account.move
"""
if context is None:
context = {}
- res = super(AccountBankStatement, self
- )._prepare_move(cr, uid, st_line, st_line_number,
- context=context)
+ res = super(AccountBankStatement, self)._prepare_move(
+ cr, uid, st_line, st_line_number, context=context)
ctx = context.copy()
ctx['company_id'] = st_line.company_id.id
period_id = self._get_period(cr, uid, st_line.date, context=ctx)
@@ -300,31 +287,35 @@ class AccountBankStatement(Model):
self, cr, uid, st_line, move_id, debit, credit, currency_id=False,
amount_currency=False, account_id=False, analytic_id=False,
partner_id=False, context=None):
- """Add the period_id from the statement line date to the move preparation.
- Originaly, it was taken from the statement period_id
+ """Add the period_id from the statement line date to the move
+ preparation. Originaly, it was taken from the statement period_id
- :param browse_record st_line: account.bank.statement.line record to
- create the move from.
- :param int/long move_id: ID of the account.move to link the move line
+ :param browse_record st_line: account.bank.statement.line record
+ to create the move from.
+ :param int/long move_id: ID of the account.move to link the move
+ line
:param float debit: debit amount of the move line
:param float credit: credit amount of the move line
- :param int/long currency_id: ID of currency of the move line to create
- :param float amount_currency: amount of the debit/credit expressed in the currency_id
- :param int/long account_id: ID of the account to use in the move line if different
- from the statement line account ID
- :param int/long analytic_id: ID of analytic account to put on the move line
+ :param int/long currency_id: ID of currency of the move line to
+ create
+ :param float amount_currency: amount of the debit/credit expressed
+ in the currency_id
+ :param int/long account_id: ID of the account to use in the move
+ line if different from the statement line account ID
+ :param int/long analytic_id: ID of analytic account to put on the
+ move line
:param int/long partner_id: ID of the partner to put on the move line
:return: dict of value to create() the account.move.line
"""
if context is None:
context = {}
res = super(AccountBankStatement, self)._prepare_move_line_vals(
- cr, uid, st_line, move_id, debit, credit,
- currency_id=currency_id,
- amount_currency=amount_currency,
- account_id=account_id,
- analytic_id=analytic_id,
- partner_id=partner_id, context=context)
+ cr, uid, st_line, move_id, debit, credit,
+ currency_id=currency_id,
+ amount_currency=amount_currency,
+ account_id=account_id,
+ analytic_id=analytic_id,
+ partner_id=partner_id, context=context)
ctx = context.copy()
ctx['company_id'] = st_line.company_id.id
period_id = self._get_period(cr, uid, st_line.date, context=ctx)
@@ -332,15 +323,16 @@ class AccountBankStatement(Model):
return res
def _get_counter_part_partner(self, cr, uid, st_line, context=None):
- """
- We change the move line generated from the lines depending on the profile:
- - If partner_id is set and force_partner_on_bank is ticked, we'll let the partner of each line
- for the debit line, but we'll change it on the credit move line for the choosen partner_id
- => This will ease the reconciliation process with the bank as the partner will match the bank
- statement line
- :param browse_record st_line: account.bank.statement.line record to
- create the move from.
- :return: int/long of the res.partner to use as counterpart
+ """We change the move line generated from the lines depending on the
+ profile:
+ - If partner_id is set and force_partner_on_bank is ticked, we'll let
+ the partner of each line for the debit line, but we'll change it on
+ the credit move line for the choosen partner_id
+ => This will ease the reconciliation process with the bank as the
+ partner will match the bank statement line
+ :param browse_record st_line: account.bank.statement.line record to
+ create the move from.
+ :return: int/long of the res.partner to use as counterpart
"""
bank_partner_id = super(AccountBankStatement, self
)._get_counter_part_partner(cr, uid, st_line,
@@ -351,38 +343,38 @@ class AccountBankStatement(Model):
return bank_partner_id
def _get_st_number_period_profile(self, cr, uid, date, profile_id):
- """
- Retrieve the name of bank statement from sequence, according to the period
- corresponding to the date passed in args. Add a prefix if set in the profile.
+ """Retrieve the name of bank statement from sequence, according to the
+ period corresponding to the date passed in args. Add a prefix if set in
+ the profile.
:param: date: date of the statement used to compute the right period
- :param: int/long: profile_id: the account.statement.profile ID from which to take the
- bank_statement_prefix for the name
+ :param: int/long: profile_id: the account.statement.profile ID from
+ which to take the bank_statement_prefix for the name
:return: char: name of the bank statement (st_number)
-
"""
- year = self.pool.get('account.period').browse(
- cr, uid, self._get_period(cr, uid, date)).fiscalyear_id.id
- profile = self.pool.get('account.statement.profile').browse(cr, uid, profile_id)
+ year = self.pool['account.period'].browse(
+ cr, uid, self._get_period(cr, uid, date)).fiscalyear_id.id
+ profile = self.pool.get(
+ 'account.statement.profile').browse(cr, uid, profile_id)
c = {'fiscalyear_id': year}
- obj_seq = self.pool.get('ir.sequence')
+ obj_seq = self.pool['ir.sequence']
journal_sequence_id = (profile.journal_id.sequence_id and
profile.journal_id.sequence_id.id or False)
if journal_sequence_id:
- st_number = obj_seq.next_by_id(cr, uid, journal_sequence_id, context=c)
+ st_number = obj_seq.next_by_id(
+ cr, uid, journal_sequence_id, context=c)
else:
- st_number = obj_seq.next_by_code(cr, uid, 'account.bank.statement', context=c)
+ st_number = obj_seq.next_by_code(
+ cr, uid, 'account.bank.statement', context=c)
if profile.bank_statement_prefix:
st_number = profile.bank_statement_prefix + st_number
return st_number
def button_confirm_bank(self, cr, uid, ids, context=None):
- """
- Completely override the method in order to have
- an error message which displays all the messages
- instead of having them pop one by one.
- We have to copy paste a big block of code, changing the error
- stack + managing period from date.
+ """Completely override the method in order to have an error message
+ which displays all the messages instead of having them pop one by one.
+ We have to copy paste a big block of code, changing the error stack +
+ managing period from date.
TODO: Log the error in a bank statement field instead of using a popup!
"""
@@ -390,73 +382,78 @@ class AccountBankStatement(Model):
j_type = st.journal_id.type
company_currency_id = st.journal_id.company_id.currency_id.id
- if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
+ if not self.check_status_condition(cr, uid, st.state,
+ journal_type=j_type):
continue
-
- self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
+ self.balance_check(
+ cr, uid, st.id, journal_type=j_type, context=context)
if (not st.journal_id.default_credit_account_id) \
or (not st.journal_id.default_debit_account_id):
- raise osv.except_osv(_('Configuration Error!'),
- _('Please verify that an account is defined in the journal.'))
-
+ raise orm.except_orm(
+ _('Configuration Error!'),
+ _('Please verify that an account is defined in the '
+ 'journal.'))
if not st.name == '/':
st_number = st.name
else:
-# Begin Changes
- st_number = self._get_st_number_period_profile(cr, uid, st.date, st.profile_id.id)
-# End Changes
+ # Begin Changes
+ st_number = self._get_st_number_period_profile(
+ cr, uid, st.date, st.profile_id.id)
for line in st.move_line_ids:
if line.state != 'valid':
- raise osv.except_osv(_('Error!'),
- _('The account entries lines are not in valid state.'))
-# begin changes
+ raise orm.except_orm(
+ _('Error!'),
+ _('The account entries lines are not in valid state.'))
errors_stack = []
for st_line in st.line_ids:
try:
if st_line.analytic_account_id:
if not st.journal_id.analytic_journal_id:
- raise osv.except_osv(_('No Analytic Journal!'),
- _("You have to assign an analytic"
- " journal on the '%s' journal!") % st.journal_id.name)
+ raise orm.except_orm(
+ _('No Analytic Journal!'),
+ _("You have to assign an analytic journal on "
+ "the '%s' journal!") % st.journal_id.name)
if not st_line.amount:
continue
- st_line_number = self.get_next_st_line_number(cr, uid, st_number, st_line, context)
- self.create_move_from_st_line(cr, uid, st_line.id,
- company_currency_id,
- st_line_number,
- context)
- except osv.except_osv, exc:
- msg = "Line ID %s with ref %s had following error: %s" % (st_line.id, st_line.ref, exc.value)
+ st_line_number = self.get_next_st_line_number(
+ cr, uid, st_number, st_line, context)
+ self.create_move_from_st_line(
+ cr, uid, st_line.id, company_currency_id,
+ st_line_number, context)
+ except orm.except_orm, exc:
+ msg = "Line ID %s with ref %s had following error: %s" % (
+ st_line.id, st_line.ref, exc.value)
errors_stack.append(msg)
except Exception, exc:
- msg = "Line ID %s with ref %s had following error: %s" % (st_line.id, st_line.ref, str(exc))
+ msg = "Line ID %s with ref %s had following error: %s" % (
+ st_line.id, st_line.ref, str(exc))
errors_stack.append(msg)
if errors_stack:
msg = u"\n".join(errors_stack)
- raise osv.except_osv(_('Error'), msg)
-# end changes
+ raise orm.except_orm(_('Error'), msg)
self.write(cr, uid, [st.id],
{'name': st_number,
'balance_end_real': st.balance_end},
context=context)
- body = _('Statement %s confirmed, journal items were created.') % st_number
+ body = _('Statement %s confirmed, journal items were '
+ 'created.') % st_number
self.message_post(cr, uid, [st.id],
body,
context=context)
return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)
- def get_account_for_counterpart(self, cr, uid, amount, account_receivable, account_payable):
+ def get_account_for_counterpart(self, cr, uid, amount, account_receivable,
+ account_payable):
"""For backward compatibility."""
- account_id, type = self.get_account_and_type_for_counterpart(cr, uid, amount,
- account_receivable,
- account_payable)
+ account_id, type = self.get_account_and_type_for_counterpart(
+ cr, uid, amount, account_receivable, account_payable)
return account_id
def _compute_type_from_partner_profile(self, cr, uid, partner_id,
default_type, context=None):
"""Compute the statement line type
from partner profile (customer, supplier)"""
- obj_partner = self.pool.get('res.partner')
+ obj_partner = self.pool['res.partner']
part = obj_partner.browse(cr, uid, partner_id, context=context)
if part.supplier == part.customer:
return default_type
@@ -476,71 +473,83 @@ class AccountBankStatement(Model):
def get_type_for_counterpart(self, cr, uid, amount, partner_id=False):
"""Give the amount and receive the type to use for the line.
The rules are:
- - If the customer checkbox is checked on the found partner, type customer
- - If the supplier checkbox is checked on the found partner, typewill be supplier
- - If both checkbox are checked or none of them, it'll be based on the amount :
+ - If the customer checkbox is checked on the found partner, type
+ customer
+ - If the supplier checkbox is checked on the found partner, typewill
+ be supplier
+ - If both checkbox are checked or none of them, it'll be based on the
+ amount:
If amount is positif the type customer,
If amount is negativ, the type supplier
:param float: amount of the line
:param int/long: partner_id the partner id
- :return: type as string: the default type to use: 'customer' or 'supplier'.
+ :return: type as string: the default type to use: 'customer' or
+ 'supplier'.
"""
s_line_type = self._compute_type_from_amount(cr, uid, amount)
if partner_id:
- s_line_type = self._compute_type_from_partner_profile(cr, uid,
- partner_id, s_line_type)
+ s_line_type = self._compute_type_from_partner_profile(
+ cr, uid, partner_id, s_line_type)
return s_line_type
- def get_account_and_type_for_counterpart(self, cr, uid, amount, account_receivable,
- account_payable, partner_id=False):
+ def get_account_and_type_for_counterpart(
+ self, cr, uid, amount, account_receivable, account_payable,
+ partner_id=False):
"""
Give the amount, payable and receivable account (that can be found using
- get_default_pay_receiv_accounts method) and receive the one to use. This method
- should be use when there is no other way to know which one to take.
- The rules are:
- - If the customer checkbox is checked on the found partner, type and account will be customer and receivable
- - If the supplier checkbox is checked on the found partner, type and account will be supplier and payable
- - If both checkbox are checked or none of them, it'll be based on the amount :
- If amount is positive, the type and account will be customer and receivable,
- If amount is negative, the type and account will be supplier and payable
- Note that we return the payable or receivable account from agrs and not from the optional partner_id
- given!
+ get_default_pay_receiv_accounts method) and receive the one to use. This
+ method should be use when there is no other way to know which one to
+ take. The rules are:
+ - If the customer checkbox is checked on the found partner, type and
+ account will be customer and receivable
+ - If the supplier checkbox is checked on the found partner, type and
+ account will be supplier and payable
+ - If both checkbox are checked or none of them, it'll be based on the
+ amount:
+ If amount is positive, the type and account will be customer and
+ receivable,
+ If amount is negative, the type and account will be supplier and
+ payable
+ Note that we return the payable or receivable account from agrs and not
+ from the optional partner_id given!
:param float: amount of the line
:param int/long: account_receivable the receivable account
:param int/long: account_payable the payable account
:param int/long: partner_id the partner id
- :return: dict with [account_id as int/long,type as string]: the default account to be used by
- statement line as the counterpart of the journal account depending on the amount and the type
- as 'customer' or 'supplier'.
+ :return: dict with [account_id as int/long,type as string]: the
+ default account to be used by statement line as the counterpart of
+ the journal account depending on the amount and the type as
+ 'customer' or 'supplier'.
"""
account_id = False
- ltype = self.get_type_for_counterpart(cr, uid, amount, partner_id=partner_id)
+ ltype = self.get_type_for_counterpart(
+ cr, uid, amount, partner_id=partner_id)
if ltype == 'supplier':
account_id = account_payable
else:
account_id = account_receivable
if not account_id:
- raise osv.except_osv(
+ raise orm.except_orm(
_('Can not determine account'),
- _('Please ensure that minimal properties are set')
- )
+ _('Please ensure that minimal properties are set'))
return [account_id, ltype]
def get_default_pay_receiv_accounts(self, cr, uid, context=None):
"""
- We try to determine default payable/receivable accounts to be used as counterpart
- from the company default propoerty. This is to be used if there is no otherway to
- find the good one, or to find a default value that will be overriden by a completion
- method (rules of account_statement_base_completion) afterwards.
+ We try to determine default payable/receivable accounts to be used as
+ counterpart from the company default propoerty. This is to be used if
+ there is no otherway to find the good one, or to find a default value
+ that will be overriden by a completion method (rules of
+ account_statement_base_completion) afterwards.
- :return: tuple of int/long ID that give account_receivable, account_payable based on
- company default.
+ :return: tuple of int/long ID that give account_receivable,
+ account_payable based on company default.
"""
-
- property_obj = self.pool.get('ir.property')
- account_receivable = property_obj.get(cr, uid, 'property_account_receivable',
- 'res.partner', context=context)
+ property_obj = self.pool['ir.property']
+ account_receivable = property_obj.get(
+ cr, uid, 'property_account_receivable', 'res.partner',
+ context=context)
account_payable = property_obj.get(cr, uid, 'property_account_payable',
'res.partner', context=context)
@@ -549,8 +558,8 @@ class AccountBankStatement(Model):
def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
"""
- Balance check depends on the profile. If no check for this profile is required,
- return True and do nothing, otherwise call super.
+ Balance check depends on the profile. If no check for this profile is
+ required, return True and do nothing, otherwise call super.
:param int/long st_id: ID of the concerned account.bank.statement
:param char: journal_type that concern the bank statement
@@ -565,27 +574,25 @@ class AccountBankStatement(Model):
return True
def onchange_imp_config_id(self, cr, uid, ids, profile_id, context=None):
- """
- Compute values on the change of the profile.
+ """Compute values on the change of the profile.
:param: int/long: profile_id that changed
:return dict of dict with key = name of the field
"""
if not profile_id:
return {}
- import_config = self.pool.get("account.statement.profile").browse(
- cr, uid, profile_id, context=context)
+ import_config = self.pool["account.statement.profile"].browse(
+ cr, uid, profile_id, context=context)
journal_id = import_config.journal_id.id
return {'value': {'journal_id': journal_id,
'balance_check': import_config.balance_check}}
-class AccountBankStatementLine(Model):
- """
- Override to compute the period from the date of the line, add a method to retrieve
- the values for a line from the profile. Override the on_change method to take care of
- the profile when fullfilling the bank statement manually. Set the reference to 64
- Char long instead 32.
+class AccountBankStatementLine(orm.Model):
+ """Override to compute the period from the date of the line, add a method
+ to retrieve the values for a line from the profile. Override the on_change
+ method to take care of the profile when fullfilling the bank statement
+ manually. Set the reference to 64 Char long instead 32.
"""
_inherit = "account.bank.statement.line"
@@ -599,7 +606,7 @@ class AccountBankStatementLine(Model):
local_context['account_period_prefer_normal'] = True
try:
periods = period_obj.find(cr, uid, dt=date, context=local_context)
- except osv.except_osv:
+ except orm.except_orm:
# if no period defined, we are certainly at installation time
return False
return periods and periods[0] or False
@@ -617,30 +624,40 @@ class AccountBankStatementLine(Model):
'account_id': _get_default_account,
}
- def get_values_for_line(self, cr, uid, profile_id=False, partner_id=False, line_type=False, amount=False, master_account_id=None, context=None):
- """
- Return the account_id to be used in the line of a bank statement. It'll base the result as follow:
- - If a receivable_account_id is set in the profile, return this value and type = general
+ def get_values_for_line(self, cr, uid, profile_id=False, partner_id=False,
+ line_type=False, amount=False,
+ master_account_id=None, context=None):
+ """Return the account_id to be used in the line of a bank statement.
+ It'll base the result as follow:
+ - If a receivable_account_id is set in the profile, return this
+ value and type = general
# TODO
- - Elif how_get_type_account is set to force_supplier or force_customer, will take respectively payable and type=supplier,
+ - Elif how_get_type_account is set to force_supplier or
+ force_customer, will take respectively payable and type=supplier,
receivable and type=customer otherwise
# END TODO
- - Elif line_type is given, take the partner receivable/payable property (payable if type=supplier, receivable
- otherwise)
+ - Elif line_type is given, take the partner receivable/payable
+ property (payable if type=supplier, receivable otherwise)
- Elif amount is given:
- - If the customer checkbox is checked on the found partner, type and account will be customer and receivable
- - If the supplier checkbox is checked on the found partner, type and account will be supplier and payable
- - If both checkbox are checked or none of them, it'll be based on the amount :
- If amount is positive, the type and account will be customer and receivable,
- If amount is negative, the type and account will be supplier an payable
- - Then, if no partner are given we look and take the property from the company so we always give a value
- for account_id. Note that in that case, we return the receivable one.
+ - If the customer checkbox is checked on the found partner,
+ type and account will be customer and receivable
+ - If the supplier checkbox is checked on the found partner,
+ type and account will be supplier and payable
+ - If both checkbox are checked or none of them, it'll be based
+ on the amount :
+ If amount is positive, the type and account will be
+ customer and receivable,
+ If amount is negative, the type and account will be
+ supplier an payable
+ - Then, if no partner are given we look and take the property from
+ the company so we always give a value for account_id. Note that in
+ that case, we return the receivable one.
:param int/long profile_id of the related bank statement
:param int/long partner_id of the line
:param char line_type: a value from: 'general', 'supplier', 'customer'
:param float: amount of the line
- :return: A dict of value that can be passed directly to the write method of
- the statement line:
+ :return: A dict of value that can be passed directly to the write
+ method of the statement line:
{'partner_id': value,
'account_id' : value,
'type' : value,
@@ -663,12 +680,12 @@ class AccountBankStatementLine(Model):
# on profile
if profile_id and master_account_id is None:
profile = self.pool.get("account.statement.profile").browse(
- cr, uid, profile_id, context=context)
+ cr, uid, profile_id, context=context)
if profile.receivable_account_id:
res['account_id'] = profile.receivable_account_id.id
- # We return general as default instead of get_type_for_counterpart
- # for perfomance reasons as line_type is not a meaningfull value
- # as account is forced
+ # We return general as default instead of
+ # get_type_for_counterpart for perfomance reasons as line_type
+ # is not a meaningfull value as account is forced
res['type'] = line_type if line_type else 'general'
return res
# If no account is available on profile you have to do the lookup
@@ -684,36 +701,41 @@ class AccountBankStatementLine(Model):
receiv_account = part.property_account_receivable.id
# If no value, look on the default company property
if not pay_account or not receiv_account:
- receiv_account, pay_account = obj_stat.get_default_pay_receiv_accounts(cr, uid, context=None)
- account_id, comp_line_type = obj_stat.get_account_and_type_for_counterpart(cr, uid, amount,
- receiv_account, pay_account,
- partner_id=partner_id)
+ receiv_account, pay_account = obj_stat.\
+ get_default_pay_receiv_accounts(cr, uid, context=None)
+ account_id, comp_line_type = obj_stat.\
+ get_account_and_type_for_counterpart(
+ cr, uid, amount, receiv_account, pay_account,
+ partner_id=partner_id)
res['account_id'] = account_id if account_id else receiv_account
res['type'] = line_type if line_type else comp_line_type
return res
- def onchange_partner_id(self, cr, uid, ids, partner_id, profile_id=None, context=None):
+ def onchange_partner_id(self, cr, uid, ids, partner_id, profile_id=None,
+ context=None):
"""
- Override of the basic method as we need to pass the profile_id in the on_change_type
- call.
- Moreover, we now call the get_account_and_type_for_counterpart method now to get the
- type to use.
+ Override of the basic method as we need to pass the profile_id in the
+ on_change_type call.
+ Moreover, we now call the get_account_and_type_for_counterpart method
+ now to get the type to use.
"""
- obj_stat = self.pool.get('account.bank.statement')
+ obj_stat = self.pool['account.bank.statement']
if not partner_id:
return {}
- line_type = obj_stat.get_type_for_counterpart(cr, uid, 0.0, partner_id=partner_id)
- res_type = self.onchange_type(cr, uid, ids, partner_id, line_type, profile_id, context=context)
+ line_type = obj_stat.get_type_for_counterpart(
+ cr, uid, 0.0, partner_id=partner_id)
+ res_type = self.onchange_type(
+ cr, uid, ids, partner_id, line_type, profile_id, context=context)
if res_type['value'] and res_type['value'].get('account_id', False):
return {'value': {'type': line_type,
'account_id': res_type['value']['account_id'],
'voucher_id': False}}
return {'value': {'type': line_type}}
- def onchange_type(self, cr, uid, line_id, partner_id, line_type, profile_id, context=None):
- """
- Keep the same features as in standard and call super. If an account is returned,
- call the method to compute line values.
+ def onchange_type(self, cr, uid, line_id, partner_id, line_type, profile_id,
+ context=None):
+ """Keep the same features as in standard and call super. If an account
+ is returned, call the method to compute line values.
"""
res = super(AccountBankStatementLine, self
).onchange_type(cr, uid, line_id, partner_id,
diff --git a/account_statement_ext/statement_view.xml b/account_statement_ext/statement_view.xml
index 063ba92a..3896b2c3 100644
--- a/account_statement_ext/statement_view.xml
+++ b/account_statement_ext/statement_view.xml
@@ -5,7 +5,6 @@
account.statement.profile.view
account.statement.profile
- form