testCRM.py 53.7 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3
##############################################################################
#
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# Copyright (c) 2007 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

import unittest
import os
31
import email.Header
32

33 34
import transaction

35
from Products.CMFCore.WorkflowCore import WorkflowException
36 37 38
from Products.ERP5Type.tests.utils import DummyMailHost, FileUpload
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase,\
                                                       _getConversionServerDict
Yusei Tahara's avatar
Yusei Tahara committed
39 40 41
from Products.ERP5OOo.tests.testIngestion import FILE_NAME_REGULAR_EXPRESSION
from Products.ERP5OOo.tests.testIngestion import REFERENCE_REGULAR_EXPRESSION

42 43
def makeFilePath(name):
  return os.path.join(os.path.dirname(__file__), 'test_data', 'crm_emails', name)
44

45 46 47
def makeFileUpload(name):
  path = makeFilePath(name)
  return FileUpload(path, name)
48

49
clear_module_name_list = """
50 51 52 53 54 55 56
campaign_module
event_module
meeting_module
organisation_module
person_module
sale_opportunity_module
""".strip().splitlines()
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
class BaseTestCRM(ERP5TypeTestCase):

  def afterSetUp(self):
    super(BaseTestCRM, self).afterSetUp()
    # add a dummy mailhost not to send real messages
    self.oldMailHost = getattr(self.portal, 'MailHost', None)
    if self.oldMailHost is not None:
      self.portal.manage_delObjects(['MailHost'])
      self.portal._setObject('MailHost', DummyMailHost('MailHost'))

  def beforeTearDown(self):
    transaction.abort()
    # restore the original MailHost
    if self.oldMailHost is not None:
      self.portal.manage_delObjects(['MailHost'])
      self.portal._setObject('MailHost', DummyMailHost('MailHost'))
    # clear modules if necessary
75
    for module_name in clear_module_name_list:
76 77 78
      module = getattr(self.portal, module_name)
      module.manage_delObjects(list(module.objectIds()))

79
    self.stepTic()
80 81 82
    super(BaseTestCRM, self).beforeTearDown()

class TestCRM(BaseTestCRM):
83 84 85
  def getTitle(self):
    return "CRM"

86
  def getBusinessTemplateList(self):
87 88
    return ('erp5_base',
            'erp5_crm',)
89

90
  def test_Event_CreateRelatedEvent(self):
91
    # test workflow to create a related event from responded event
92
    event_module = self.portal.event_module
93
    portal_workflow = self.portal.portal_workflow
94
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',)
95 96
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
97 98
      event = event_module.newContent(portal_type=ptype,
                                      follow_up_value=ticket)
99 100 101 102 103 104

      event.receive()
      event.respond()

      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)

105
      transaction.commit()
106 107 108 109 110 111 112
      self.tic()

      portal_workflow.doActionFor(event, 'create_related_event_action',
                                  related_event_portal_type=ptype,
                                  related_event_title='New Title',
                                  related_event_description='New Desc')

113
      transaction.commit()
114 115 116 117 118 119 120 121 122
      self.tic()

      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)

      related_event = event.getCausalityRelatedValue()

      self.assertEqual(related_event.getPortalType(), ptype)
      self.assertEqual(related_event.getTitle(), 'New Title')
      self.assertEqual(related_event.getDescription(), 'New Desc')
123
      self.assertEqual(related_event.getFollowUpValue(), ticket)
124
 
125
  def test_Event_CreateRelatedEventUnauthorized(self):
126
    # test that we don't get Unauthorized error when invoking the "Create
127 128
    # Related Event" without add permission on the module,
    # but will get WorkflowException error.
129 130
    event = self.portal.event_module.newContent(portal_type='Letter')
    self.portal.event_module.manage_permission('Add portal content', [], 0)
131 132 133 134 135
    self.assertRaises(WorkflowException,
                      event.Event_createRelatedEvent,
                      portal_type='Letter',
                      title='New Title',
                      description='New Desc')
136
    
137 138
  def test_Ticket_CreateRelatedEvent(self):
    # test action to create a related event from a ticket
139
    event_module_url = self.portal.event_module.absolute_url()
140
    ticket = self.portal.meeting_module.newContent(portal_type='Meeting')
141 142
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
143 144 145 146 147
      # incoming
      redirect = ticket.Ticket_newEvent(direction='incoming',
                                        portal_type=ptype,
                                        title='New Title',
                                        description='New Desc')
148 149
      self.assert_(redirect.startswith(event_module_url), redirect)
      new_id = redirect[len(event_module_url)+1:].split('/', 1)[0]
150 151 152 153 154 155 156 157 158
      new_event = self.portal.event_module._getOb(new_id)
      self.assertEquals(ticket, new_event.getFollowUpValue())
      self.assertEquals('new', new_event.getSimulationState())

      # outgoing
      redirect = ticket.Ticket_newEvent(direction='outgoing',
                                        portal_type=ptype,
                                        title='New Title',
                                        description='New Desc')
159 160
      self.assert_(redirect.startswith(event_module_url), redirect)
      new_id = redirect[len(event_module_url)+1:].split('/', 1)[0]
161 162 163
      new_event = self.portal.event_module._getOb(new_id)
      self.assertEquals(ticket, new_event.getFollowUpValue())
      self.assertEquals('planned', new_event.getSimulationState())
164

165 166 167 168 169 170 171 172 173 174
  def test_Ticket_CreateRelatedEventUnauthorized(self):
    # test that we don't get Unauthorized error when invoking the "Create
    # New Event" without add permission on the module
    ticket = self.portal.meeting_module.newContent(portal_type='Meeting')
    self.portal.event_module.manage_permission('Add portal content', [], 0)
    ticket.Ticket_newEvent(portal_type='Letter',
                           title='New Title',
                           description='New Desc',
                           direction='incoming')
   
175
  def test_PersonModule_CreateRelatedEventSelectionParams(self):
176
    # create related event from selected persons.
177 178 179 180 181 182 183 184 185
    person_module = self.portal.person_module
    pers1 = person_module.newContent(portal_type='Person', title='Pers1')
    pers2 = person_module.newContent(portal_type='Person', title='Pers2')
    pers3 = person_module.newContent(portal_type='Person', title='Pers3')
    self.portal.person_module.view()
    self.portal.portal_selections.setSelectionCheckedUidsFor(
                          'person_module_selection', [])
    self.portal.portal_selections.setSelectionParamsFor(
                          'person_module_selection', dict(title='Pers1'))
186
    transaction.commit()
187 188 189 190 191 192 193 194 195
    self.tic()
    person_module.PersonModule_newEvent(portal_type='Mail Message',
                                        title='The Event Title',
                                        description='The Event Descr.',
                                        direction='outgoing',
                                        selection_name='person_module_selection',
                                        follow_up='',
                                        text_content='Event Content',
                                        form_id='PersonModule_viewPersonList')
196

197
    transaction.commit()
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    self.tic()

    related_event = pers1.getDestinationRelatedValue(
                          portal_type='Mail Message')
    self.assertNotEquals(None, related_event)
    self.assertEquals('The Event Title', related_event.getTitle())
    self.assertEquals('The Event Descr.', related_event.getDescription())
    self.assertEquals('Event Content', related_event.getTextContent())

    for person in (pers2, pers3):
      self.assertEquals(None, person.getDestinationRelatedValue(
                                       portal_type='Mail Message'))

  def test_PersonModule_CreateRelatedEventCheckedUid(self):
    # create related event from selected persons.
    person_module = self.portal.person_module
    pers1 = person_module.newContent(portal_type='Person', title='Pers1')
    pers2 = person_module.newContent(portal_type='Person', title='Pers2')
    pers3 = person_module.newContent(portal_type='Person', title='Pers3')
    self.portal.person_module.view()
    self.portal.portal_selections.setSelectionCheckedUidsFor(
          'person_module_selection',
          [pers1.getUid(), pers2.getUid()])
221
    transaction.commit()
222 223 224 225 226 227 228 229 230 231
    self.tic()
    person_module.PersonModule_newEvent(portal_type='Mail Message',
                                        title='The Event Title',
                                        description='The Event Descr.',
                                        direction='outgoing',
                                        selection_name='person_module_selection',
                                        follow_up='',
                                        text_content='Event Content',
                                        form_id='PersonModule_viewPersonList')

232
    transaction.commit()
233 234 235 236 237 238 239 240 241 242 243 244 245
    self.tic()

    for person in (pers1, pers2):
      related_event = person.getDestinationRelatedValue(
                            portal_type='Mail Message')
      self.assertNotEquals(None, related_event)
      self.assertEquals('The Event Title', related_event.getTitle())
      self.assertEquals('The Event Descr.', related_event.getDescription())
      self.assertEquals('Event Content', related_event.getTextContent())

    self.assertEquals(None, pers3.getDestinationRelatedValue(
                                portal_type='Mail Message'))

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
  def test_SaleOpportunitySold(self):
    # test the workflow of sale opportunities, when the sale opportunity is
    # finaly sold
    so = self.portal.sale_opportunity_module.newContent(
                              portal_type='Sale Opportunity')
    self.assertEquals('draft', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'submit_action')
    self.assertEquals('submitted', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'validate_action')
    self.assertEquals('contacted', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'enquire_action')
    self.assertEquals('enquired', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'offer_action')
    self.assertEquals('offered', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'sell_action')
    self.assertEquals('sold', so.getSimulationState())

  def test_SaleOpportunityRejected(self):
    # test the workflow of sale opportunities, when the sale opportunity is
    # finaly rejected.
    # Uses different transitions than test_SaleOpportunitySold
    so = self.portal.sale_opportunity_module.newContent(
                              portal_type='Sale Opportunity')
    self.assertEquals('draft', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'validate_action')
    self.assertEquals('contacted', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'enquire_action')
    self.assertEquals('enquired', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'offer_action')
    self.assertEquals('offered', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'reject_action')
    self.assertEquals('rejected', so.getSimulationState())

  def test_SaleOpportunityExpired(self):
    # test the workflow of sale opportunities, when the sale opportunity
    # expires
    so = self.portal.sale_opportunity_module.newContent(
                              portal_type='Sale Opportunity')
    self.assertEquals('draft', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'validate_action')
    self.assertEquals('contacted', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'expire_action')
    self.assertEquals('expired', so.getSimulationState())

290 291 292
  def test_Event_AcknowledgeAndCreateEvent(self):
    """
    Make sure that when acknowledge event, we can create a new event.
293 294 295 296 297 298 299

    XXX This is probably meaningless in near future. event_workflow
    will be reviewed in order to have steps closer to usual packing 
    list workflow. For now we have a conflict name between the 
    acknowledge method of event_workflow and Acknowledgement features
    that comes with AcknowledgementTool. So for now disable site
    message in this test.
300 301 302
    """
    portal_workflow = self.portal.portal_workflow

303
    event_type_list = [x for x in self.portal.getPortalEventTypeList() \
304
                       if x not in  ['Site Message', 'Acknowledgement']]
305

306
    # if create_event option is false, it does not create a new event.
307
    for portal_type in event_type_list:
308 309 310 311 312
      ticket = self.portal.meeting_module.newContent(portal_type='Meeting',
                                                     title='Meeting1')
      ticket_url = ticket.getRelativeUrl()
      event = self.portal.event_module.newContent(portal_type=portal_type,
                                                  follow_up=ticket_url)
313
      transaction.commit()
314 315 316 317
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action', create_event=0)
318
      transaction.commit()
319 320 321 322
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      
    # if create_event option is true, it create a new event.
323
    for portal_type in event_type_list:
324 325 326 327 328
      ticket = self.portal.meeting_module.newContent(portal_type='Meeting',
                                                     title='Meeting1')
      ticket_url = ticket.getRelativeUrl()
      event = self.portal.event_module.newContent(portal_type=portal_type,
                                                  follow_up=ticket_url)
329
      transaction.commit()
330 331 332 333
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action', create_event=1)
334
      transaction.commit()
335 336 337 338 339
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)
      new_event = event.getCausalityRelatedValue()
      self.assertEqual(new_event.getFollowUp(), ticket_url)

340 341
    # if quote_original_message option is true, the new event content will be
    # the current event message quoted.
342
    for portal_type in event_type_list:
343 344 345 346 347 348 349
      ticket = self.portal.meeting_module.newContent(portal_type='Meeting',
                                                     title='Meeting1')
      ticket_url = ticket.getRelativeUrl()
      event = self.portal.event_module.newContent(portal_type=portal_type,
                                                  follow_up=ticket_url,
                                                  title='Event Title',
                                                  text_content='Event Content',
350
                                                  content_type='text/plain')
351
      transaction.commit()
352 353 354 355 356 357
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action',
                                  create_event=1,
                                  quote_original_message=1)
358
      transaction.commit()
359 360 361 362
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)
      new_event = event.getCausalityRelatedValue()
      self.assertEqual(new_event.getFollowUp(), ticket_url)
363
      self.assertEqual(new_event.getContentType(), 'text/plain')
364 365 366
      self.assertEqual(new_event.getTextContent(), '> Event Content')
      self.assertEqual(new_event.getTitle(), 'Re: Event Title')

367

368
class TestCRMMailIngestion(BaseTestCRM):
Yusei Tahara's avatar
Yusei Tahara committed
369
  """Test Mail Ingestion for standalone CRM.
370
  """
371 372
  def getTitle(self):
    return "CRM Mail Ingestion"
373 374

  def getBusinessTemplateList(self):
375 376 377
    # Mail Ingestion must work with CRM alone.
    return ('erp5_base',
            'erp5_ingestion',
Yusei Tahara's avatar
Yusei Tahara committed
378 379
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_crm',
380
            )
381 382

  def afterSetUp(self):
383
    super(TestCRMMailIngestion, self).afterSetUp()
384
    portal = self.portal
385

386
    # create customer organisation and person
387 388 389 390
    portal.organisation_module.newContent(
            id='customer',
            portal_type='Organisation',
            title='Customer')
391
    customer_organisation = portal.organisation_module.customer
392 393 394 395 396
    portal.person_module.newContent(
            id='sender',
            title='Sender',
            subordination_value=customer_organisation,
            default_email_text='sender@customer.com')
397
    # also create the recipients
398 399 400 401 402 403 404 405
    portal.person_module.newContent(
            id='me',
            title='Me',
            default_email_text='me@erp5.org')
    portal.person_module.newContent(
            id='he',
            title='He',
            default_email_text='he@erp5.org')
406

407
    # make sure customers are available to catalog
408
    transaction.commit()
409
    self.tic()
410

Yusei Tahara's avatar
Yusei Tahara committed
411 412 413 414 415 416
  def _readTestData(self, filename):
    """read test data from data directory."""
    return file(os.path.join(os.path.dirname(__file__),
                             'test_data', 'crm_emails', filename)).read()

  def _ingestMail(self, filename=None, data=None):
417
    """ingest an email from the mail in data dir named `filename`"""
Yusei Tahara's avatar
Yusei Tahara committed
418 419
    if data is None:
      data=self._readTestData(filename)
420 421 422 423 424 425 426
    return self.portal.portal_contributions.newContent(
                    container_path='event_module',
                    file_name='postfix_mail.eml',
                    data=data)

  def test_findTypeByName_MailMessage(self):
    # without this, ingestion will not work
427 428 429 430 431
    self.assertEquals(
      'Mail Message',
      self.portal.portal_contribution_registry.findPortalTypeName(
      file_name='postfix_mail.eml', mime_type='message/rfc822', data='Test'
      ))
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
  def test_Base_getEntityListFromFromHeader(self):
    expected_values = (
      ('me@erp5.org', ['person_module/me']),
      ('me@erp5.org, he@erp5.org', ['person_module/me', 'person_module/he']),
      ('Sender <sender@customer.com>', ['person_module/sender']),
      # tricks to confuse the e-mail parser:
      # a comma in the name
      ('"Sender," <sender@customer.com>, he@erp5.org', ['person_module/sender',
                                                        'person_module/he']),
      # multiple e-mails in the "Name" part that shouldn't be parsed
      ('"me@erp5.org,sender@customer.com," <he@erp5.org>', ['person_module/he']),
      # a < sign
      ('"He<" <he@erp5.org>', ['person_module/he']),
    )
    portal = self.portal
    Base_getEntityListFromFromHeader = portal.Base_getEntityListFromFromHeader
    pc = self.portal.portal_catalog
    for header, expected_paths in expected_values:
      paths = [entity.getRelativeUrl()
               for entity in portal.Base_getEntityListFromFromHeader(header)] 
      self.assertEquals(paths, expected_paths,
                        '%r should return %r, but returned %r' %
                        (header, expected_paths, paths))

457 458 459 460 461 462
  def test_document_creation(self):
    # CRM email ingestion creates a Mail Message in event_module
    event = self._ingestMail('simple')
    self.assertEquals(len(self.portal.event_module), 1)
    self.assertEquals(event, self.portal.event_module.contentValues()[0])
    self.assertEquals('Mail Message', event.getPortalType())
463 464
    self.assertEquals('text/plain', event.getContentType())
    self.assertEquals('message/rfc822', event._baseGetContentType())
465 466 467 468 469
    # check if parsing of metadata from content is working
    content_dict = {'source_list': ['person_module/sender'],
                    'destination_list': ['person_module/me',
                                         'person_module/he']}
    self.assertEquals(event.getPropertyDictFromContent(), content_dict)
470

471
  def test_title(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
472
    # title is found automatically, based on the Subject: header in the mail
473 474
    event = self._ingestMail('simple')
    self.assertEquals('Simple Mail Test', event.getTitle())
475
    self.assertEquals('Simple Mail Test', event.getTitleOrId())
476 477 478 479 480 481

  def test_asText(self):
    # asText requires portal_transforms
    event = self._ingestMail('simple')
    self.assertEquals('Hello,\nContent of the mail.\n', str(event.asText()))
 
482 483 484 485
  def test_sender(self):
    # source is found automatically, based on the From: header in the mail
    event = self._ingestMail('simple')
    # metadata discovery is done in an activity
486
    transaction.commit()
487 488 489 490 491 492
    self.tic()
    self.assertEquals('person_module/sender', event.getSource())

  def test_recipient(self):
    # destination is found automatically, based on the To: header in the mail
    event = self._ingestMail('simple')
493
    transaction.commit()
494
    self.tic()
495 496 497 498
    destination_list = event.getDestinationList()
    destination_list.sort()
    self.assertEquals(['person_module/he', 'person_module/me'],
                      destination_list)
499 500 501 502 503 504 505

  def test_follow_up(self):
    # follow up is found automatically, based on the content of the mail, and
    # what you defined in preference regexpr.
    # But, we don't want it to associate with the first campaign simply
    # because we searched against nothing
    self.portal.campaign_module.newContent(portal_type='Campaign')
506
    transaction.commit()
507 508
    self.tic()
    event = self._ingestMail('simple')
509
    transaction.commit()
510 511
    self.tic()
    self.assertEquals(None, event.getFollowUp())
Yusei Tahara's avatar
Yusei Tahara committed
512 513 514 515 516 517 518 519 520

  def test_portal_type_determination(self):
    """
    Make sure that ingested email will be correctly converted to
    appropriate portal type by email metadata.
    """
    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'Visit:Company A')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
521
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
522 523 524 525 526 527
    self.assertEqual(document.portal_type, 'Visit')
    self.assertEqual(document.getTitle(), 'Company A')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'Fax:Company B')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
528
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
529 530 531 532 533 534
    self.assertEqual(document.portal_type, 'Fax Message')
    self.assertEqual(document.getTitle(), 'Company B')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'TEST:Company B')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
535
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
536 537 538 539 540 541
    self.assertEqual(document.portal_type, 'Mail Message')
    self.assertEqual(document.getTitle(), 'TEST:Company B')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'visit:Company A')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
542
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
543 544 545 546 547 548
    self.assertEqual(document.portal_type, 'Visit')
    self.assertEqual(document.getTitle(), 'Company A')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'phone:Company B')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
549
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
550 551 552 553 554 555
    self.assertEqual(document.portal_type, 'Phone Call')
    self.assertEqual(document.getTitle(), 'Company B')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'LETTER:Company C')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
556
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
557 558 559 560 561 562 563
    self.assertEqual(document.portal_type, 'Letter')
    self.assertEqual(document.getTitle(), 'Company C')

    message = email.message_from_string(self._readTestData('simple'))
    body = message.get_payload()
    message.set_payload('Visit:%s' % body)
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
564
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
565 566 567 568 569 570 571
    self.assertEqual(document.portal_type, 'Visit')
    self.assertEqual(document.getTextContent(), body)

    message = email.message_from_string(self._readTestData('simple'))
    body = message.get_payload()
    message.set_payload('PHONE CALL:%s' % body)
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
572
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
573 574 575
    self.assertEqual(document.portal_type, 'Phone Call')
    self.assertEqual(document.getTextContent(), body)

Yusei Tahara's avatar
Yusei Tahara committed
576 577 578 579 580 581 582 583
  def test_forwarder_mail(self):
    """
    Make sure that if ingested email is forwarded one, the sender of
    original mail should be the sender of event and the sender of
    forwarded mail should be the recipient of event.
    """
    document = self._ingestMail(filename='forwarded')

584
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
585 586 587 588 589 590
    self.tic()

    self.assertEqual(document.getContentInformation().get('From'), 'Me <me@erp5.org>')
    self.assertEqual(document.getContentInformation().get('To'), 'crm@erp5.org')
    self.assertEqual(document.getSourceValue().getTitle(), 'Sender')
    self.assertEqual(document.getDestinationValue().getTitle(), 'Me')
591 592 593 594 595 596 597 598 599

  def test_forwarder_mail_with_attachment(self):
    """
    Make sure that if ingested email is forwarded one, the sender of
    original mail should be the sender of event and the sender of
    forwarded mail should be the recipient of event.
    """
    document = self._ingestMail(filename='forwarded_attached')

600
    transaction.commit()
601 602 603 604 605 606
    self.tic()

    self.assertEqual(document.getContentInformation().get('From'), 'Me <me@erp5.org>')
    self.assertEqual(document.getContentInformation().get('To'), 'crm@erp5.org')
    self.assertEqual(document.getSourceValue().getTitle(), 'Sender')
    self.assertEqual(document.getDestinationValue().getTitle(), 'Me')
Yusei Tahara's avatar
Yusei Tahara committed
607

608 609 610
  def test_encoding(self):
    document = self._ingestMail(filename='encoded')

611
    transaction.commit()
612 613 614 615 616 617 618 619 620 621 622
    self.tic()

    self.assertEqual(document.getContentInformation().get('To'),
                     'Me <me@erp5.org>')
    self.assertEqual(document.getSourceValue().getTitle(), 'Sender')
    self.assertEqual(document.getDestinationValue().getTitle(), 'Me')
    self.assertEqual(document.getContentInformation().get('Subject'),
                     'Test éncödèd email')
    self.assertEqual(document.getTitle(), 'Test éncödèd email')
    self.assertEqual(document.getTextContent(), 'cöntént\n')

Yusei Tahara's avatar
Yusei Tahara committed
623

624 625 626 627 628 629 630 631 632 633 634 635 636 637
  def test_HTML_multipart_attachments(self):
    """Test that html attachments are cleaned up.
    and check the behaviour of getTextContent
    if multipart/alternative return html
    if multipart/mixed return text
    """
    document = self._ingestMail(filename='sample_multipart_mixed_and_alternative')
    transaction.commit()
    self.tic()
    stripped_html = document.asStrippedHTML()
    self.assertTrue('<form' not in stripped_html)
    self.assertTrue('<form' not in document.getAttachmentData(4))
    self.assertEquals('This is my content.\n*ERP5* is a Free _Software_\n',
                      document.getAttachmentData(2))
638
    self.assertEquals('text/html', document.getContentType())
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
    self.assertEquals('\n<html>\n<head>\n\n<meta http-equiv="content-type"'\
                      ' content="text/html; charset=utf-8" />\n'\
                      '</head>\n<body text="#000000"'\
                      ' bgcolor="#ffffff">\nThis is my content.<br />\n'\
                      '<b>ERP5</b> is a Free <u>Software</u><br />'\
                      '\n\n</body>\n</html>\n', document.getAttachmentData(3))
    self.assertEquals(document.getAttachmentData(3), document.getTextContent())

    # now check a message with multipart/mixed
    mixed_document = self._ingestMail(filename='sample_html_attachment')
    transaction.commit()
    self.tic()
    self.assertEquals(mixed_document.getAttachmentData(1),
                      mixed_document.getTextContent())
    self.assertEquals('Hi, this is the Message.\nERP5 is a free software.\n\n',
                      mixed_document.getTextContent())
655
    self.assertEquals('text/plain', mixed_document.getContentType())
656 657


658 659 660 661 662
## TODO:
##
##  def test_attachements(self):
##    event = self._ingestMail('with_attachements')
##
663

664
class TestCRMMailSend(BaseTestCRM):
Yusei Tahara's avatar
Yusei Tahara committed
665 666
  """Test Mail Sending for CRM
  """
667 668
  def getTitle(self):
    return "CRM Mail Sending"
Yusei Tahara's avatar
Yusei Tahara committed
669 670

  def getBusinessTemplateList(self):
Yusei Tahara's avatar
Yusei Tahara committed
671 672
    # In this test, We will attach some document portal types in event.
    # So we add DMS and Web.
673 674 675 676 677 678 679
    return ('erp5_base',
            'erp5_ingestion',
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_crm',
            'erp5_web',
            'erp5_dms',
            )
Yusei Tahara's avatar
Yusei Tahara committed
680 681

  def afterSetUp(self):
682
    super(TestCRMMailSend, self).afterSetUp()
Yusei Tahara's avatar
Yusei Tahara committed
683 684 685
    portal = self.portal

    # create customer organisation and person
686 687 688 689
    portal.organisation_module.newContent(
            id='customer',
            portal_type='Organisation',
            title='Customer')
690
    customer_organisation = portal.organisation_module.customer
691 692 693 694 695 696 697 698 699 700 701 702 703 704
    portal.person_module.newContent(
            id='recipient',
            # The ',' below is to force quoting of the name in e-mail
            # addresses on Zope 2.12
            title='Recipient,',
            subordination_value=customer_organisation,
            default_email_text='recipient@example.com')
    # also create the sender
    portal.person_module.newContent(
            id='me',
            # The ',' below is to force quoting of the name in e-mail
            # addresses on Zope 2.12
            title='Me,',
            default_email_text='me@erp5.org')
Yusei Tahara's avatar
Yusei Tahara committed
705 706 707

    # set preference
    default_pref = self.portal.portal_preferences.default_site_preference
708 709 710
    conversion_dict = _getConversionServerDict()
    default_pref.setPreferredOoodocServerAddress(conversion_dict['hostname'])
    default_pref.setPreferredOoodocServerPortNumber(conversion_dict['port'])
Yusei Tahara's avatar
Yusei Tahara committed
711 712
    default_pref.setPreferredDocumentFileNameRegularExpression(FILE_NAME_REGULAR_EXPRESSION)
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
713 714
    if default_pref.getPreferenceState() == 'disabled':
      default_pref.enable()
Yusei Tahara's avatar
Yusei Tahara committed
715 716

    # make sure customers are available to catalog
717
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
718 719
    self.tic()

720 721 722 723 724 725 726 727 728 729
  def test_MailFromMailMessageEvent(self):
    # passing start_action transition on event workflow will send an email to the
    # person as destination
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTitle('A Mail')
    event.setTextContent('Mail Content')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
730
    transaction.commit()
731 732 733 734
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
735 736
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
737 738 739
    
    message = email.message_from_string(messageText)

740 741
    self.assertEquals('A Mail',
                      email.Header.decode_header(message['Subject'])[0][0])
742 743 744 745 746 747
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual('Mail Content', part.get_payload(decode=True))

748 749 750 751 752 753 754 755 756 757 758
    #
    # Test multiple recipients.
    #
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    # multiple recipients.
    event.setDestinationList(['person_module/recipient', 'person_module/me'])
    event.setTitle('A Mail')
    event.setTextContent('Mail Content')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
759
    transaction.commit()
760 761 762 763
    self.tic()
    last_message_1, last_message_2 = self.portal.MailHost._message_list[-2:]
    self.assertNotEquals((), last_message_1)
    self.assertNotEquals((), last_message_2)
764 765
    # check last message 1 and last message 2 (the order is random)
    # both should have 'From: Me'
766
    self.assertEquals(['"Me," <me@erp5.org>', '"Me," <me@erp5.org>'],
767 768
                      [x[0] for x in (last_message_1, last_message_2)])
    # one should have 'To: Me' and the other should have 'To: Recipient'
769
    self.assertEquals([['"Me," <me@erp5.org>'], ['"Recipient," <recipient@example.com>']],
770
                      sorted([x[1] for x in (last_message_1, last_message_2)]))
771

772 773 774 775 776 777 778 779 780 781 782
  def test_MailFromMailMessageEventNoSendMail(self):
    # passing start_action transition on event workflow will send an email to the
    # person as destination, unless you don't check "send_mail" box in the
    # workflow dialog
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTitle('A Mail')
    event.setTextContent('Mail Content')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
783
    transaction.commit()
784 785 786 787 788 789 790 791
    self.tic()
    # no mail sent
    last_message = self.portal.MailHost._last_message

  def test_MailFromOtherEvents(self):
    # passing start_action transition on event workflow will not send an email
    # when the portal type is not Mail Message
    for ptype in [t for t in self.portal.getPortalEventTypeList()
792 793
        if t not in ('Mail Message', 'Document Ingestion Message',
          'Acknowledgement')]:
794 795 796 797 798 799 800
      event = self.portal.event_module.newContent(portal_type=ptype)
      event.setSource('person_module/me')
      event.setDestination('person_module/recipient')
      event.setTextContent('Hello !')
      self.portal.portal_workflow.doActionFor(event, 'start_action',
                                              send_mail=1)

801
      transaction.commit()
802 803 804 805
      self.tic()
      # this means no message have been set
      self.assertEquals((), self.portal.MailHost._last_message)

Rafael Monnerat's avatar
Rafael Monnerat committed
806 807 808
  def test_MailMarkPosted(self):
    # mark_started_action transition on event workflow will not send an email
    # even if the portal type is a Mail Message
809 810
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
Rafael Monnerat's avatar
Rafael Monnerat committed
811 812 813 814 815 816 817
      event = self.portal.event_module.newContent(portal_type=ptype)
      event.setSource('person_module/me')
      event.setDestination('person_module/recipient')
      event.setTextContent('Hello !')
      self.portal.portal_workflow.doActionFor(event, 'receive_action')
      self.portal.portal_workflow.doActionFor(event, 'mark_started_action')

818
      transaction.commit()
Rafael Monnerat's avatar
Rafael Monnerat committed
819 820 821 822 823
      self.tic()
      # this means no message have been set
      self.assertEquals((), self.portal.MailHost._last_message)


824
  def test_MailMessageHTML(self):
825 826
    # test sending a mail message edited as HTML (the default with FCKEditor),
    # then the mail should have HTML.
827 828 829
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
830
    event.setContentType('text/html')
831 832 833
    event.setTextContent('Hello<br/>World')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
834
    transaction.commit()
835 836 837 838
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
839 840
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
841

842 843 844
    message = email.message_from_string(messageText)
    part = None
    for i in message.get_payload():
845
      if i.get_content_type()=='text/html':
846
        part = i
847 848
    self.assertNotEqual(part, None)
    self.assertEqual('<html><body>Hello<br/>World</body></html>', part.get_payload(decode=True))
849 850 851 852 853 854 855 856 857 858

  def test_MailMessageEncoding(self):
    # test sending a mail message with non ascii characters
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTitle('Héhé')
    event.setTextContent('Hàhà')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
859
    transaction.commit()
860 861 862 863
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
864 865
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
866 867 868
    
    message = email.message_from_string(messageText)

869 870
    self.assertEquals('Héhé',
                      email.Header.decode_header(message['Subject'])[0][0])
871 872 873 874 875 876
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual('Hàhà', part.get_payload(decode=True))

Yusei Tahara's avatar
Yusei Tahara committed
877
  def test_MailAttachmentPdf(self):
Yusei Tahara's avatar
Yusei Tahara committed
878 879 880
    """
    Make sure that pdf document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
881 882
    # Add a document which will be attached.

Yusei Tahara's avatar
Yusei Tahara committed
883
    def add_document(filename, id, container, portal_type):
884
      f = makeFileUpload(filename)
Yusei Tahara's avatar
Yusei Tahara committed
885 886 887
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document
Yusei Tahara's avatar
Yusei Tahara committed
888

Yusei Tahara's avatar
Yusei Tahara committed
889 890 891
    # pdf
    document_pdf = add_document('sample_attachment.pdf', '1',
                                self.portal.document_module, 'PDF')
Yusei Tahara's avatar
Yusei Tahara committed
892

893
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
909
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
910
               aggregate=document_pdf.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # pdf
    self.assert_('sample_attachment.pdf' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.pdf':
        part = i
    self.assertEqual(part.get_payload(decode=True), str(document_pdf.getData()))
Yusei Tahara's avatar
Yusei Tahara committed
932 933

  def test_MailAttachmentText(self):
Yusei Tahara's avatar
Yusei Tahara committed
934 935 936
    """
    Make sure that text document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
937 938 939
    # Add a document which will be attached.

    def add_document(filename, id, container, portal_type):
940
      f = makeFileUpload(filename)
Yusei Tahara's avatar
Yusei Tahara committed
941 942 943 944 945 946 947 948
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # odt
    document_odt = add_document('sample_attachment.odt', '2',
                                self.portal.document_module, 'Text')
    
949
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
965
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
966 967 968 969 970 971 972 973 974 975 976 977 978 979
               aggregate=document_odt.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
Yusei Tahara's avatar
Yusei Tahara committed
980 981 982 983 984 985 986 987 988
    # odt
    self.assert_('sample_attachment.odt' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.odt':
        part = i
    self.assert_(len(part.get_payload(decode=True))>0)

Yusei Tahara's avatar
Yusei Tahara committed
989
  def test_MailAttachmentFile(self):
Yusei Tahara's avatar
Yusei Tahara committed
990 991 992
    """
    Make sure that file document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
993 994 995
    # Add a document which will be attached.

    def add_document(filename, id, container, portal_type):
996
      f = makeFileUpload(filename)
Yusei Tahara's avatar
Yusei Tahara committed
997 998 999 1000 1001 1002 1003 1004
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # zip
    document_zip = add_document('sample_attachment.zip', '3',
                                self.portal.document_module, 'File')

1005
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1021
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
               aggregate=document_zip.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # zip
    self.assert_('sample_attachment.zip' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.zip':
        part = i
    self.assert_(len(part.get_payload(decode=True))>0)

  def test_MailAttachmentImage(self):
Yusei Tahara's avatar
Yusei Tahara committed
1046 1047 1048
    """
    Make sure that image document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1049 1050 1051
    # Add a document which will be attached.

    def add_document(filename, id, container, portal_type):
1052
      f = makeFileUpload(filename)
Yusei Tahara's avatar
Yusei Tahara committed
1053 1054 1055 1056 1057 1058 1059 1060
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # gif
    document_gif = add_document('sample_attachment.gif', '4',
                                self.portal.image_module, 'Image')

1061
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1077
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
               aggregate=document_gif.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # gif
    self.assert_('sample_attachment.gif' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.gif':
        part = i
    self.assertEqual(part.get_payload(decode=True), str(document_gif.getData()))

  def test_MailAttachmentWebPage(self):
Yusei Tahara's avatar
Yusei Tahara committed
1102 1103 1104
    """
    Make sure that webpage document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1105 1106 1107 1108 1109 1110 1111
    # Add a document which will be attached.

    document_html = self.portal.web_page_module.newContent(id='5',
                                                           portal_type='Web Page')
    document_html.edit(text_content='<html><body>Hello world!</body></html>',
                       reference='sample_attachment.html')

1112
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1128
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
               aggregate=document_html.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # html
    self.assert_('sample_attachment.html' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.html':
        part = i
1150 1151 1152
    self.assertEqual(part.get_payload(decode=True),
                     str(document_html.getTextContent()))
    self.assertEqual(part.get_content_type(), 'text/html')
Yusei Tahara's avatar
Yusei Tahara committed
1153

Aurel's avatar
Aurel committed
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  def test_MailRespond(self):
    """
    Test we can answer an incoming event and quote it
    """
    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='incoming')
Yusei Tahara's avatar
Yusei Tahara committed
1167

Aurel's avatar
Aurel committed
1168 1169 1170
    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1171
               destination='person_module/recipient',
Aurel's avatar
Aurel committed
1172 1173 1174 1175 1176
               text_content='This is an advertisement mail.')
    first_event_id = event.getId()
    self.getWorkflowTool().doActionFor(event, 'respond_action', 
                                       respond_event_portal_type = "Mail Message",
                                       respond_event_title = "Answer",
1177
                                       respond_event_text_content="> This is an advertisement mail."
Aurel's avatar
Aurel committed
1178 1179 1180
                                       )

    self.assertEqual(event.getSimulationState(), "responded")
1181

Aurel's avatar
Aurel committed
1182 1183 1184 1185 1186 1187 1188
    # answer event must have been created
    self.assertEqual(len(self.portal.event_module), 2)
    for ev in self.portal.event_module.objectValues():
      if ev.getId() != first_event_id:
        answer_event = ev

    # check properties of answer event
1189
    self.assertEqual(answer_event.getSimulationState(), "started")
Aurel's avatar
Aurel committed
1190 1191
    self.assertEqual(answer_event.getCausality(), event.getRelativeUrl())
    self.assertEqual(answer_event.getDestination(), 'person_module/me')
1192
    self.assertEqual(answer_event.getSource(), 'person_module/recipient')
Aurel's avatar
Aurel committed
1193
    self.assertEqual(answer_event.getTextContent(), '> This is an advertisement mail.')
1194 1195
    self.assertEqual(answer_event.getFollowUpValue(), ticket)
    self.assert_(answer_event.getData() is not None)
Yusei Tahara's avatar
Yusei Tahara committed
1196

1197 1198 1199 1200 1201 1202 1203
  def test_MailAttachmentFileWithoutDMS(self):
    """
    Make sure that file document is correctly attached in email
    """
    # Add a document on a person which will be attached.

    def add_document(filename, id, container, portal_type):
1204
      f = makeFileUpload(filename)
1205 1206 1207 1208 1209 1210 1211 1212
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # txt
    document_txt = add_document('sample_attachment.txt', '2',
                                self.portal.person_module['me'], 'File')

1213
    transaction.commit()
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1229
               destination='person_module/recipient',
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
               aggregate=document_txt.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
1241
        break
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # txt
    self.assert_('sample_attachment.txt' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.txt':
        part = i
    self.assert_(len(part.get_payload(decode=True))>0)



  def test_MailAttachmentImageWithoutDMS(self):
    """
    Make sure that image document is correctly attached in email without dms
    """
    # Add a document on a person which will be attached.

    def add_document(filename, id, container, portal_type):
1263
      f = makeFileUpload(filename)
1264 1265 1266 1267 1268 1269 1270 1271
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # gif
    document_gif = add_document('sample_attachment.gif', '1',
                                self.portal.person_module['me'], 'Image')

1272
    transaction.commit()
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1288
               destination='person_module/recipient',
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
               aggregate=document_gif.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # gif
    self.assert_('sample_attachment.gif' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.gif':
        part = i
    self.assertEqual(part.get_payload(decode=True), str(document_gif.getData()))

1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
  def test_cloneEvent(self):
    """
      All events uses after script and interaciton
      workflow add a test for clone
    """
    portal_type = "Mail Message"
    event = self.portal.event_module.newContent(portal_type=portal_type)
    event.setData("This is the context of the event...")
    self.stepTic()
    new_event = event.Base_createCloneDocument(batch_mode=1)
    self.failIf(new_event.hasFile())
    self.assertEquals(new_event.getData(), "")

1325

1326 1327
def test_suite():
  suite = unittest.TestSuite()
1328
  suite.addTest(unittest.makeSuite(TestCRM))
1329
  suite.addTest(unittest.makeSuite(TestCRMMailIngestion))
Yusei Tahara's avatar
Yusei Tahara committed
1330
  suite.addTest(unittest.makeSuite(TestCRMMailSend))
1331
  return suite