Commits

Raimon Esteve (Zikzakmedia) committed 3ad582e

Active Record

  • Participants
  • Parent commits 3f5e2f8

Comments (0)

Files changed (10)

+Version 2.6.0 - 2012-10-08
+* Simplify module information with python configuration
+* Active Record
+
+Version 2.4.0 - 2012-09-06
 * Add signature if template and user have signature
 * Add event if party_event is installed
 * Available Send Email by user (button)
 #the full copyright notices and license terms.
 'Electronic Mail Templates'
 
+from trytond.pool import Pool
 from .template import *
 from .electronic_mail import *
 from .trigger import *
 from .report import *
+
+
+def register():
+    Pool.register(
+        ElectronicMail,
+        ActionReport,
+        Template,
+        TemplateReport,
+        Trigger,
+        module='electronic_mail_template', type_='model')

__tryton__.py

-# -*- coding: UTF-8 -*-
-#This file is part electronic_mail_template module for Tryton.
-#The COPYRIGHT file at the top level of this repository contains 
-#the full copyright notices and license terms.
-
-{
-    'name': 'Electronic Mail Template',
-    'description': '''Electronic mail template''',
-    'version': '2.4.0.2',
-    'author': 'Openlabs Technologies & Consulting (P) LTD',
-    'email': 'info@openlabs.co.in',
-    'website': 'http://openlabs.co.in',
-    'active': True,
-    'depends': [
-        'ir',
-        'res',
-        'electronic_mail',
-    ],
-    'xml': [
-        'template.xml',
-        'trigger.xml',
-        'report.xml',
-    ],
-    'translation': [
-        'locale/ca_ES.po',
-        'locale/es_ES.po',
-    ],
-}
-

electronic_mail.py

 from trytond.pool import Pool
 from trytond.pyson import Eval
 
+__all__ = ['ElectronicMail']
 
 class ElectronicMail(ModelSQL, ModelView):
     "E-Mail module extended to suit inbuilt reading and templating"
-    _name = 'electronic.mail'
+    __name__ = 'electronic.mail'
 
+    subject = fields.Char('Subject', translate=True)
     body_html = fields.Function(
         fields.Text('HTML (BODY)'), 'get_email_body')
     body_plain = fields.Function(
         fields.Text('Plain Text (BODY)'), 'get_email_body')
 
-    def __init__(self):
-        super(ElectronicMail, self).__init__()
-        self._buttons.update({
+    @classmethod
+    def __setup__(cls):
+        super(ElectronicMail, cls).__setup__()
+        cls._buttons.update({
                 'send_mail': {
                     'invisible': Eval('body_plain') == '',
                     },
                 })
 
-    def get_email_body(self, ids, names):
+    def get_email_body(self, name):
         """Returns the email body
         """
-        result = dict.fromkeys(names)
-        for name in names:
-            result[name] = defaultdict(unicode).fromkeys(ids)
-
-        for email in self.browse(ids):
-            message = message_from_string(self._get_email(email))
-            for part in message.walk():
-                content_type = part.get_content_type()
-                for name in names:
-                    if content_type == 'text/' + name.lstrip('body_'):
-                        result[name][email.id] = part.get_payload()
+        result = ''
+        test = defaultdict(unicode).fromkeys(name)
+        message = message_from_string(self._get_email(self))
+        for part in message.walk():
+            content_type = part.get_content_type()
+            if content_type == 'text/plain':
+                result = part.get_payload()
         return result
 
-    def check_xml_record(self, ids, values):
+    @classmethod
+    def check_xml_record(cls, records, values):
         '''It should be possible to overwrite templates'''
         return True
 
             template_obj.send_email(email_id)
         return True
 
-ElectronicMail()
 #The COPYRIGHT file at the top level of this repository contains 
 #the full copyright notices and license terms.
 from trytond.model import ModelView, ModelSQL, fields
+from trytond.pool import PoolMeta
 
+__all__ = ['ActionReport']
+__metaclass__ = PoolMeta
 
-class ActionReport(ModelSQL, ModelView):
+class ActionReport:
     "Action report"
-    _name = 'ir.action.report'
+    __name__ = 'ir.action.report'
 
     file_name = fields.Char('File Name Pattern', translate=True, 
         help='File name e-mail attachment without extension. eg. sale_${record.reference}')
 
-ActionReport()
 
 from setuptools import setup
 import re
+import os
+import ConfigParser
 
-info = eval(open('__tryton__.py').read())
+config = ConfigParser.ConfigParser()
+config.readfp(open('tryton.cfg'))
+info = dict(config.items('tryton'))
+for key in ('depends', 'extras_depend', 'xml'):
+    if key in info:
+        info[key] = info[key].strip().splitlines()
 major_version, minor_version, _ = info.get('version', '0.0.1').split('.', 2)
 major_version = int(major_version)
 minor_version = int(minor_version)
 
 setup(name='trytond_electronic_mail_template',
     version=info.get('version', '0.0.1'),
-    description=info.get('description', ''),
-    author=info.get('author', ''),
-    author_email=info.get('email', ''),
-    url=info.get('website', ''),
-    download_url="http://downloads.tryton.org/" + \
-            info.get('version', '0.0.1').rsplit('.', 1)[0] + '/',
+    description='Electronic mail storage',
+    author='Openlabs Technologies & Consulting (P) LTD',
+    author_email='info@openlabs.co.in',
+    url='http://openlabs.co.in/',
+    download_url='https://bitbucket.org/zikzakmedia/trytond-electronic_mail',
     package_dir={'trytond.modules.electronic_mail_template': '.'},
     packages=[
         'trytond.modules.electronic_mail_template',
     ],
     package_data={
         'trytond.modules.electronic_mail_template': info.get('xml', []) \
-                + info.get('translation', []),
+            + ['tryton.cfg', 'locale/*.po'],
     },
     classifiers=[
         'Development Status :: 5 - Production/Stable',
 from trytond.pyson import Eval
 from trytond.pool import Pool
 
-
 def split_emails(email_ids):
     """Email IDs could be separated by ';' or ','
 
         recepients.extend(split_emails(getattr(email_record, field)))
     return recepients
 
-class ElectronicMail(ModelSQL, ModelView):
-    "E-mail"
-    _name = 'electronic.mail'
-    _description = __doc__
+__all__ = ['Template', 'TemplateReport']
 
-    subject = fields.Char('Subject', translate=True)
-
-ElectronicMail()
 
 class Template(ModelSQL, ModelView):
     'Email Template'
-    _name = 'electronic.mail.template'
-    _description = __doc__
+    __name__ = 'electronic.mail.template'
     _inherits = {
         'electronic.mail': 'electronic_mail',
         }
     signature =  fields.Boolean('Use Signature',
         help='The signature from the User details will be appened to the mail.')
 
-    def __init__(self):
-        super(Template, self).__init__()
-        self._error_messages.update({
+    @classmethod
+    def __setup__(cls):
+        super(Template, cls).__setup__()
+        cls._error_messages.update({
             'smtp_error': 'Wrong connection to SMTP server. Email have not sent',
             'recipients_error': 'Not valid recipients emails. Check emails in TO, CC or BBC',
             })
 
-    def default_template(self):
+    @staticmethod
+    def default_template():
         return True
 
-    def default_engine(self):
+    @staticmethod
+    def default_engine():
         '''Default Engine'''
         return 'genshi'
 
-    def get_engines(self):
+    @classmethod
+    def get_engines(cls):
         '''Returns the engines as list of tuple
 
         :return: List of tuples
         ]
         return engines
 
-    def check_xml_record(self, ids, values):
+    @classmethod
+    def check_xml_record(cls, records, values):
         '''It should be possible to overwrite templates'''
         return True
 
                 email_message, template.mailbox.id)
             self.send_email(email_id, template)
 
-            #add event if party_event is installed
-            cursor = Transaction().cursor
-            cursor.execute("SELECT state from ir_module_module where state='installed' and name = 'party_event'")
-            party_event = cursor.fetchall()
-            if template.party and party_event:
-                party = self.eval(template, template.party, record)
-                resource = 'electronic.mail,%s' % email_id
-                values = {
-                    'subject':email_message.get('subject'),
-                    'description':self.eval(template, template.plain, record),
-                }
-                Pool().get('party.event').create_event(party, resource, values)
+            self.add_event(template, record, email_id, email_message) #add event
         return True
 
     def mail_from_trigger(self, record_ids, trigger_id):
             self.raise_user_error('smtp_error')
         return True
 
-Template()
+    def add_event(self, template, record, email_id, email_message):
+        """
+        Add event if party_event is installed
+        :param template: Browse Record of the template
+        :param record: Browse record of the record
+        :param email_id: ID email to send
+        :param email_message: Data email to extract values
+        """
+        cursor = Transaction().cursor
+        cursor.execute("SELECT state from ir_module_module where state='installed' and name = 'party_event'")
+        party_event = cursor.fetchall()
+        if template.party and party_event:
+            party = self.eval(template, template.party, record)
+            resource = 'electronic.mail,%s' % email_id
+            values = {
+                'subject':email_message.get('subject'),
+                'description':self.eval(template, template.plain, record),
+            }
+            Pool().get('party.event').create_event(party, resource, values)
+        return True
 
 
 class TemplateReport(ModelSQL):
     'Template - Report Action'
-    _name = 'electronic.mail.template.ir.action.report'
-    _description = __doc__
+    __name__ = 'electronic.mail.template.ir.action.report'
 
     template = fields.Many2One('electronic.mail.template', 'Template')
     report = fields.Many2One('ir.action.report', 'Report')
 
-TemplateReport()
             <xpath
               expr="/form/group[@id=&quot;send_area&quot;]/field[@name=&quot;flag_send&quot;]"
               position="after">
-              <button name="send_mail" type="object" string="Send Email" icon="tryton-ok"/>
+              <button name="send_mail" string="Send Email" icon="tryton-ok"/>
             </xpath>
             <xpath expr="/form/field[@name='email']" position="replace">
               <notebook colspan="4">
 #The COPYRIGHT file at the top level of this repository contains 
 #the full copyright notices and license terms.
 "Trigger Extension"
-
 from trytond.model import ModelSQL, ModelView, fields
 from trytond.transaction import Transaction
-from trytond.pool import Pool
+from trytond.pool import Pool, PoolMeta
 
+__all__ = ['Trigger']
+__metaclass__ = PoolMeta
 
-class Trigger(ModelSQL, ModelView):
+class Trigger:
     "Extend triggers to use Email template"
-    _name = 'ir.trigger'
+    __name__ = 'ir.trigger'
 
     email_template = fields.Many2One(
         'electronic.mail.template', 'Template', 
         )
 
-    def default_model(self):
+    @staticmethod
+    def default_model():
         """If invoked from the email_template fill model
         """
         return Transaction().context.get('model', False)
 
-    def default_action_model(self):
+    @staticmethod
+    def default_action_model():
         """If invoked from the email_template fill 
         action model as email_template
         """
         assert len(model_ids) == 1, 'Unexpected result for model search'
         return model_ids[0]
 
-    def default_action_function(self):
+    @staticmethod
+    def default_action_function():
         """If invoked from the email_template fill
         action function as 'mail_from_trigger'
         """
         email_trigger = Transaction().context.get('email_template', False)
         return email_trigger and 'mail_from_trigger' or False
 
-Trigger()
+[tryton]
+version=2.6.0
+depends:
+    ir
+    res
+    electronic_mail
+xml:
+    template.xml
+    trigger.xml
+    report.xml