trytond-electronic_mail_filter/template.py

63 lines
2.2 KiB
Python

# The COPYRIGHT file at the top level of this repository contains the full
# copyright notices and license terms.
import mimetypes
try:
from email import Encoders
except ImportError:
from email import encoders as Encoders
from email.mime.base import MIMEBase
from trytond.model import fields
from trytond.pool import PoolMeta, Pool
from trytond.pyson import Eval
__all__ = ['Template']
class Template(metaclass=PoolMeta):
__name__ = 'electronic.mail.template'
filters = fields.One2Many('electronic.mail.filter', 'template',
'Filters')
no_records_email = fields.Boolean('Send email when no records')
@classmethod
def __setup__(cls):
super().__setup__()
if cls.reports.states.get('invisible'):
cls.reports.states['invisible'] |= Eval('no_records_email')
else:
cls.reports.states['invisible'] = Eval('no_records_email')
if cls.reports.states.get('readonly'):
cls.reports.states['readonly'] |= Eval('no_records_email')
else:
cls.reports.states['readonly'] = Eval('no_records_email')
cls.reports.depends.append('no_records_email')
def get_attachments(self, records):
record_ids = [r.id for r in records if r]
attachments = []
for report in self.reports:
report = Pool().get(report.report_name, type='report')
ext, data, filename, file_name = report.execute(record_ids, {})
if file_name:
filename = self.eval(file_name, record_ids)
filename = ext and '%s.%s' % (filename, ext) or filename
content_type, _ = mimetypes.guess_type(filename)
maintype, subtype = (
content_type or 'application/octet-stream'
).split('/', 1)
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(data)
Encoders.encode_base64(attachment)
attachment.add_header(
'Content-Disposition', 'attachment', filename=filename)
attachments.append(attachment)
return attachments
@fields.depends('no_records_email')
def on_change_no_records_email(self):
if self.no_records_email:
self.reports = []