[CHG] cleanings

(lp:c2c-addons/6.1  rev 89.1.5)
This commit is contained in:
Guewen Baconnier @ Camptocamp
2012-10-23 13:36:28 +02:00
parent 5ccf999f6f
commit a51a427cca
2 changed files with 181 additions and 133 deletions

View File

@@ -28,6 +28,8 @@ from openerp.osv.osv import except_osv
logger = logging.getLogger('Credit Control run')
# beware, do always use the DB lock of `CreditControlRun.generate_credit_lines`
# to use this variable, otherwise you will have race conditions
memoizers = {}
@@ -37,62 +39,72 @@ class CreditControlRun(Model):
_name = "credit.control.run"
_rec_name = 'date'
_description = """Credit control line generator"""
_columns = {'date': fields.date('Controlling date', required=True),
'policy_ids': fields.many2many('credit.control.policy',
rel="credit_run_policy_rel",
string='Policies',
readonly=True,
help="If nothing set all policies will be used",
_columns = {
'date': fields.date('Controlling Date', required=True),
'policy_ids': fields.many2many('credit.control.policy',
rel="credit_run_policy_rel",
id1='run_id', id2='policy_id',
string='Policies',
readonly=True,
states={'draft': [('readonly', False)]}),
states={'draft': [('readonly', False)]}),
'report': fields.text('Report', readonly=True),
'report': fields.text('Report', readonly=True),
'state': fields.selection([('draft', 'Draft'),
('running', 'Running'),
('done', 'Done'),
('error', 'Error')],
string='State',
required=True,
readonly=True),
'state': fields.selection([('draft', 'Draft'),
('running', 'Running'),
('done', 'Done'),
('error', 'Error')],
string='State',
required=True,
readonly=True),
'manual_ids': fields.many2many('account.move.line',
rel="credit_runreject_rel",
string='Line to be handled manually',
readonly=True),
'manual_ids': fields.many2many('account.move.line',
rel="credit_runreject_rel",
string='Lines to handle manually',
readonly=True),
}
_defaults = {'state': 'draft'}
def _get_policies(self, cursor, uid, context=None):
return self.pool.get('credit.control.policy').\
search(cursor, uid, [], context=context)
def check_run_date(self, cursor, uid, ids, controlling_date, context=None):
_defaults = {
'state': 'draft',
'policy_ids': _get_policies,
}
def _check_run_date(self, cursor, uid, ids, controlling_date, context=None):
"""Ensure that there is no credit line in the future using controlling_date"""
line_obj = self.pool.get('credit.control.line')
lines = line_obj.search(cursor, uid, [('date', '>', controlling_date)],
order='date DESC', limit=1)
order='date DESC', limit=1, context=context)
if lines:
line = line_obj.browse(cursor, uid, lines[0])
raise except_osv(_('A run was already executed in a greater date'),
_('Run date should be >= %s') % (line.date))
line = line_obj.browse(cursor, uid, lines[0], context=context)
raise except_osv(_('A run has already been executed more recently than %s') % (line.date))
return True
def _generate_credit_lines(self, cursor, uid, run_id, context=None):
""" Generate credit line. Function can be a little dryer but
it does almost noting, initalise variable maange error and call
real know how method"""
""" Generate credit control lines. """
memoizers['credit_line_residuals'] = {}
cr_line_obj = self.pool.get('credit.control.line')
assert not (isinstance(run_id, list) and len(run_id) > 1), \
"run_id: only one id expected"
if isinstance(run_id, list):
run_id = run_id[0]
run = self.browse(cursor, uid, run_id, context=context)
errors = []
manualy_managed_lines = [] #line who changed policy
credit_line_ids = [] # generated lines
run.check_run_date(run.date, context=context)
manually_managed_lines = [] # line who changed policy
credit_line_ids = [] # generated lines
run._check_run_date(run.date, context=context)
policy_ids = run.policy_ids
if not policy_ids:
policy_obj = self.pool.get('credit.control.policy')
policy_ids_ids = policy_obj.search(cursor, uid, [])
policy_ids = policy_obj.browse(cursor, uid, policy_ids_ids)
raise except_osv(
_('Error'),
_('Please select a policy'))
lines = []
for policy in policy_ids:
if policy.do_nothing:
continue
@@ -100,43 +112,50 @@ class CreditControlRun(Model):
lines = policy._get_moves_line_to_process(run.date, context=context)
tmp_manual = policy._check_lines_policies(lines, context=context)
lines = list(set(lines) - set(tmp_manual))
manualy_managed_lines += tmp_manual
manually_managed_lines += tmp_manual
if not lines:
continue
# policy levels are sorted by level so iteration is in the correct order
for level in policy.level_ids:
level_lines = level.get_level_lines(run.date, lines)
#only this write action own a separate cursor
credit_line_ids += cr_line_obj.create_or_update_from_mv_lines(
cursor, uid, [], level_lines, level.id, run.date, errors=errors, context=context)
level_lines = level.get_level_lines(run.date, lines, context=context)
# only this write action own a separate cursor
loc_ids, loc_errors = cr_line_obj.create_or_update_from_mv_lines(
cursor, uid, [], level_lines, level.id, run.date, context=context)
credit_line_ids += loc_ids
errors += loc_errors
lines = list(set(lines) - set(level_lines))
except except_osv, exc:
# TODO: check if rollback on cursor is safe ?
cursor.rollback()
error_type, error_value, trbk = sys.exc_info()
st = "Error: %s\nDescription: %s\nTraceback:" % (error_type.__name__, error_value)
st += ''.join(traceback.format_tb(trbk, 30))
logger.error(st)
self.write(cursor, uid, [run.id], {'report':st, 'state': 'error'})
self.write(cursor, uid,
[run.id],
{'report':st,
'state': 'error'},
context=context)
return False
vals = {'report': u"Number of generated lines : %s \n" % (len(credit_line_ids),),
'state': 'done',
'manual_ids': [(6, 0, manualy_managed_lines)]}
'manual_ids': [(6, 0, manually_managed_lines)]}
if errors:
vals['report'] += u"Following line generation errors appends:"
vals['report'] += u"----\n".join(errors)
vals['state'] = 'done'
run.write(vals)
run.write(vals, context=context)
# lines will correspond to line that where not treated
return lines
def generate_credit_lines(self, cursor, uid, run_id, context=None):
"""Generate credit control lines"""
"""Generate credit control lines
Lock the ``credit_control_run`` Postgres table to avoid concurrent
calls of this method.
"""
context = context or {}
# we do a little magical tips in order to ensure non concurrent run
# of the function generate_credit_lines
try:
cursor.execute('SELECT id FROM credit_control_run'
' LIMIT 1 FOR UPDATE NOWAIT' )