trytond-account_dunning_cron/dunning.py

87 lines
2.6 KiB
Python
Raw Permalink Normal View History

2014-11-07 13:13:30 +01:00
# This file is part account_dunning_cron module for Tryton.
# The COPYRIGHT file at the top level of this repository contains
# the full copyright notices and license terms.
2013-12-19 17:31:32 +01:00
from trytond.pool import Pool, PoolMeta
from trytond.transaction import Transaction
2016-04-07 18:59:20 +02:00
from trytond.sendmail import sendmail
2013-12-19 17:31:32 +01:00
from email.mime.text import MIMEText
from email.header import Header
2015-08-12 01:25:19 +02:00
import logging
2013-12-19 17:31:32 +01:00
__all__ = ['Dunning']
2015-08-12 01:25:19 +02:00
logger = logging.getLogger(__name__)
2013-12-19 17:31:32 +01:00
class Dunning:
2016-03-29 12:00:15 +02:00
__metaclass__ = PoolMeta
2013-12-19 17:31:32 +01:00
__name__ = 'account.dunning'
@classmethod
def __setup__(cls):
super(Dunning, cls).__setup__()
cls._error_messages.update({
'request_title': '[%s] New dunnings generated',
'request_body': ("New dunnings are generated and pending "
"to done:\n\n%s")
})
@classmethod
def generate_today_dunnings(cls):
"""
Generate Account Today Dunnigs
"""
pool = Pool()
Date = pool.get('ir.date')
User = pool.get('res.user')
Config = pool.get('account.configuration')
today = Date.today()
cls.generate_dunnings(date=today)
config = Config(1)
group = config.dunning_group_cron
emails = None
records = []
for dunning in cls.search([
('state', '=', 'draft'),
('blocked', '=', False),
('maturity_date', '=', today),
]):
records.append('%s, %s, %s' % (
dunning.party.rec_name,
dunning.amount,
dunning.maturity_date,
))
if records:
records.sort()
users = User.search([
('groups', 'in', [group.id]),
])
emails = [user.email for user in users if user.email]
if not emails:
2015-08-12 01:25:19 +02:00
logger.info(
2013-12-19 17:31:32 +01:00
'Unable to deliver dunny email. '
'Add email dunning group users')
if emails:
subject = cls.raise_user_error('request_title',
(Transaction().database.name),
2013-12-19 17:31:32 +01:00
raise_exception=False)
body = cls.raise_user_error('request_body',
('\n'.join(records)),
raise_exception=False)
2014-11-17 15:59:32 +01:00
from_addr = config.get('email', 'from')
2013-12-19 17:31:32 +01:00
to_addr = list(set(emails))
msg = MIMEText(body, _charset='utf-8')
msg['To'] = ', '.join(to_addr)
msg['From'] = from_addr
msg['Subject'] = Header(subject, 'utf-8')
2016-04-07 18:59:20 +02:00
sendmail(from_addr, to_addr, msg)