Commits

Raimon Esteve (Zikzakmedia) committed a3dc7ea

Active Record

Comments (0)

Files changed (8)

+Version 2.6.0 - 2012-10-08
+* Simplify module information with python configuration
+* Active Record
+
+Version 2.4.0 - 2012-09-06
 * Electronic Email Form View: flag group 
 * Usability: Email menu in top menu. Access user email group (not necessary admin group)
 * Add flag send field
 =======================
 
 The electronic_mail module of the Tryton application platform.
-See __tryton__.py
 
 Installing
 ----------
 #This file is part electronic_mail module for Tryton.
 #The COPYRIGHT file at the top level of this repository contains 
 #the full copyright notices and license terms.
-"Electronic Mail"
 
+from trytond.pool import Pool
 from electronic_mail import *
 
+def register():
+    Pool.register(
+        Mailbox,
+        MailboxParent,
+        ReadUser,
+        WriteUser,
+        ElectronicMail,
+        Header,
+        module='electronic_mail', type_='model')

__tryton__.py

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

electronic_mail.py

 import base64
 import re
 from sys import getsizeof
+
 try:
     import hashlib
 except ImportError:
 from trytond.transaction import Transaction
 from trytond.pool import Pool
 
+__all__ = ['Mailbox', 'MailboxParent', 'ReadUser', 'WriteUser',
+    'ElectronicMail', 'Header']
 
 class Mailbox(ModelSQL, ModelView):
     "Mailbox"
-    _name = "electronic.mail.mailbox"
-    _description = __doc__
+    __name__ = "electronic.mail.mailbox"
 
     name = fields.Char('Name', required=True)
     user = fields.Many2One('res.user', 'Owner')
     write_users = fields.Many2Many('electronic.mail.mailbox.write.res.user',
             'mailbox', 'user', 'Write Users')
 
-Mailbox()
 
 
 class MailboxParent(ModelSQL):
     'Mailbox - parent - Mailbox'
-    _description = __doc__
-    _name = 'electronic.mail.mailbox.mailbox'
+    __name__ = 'electronic.mail.mailbox.mailbox'
 
     parent = fields.Many2One('electronic.mail.mailbox', 'Parent',
             ondelete='CASCADE', required=True, select=1)
     child = fields.Many2One('electronic.mail.mailbox', 'Child',
             ondelete='CASCADE', required=True, select=1)
 
-MailboxParent()
 
 
 class ReadUser(ModelSQL):
     'Electronic Mail - read - User'
-    _description = __doc__
-    _name = 'electronic.mail.mailbox.read.res.user'
+    __name__ = 'electronic.mail.mailbox.read.res.user'
 
     mailbox = fields.Many2One('electronic.mail.mailbox', 'Mailbox',
             ondelete='CASCADE', required=True, select=1)
     user = fields.Many2One('res.user', 'User', ondelete='CASCADE',
             required=True, select=1)
 
-ReadUser()
 
 
 class WriteUser(ModelSQL):
     'Mailbox - write - User'
-    _description = __doc__
-    _name = 'electronic.mail.mailbox.write.res.user'
+    __name__ = 'electronic.mail.mailbox.write.res.user'
 
     mailbox = fields.Many2One('electronic.mail.mailbox', 'mailbox',
             ondelete='CASCADE', required=True, select=1)
     user = fields.Many2One('res.user', 'User', ondelete='CASCADE',
             required=True, select=1)
 
-WriteUser()
 
 
 class ElectronicMail(ModelSQL, ModelView):
     "E-mail"
-    _name = 'electronic.mail'
-    _description = __doc__
+    __name__ = 'electronic.mail'
     _order_name = 'date'
 
     mailbox = fields.Many2One(
         'electronic.mail.header', 'electronic_mail', 'Headers')
     digest = fields.Char('MD5 Digest', size=32)
     collision = fields.Integer('Collision')
-    email = fields.Function(fields.Binary('Email'), 'get_email', 'set_email')
+    email = fields.Function(fields.Binary('Email'), 'get_email', setter='set_email')
     flag_send = fields.Boolean('Sent', readonly=True)
     flag_seen = fields.Boolean('Seen')
     flag_answered = fields.Boolean('Answered')
         fields.One2Many('res.user', None, 'Write Users'),
         'get_mailbox_users', searcher='search_mailbox_users')
 
-    def __init__(self):
-        super(ElectronicMail, self).__init__()
-        self._order.insert(0, ('date', 'DESC'))
+    @classmethod
+    def __setup__(cls):
+        super(ElectronicMail, cls).__setup__()
+        cls._order.insert(0, ('date', 'DESC'))
 
-    def default_collision(self):
+    @staticmethod
+    def default_collision():
         return 0
 
-    def default_flag_seen(self):
+    @staticmethod
+    def default_flag_seen():
         return False
 
-    def default_flag_answered(self):
+    @staticmethod
+    def default_flag_answered():
         return False
 
-    def default_flag_flagged(self):
+    @staticmethod
+    def default_flag_flagged():
         return False
 
-    def default_flag_recent(self):
+    @staticmethod
+    def default_flag_recent():
         return False
 
-    def default_template(self):
+    @staticmethod
+    def default_template():
         return False
 
-    def get_rec_name(self, ids, name):
-        if not ids:
+    @classmethod
+    def get_rec_name(cls, records, name):
+        if not records:
             return {}
         res = {}
-        for mail in self.browse(ids):
+        for mail in records:
             res[mail.id] = '%s (ID: %s)' % (mail.subject, mail.id)
         return res
 
-    def get_mailbox_owner(self, ids, name):
+    @classmethod
+    def get_mailbox_owner(cls, records, name):
         "Returns owner of mailbox"
-        mails = self.browse(ids)
+        mails = records
         return dict([(mail.id, mail.mailbox.user.id) for mail in mails])
 
-    def get_mailbox_users(self, ids, name):
+    @classmethod
+    def get_mailbox_users(cls, records, name):
         assert name in ('mailbox_read_users', 'mailbox_write_users')
         res = {}
-        for mail in self.browse(ids):
+        for mail in records:
             if name == 'mailbox_read_users':
                 res[mail.id] = [x.id for x in mail.mailbox['read_users']]
             else:
                 res[mail.id] = [x.id for x in mail.mailbox['write_users']]
         return res
 
+    @classmethod
     def search_mailbox_owner(self, name, clause):
         return [('mailbox.user',) + clause[1:]]
 
+    @classmethod
     def search_mailbox_users(self, name, clause):
         return [('mailbox.' + name[8:],) + clause[1:]]
 
                 pass
         return value
 
-    def get_email(self, ids, name):
+    def get_email(self, name):
         """Fetches email from the data_path as email object
         """
-        result = { }
-        for electronic_mail in self.browse(ids):
-            result[electronic_mail.id] = self._get_email(electronic_mail) or False
-        return result
+        return self._get_email(self) or False
 
-    def set_email(self, ids, name, data):
+    @classmethod
+    def set_email(cls, records, name, data):
         """Saves an email to the data path
 
         :param data: Email as string
         directory = os.path.join(CONFIG['data_path'], db_name)
         if not os.path.isdir(directory):
             os.makedirs(directory, 0770)
-        digest = self.make_digest(data)
+        digest = cls.make_digest(data)
         directory = os.path.join(directory, 'email', digest[0:2])
         if not os.path.isdir(directory):
             os.makedirs(directory, 0770)
                         directory, digest + '-' + str(collision))
                     with open(filename, 'w') as file_p:
                         file_p.write(data)
-        self.write(ids, {'digest': digest, 'collision': collision})
+        cls.write(records, {'digest': digest, 'collision': collision})
 
-    def make_digest(self, data):
+    @staticmethod
+    def make_digest(data):
         """
         Returns a digest from the mail
 
         header_obj.create_from_email(mail, create_id)
         return create_id
 
-    def get_email_valid(self, email):
+    @classmethod
+    def get_email_valid(cls, email):
         """Get if email is valid. @ and . characters validation
         :email: str
         return: True or False
                     break
         return True
 
-ElectronicMail()
-
 
 class Header(ModelSQL, ModelView):
     "Header fields"
-    _name = 'electronic.mail.header'
-    _description = __doc__
+    __name__ = 'electronic.mail.header'
 
     name = fields.Char('Name', help='Name of Header Field')
     value = fields.Char('Value', help='Value of Header Field')
                 }
             self.create(values)
         return True
-
-Header()
 
 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',
     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_template',
     package_dir={'trytond.modules.electronic_mail': '.'},
     packages=[
         'trytond.modules.electronic_mail',
     ],
     package_data={
         'trytond.modules.electronic_mail': info.get('xml', []) \
-                + info.get('translation', []) \
-                + ['icons/*.svg'],
+            + ['tryton.cfg', 'locale/*.po', 'icons/*.svg'],
     },
     classifiers=[
         'Development Status :: 5 - Production/Stable',

tests/test_electronic_mail.py

     def setUp(self):
         trytond.tests.test_tryton.install_module('electronic_mail')
 
-        self.mailbox_obj = POOL.get('electronic_mail.mailbox')
-        self.mail_obj = POOL.get('electronic_mail')
-        self.header_obj = POOL.get('electronic_mail.header')
-        self.user_obj = POOL.get('res.user')
-        self.groups_obj = POOL.get('res.group')
-        self.ir_model_data_obj = POOL.get('ir.model.data')
+        self.Mailbox = POOL.get('electronic_mail.mailbox')
+        self.Mail = POOL.get('electronic_mail')
+        self.Header = POOL.get('electronic_mail.header')
+        self.ModelData = POOL.get('ir.model.data')
 
     def create_user(self, name):
         """
         Creates a new user and returns the ID
         """
-        group_email_admin_id =  self.ir_model_data_obj.get_id(
+        group_email_admin_id =  self.ModelData.get_id(
             'electronic_mail', 'group_email_admin')
-        group_email_user_id =  self.ir_model_data_obj.get_id(
+        group_email_user_id =  self.ModelData.get_id(
             'electronic_mail', 'group_email_user')
 
-        return self.user_obj.create(
+        return self.User.create(
             {
             'login': name,
             'name': name,
             # Create Users for testing access
             user_set_1, user_set_2 = self.create_users(no_of_sets=2)
             # Create a mailbox with a user set
-            self.mailbox_obj.create(
+            self.Mailbox.create(
                 {
                     'name': 'Parent Mailbox',
                     'user': user_set_1[0],
                     })
 
             # Create a mailbox 2 with RW users of set 1 + set 2
-            self.mailbox_obj.create(
+            self.Mailbox.create(
                 {
                     'name': 'Child Mailbox',
                     'user': user_set_2[0],
             for user_id, mailbox_count in expected_results.items():
                 with Transaction().set_user(user_id):
                     self.assertEqual(
-                        self.mailbox_obj.search([], count=True),
+                        self.Mailbox.search([], count=True),
                         mailbox_count
                     )
 
         """
         with Transaction().start(DB_NAME, USER, CONTEXT) as transaction:
             user_o, user_r, user_w = self.create_users(no_of_sets=1)[0]
-            mailbox = self.mailbox_obj.create(
+            mailbox = self.Mailbox.create(
                 {
                     'name': 'Mailbox',
                     'user': user_o,
             # Raise exception when writing a mail with the read user
             with Transaction().set_user(user_r):
                 self.assertRaises(
-                    Exception, self.mail_obj.create,
+                    Exception, self.Mail.create,
                     ({
                         'from_': 'Test',
                         'mailbox': mailbox
             # Creating mail with the write user
             with Transaction().set_user(user_w):
                 self.assert_(
-                    self.mail_obj.create({'from_': 'Test', 'mailbox': mailbox})
+                    self.Mail.create({'from_': 'Test', 'mailbox': mailbox})
                 )
 
             # Create an email as mailbox owner
             with Transaction().set_user(user_o):
                 self.assert_(
-                    self.mail_obj.create({'from_': 'Test', 'mailbox': mailbox})
+                    self.Mail.create({'from_': 'Test', 'mailbox': mailbox})
                 )
 
             transaction.cursor.rollback()
         message.attach(part2)
 
         with Transaction().start(DB_NAME, USER, CONTEXT):
-            mailbox = self.mailbox_obj.create(
+            mailbox = self.Mailbox.create(
                 {
                     'name': 'Mailbox',
                     'user': USER,
                     'read_users': [('set', [USER])],
                     'write_users': [('set', [USER])],
                     })
-            mail_id = self.mail_obj.create_from_email(message, mailbox)
-            mail = self.mail_obj.browse(mail_id)
+            mail_id = self.Mail.create_from_email(message, mailbox)
+            mail = self.Mail.browse(mail_id)
 
             self.assertEqual(mail.subject, message['Subject'])
             self.assertEqual(mail.from_, message['From'])
+[tryton]
+version=2.6.0
+depends:
+    ir
+    res
+xml:
+    electronic_mail.xml