testCRM.py 69.3 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

32
from Products.CMFCore.WorkflowCore import WorkflowException
33
from Products.ERP5Type.tests.utils import FileUpload
34 35
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase,\
                                                       _getConversionServerDict
Nicolas Delaby's avatar
Nicolas Delaby committed
36
from Products.ERP5OOo.tests.testIngestion import FILENAME_REGULAR_EXPRESSION
Yusei Tahara's avatar
Yusei Tahara committed
37
from Products.ERP5OOo.tests.testIngestion import REFERENCE_REGULAR_EXPRESSION
38
from Products.ERP5Type.tests.backportUnittest import expectedFailure
39 40 41 42 43
from email.header import decode_header
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders, message_from_string
44
from DateTime import DateTime
Yusei Tahara's avatar
Yusei Tahara committed
45

46 47
def makeFilePath(name):
  return os.path.join(os.path.dirname(__file__), 'test_data', 'crm_emails', name)
48

49 50 51
def makeFileUpload(name):
  path = makeFilePath(name)
  return FileUpload(path, name)
52

53
clear_module_name_list = """
54 55 56 57 58 59
campaign_module
event_module
meeting_module
organisation_module
person_module
sale_opportunity_module
60
portal_categories/resource
Nicolas Delaby's avatar
Nicolas Delaby committed
61
portal_categories/function
62
""".strip().splitlines()
63

64 65 66 67
class BaseTestCRM(ERP5TypeTestCase):

  def afterSetUp(self):
    super(BaseTestCRM, self).afterSetUp()
68
    self.portal.MailHost.reset()
69 70

  def beforeTearDown(self):
71
    self.abort()
72
    # clear modules if necessary
73
    for module_name in clear_module_name_list:
74
      module = self.portal.unrestrictedTraverse(module_name)
75
      module.manage_delObjects(list(module.objectIds()))
76
    self.stepTic()
77 78 79
    super(BaseTestCRM, self).beforeTearDown()

class TestCRM(BaseTestCRM):
80 81 82
  def getTitle(self):
    return "CRM"

83
  def getBusinessTemplateList(self):
84 85 86 87
    return ('erp5_full_text_myisam_catalog',
            'erp5_core_proxy_field_legacy',
            'erp5_base',
            'erp5_ingestion',
88
            '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
      event.stop()
101 102 103 104 105

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

      self.tic()

106 107 108 109 110
      event.Event_createResponse(response_event_portal_type=ptype,
                                 response_event_title='New Title',
                                 response_event_text_content='New Desc',
                                 response_workflow_action='plan',
                                 )
111 112 113 114 115 116 117 118 119

      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')
120
      self.assertEqual(related_event.getTextContent(), 'New Desc')
121
      self.assertEqual(related_event.getFollowUpValue(), ticket)
Nicolas Delaby's avatar
Nicolas Delaby committed
122

123
  def test_Event_CreateRelatedEventUnauthorized(self):
124
    # test that we don't get Unauthorized error when invoking the "Create
125 126
    # Related Event" without add permission on the module,
    # but will get WorkflowException error.
127 128
    event = self.portal.event_module.newContent(portal_type='Letter')
    self.portal.event_module.manage_permission('Add portal content', [], 0)
129 130 131 132 133
    self.assertRaises(WorkflowException,
                      event.Event_createRelatedEvent,
                      portal_type='Letter',
                      title='New Title',
                      description='New Desc')
Nicolas Delaby's avatar
Nicolas Delaby committed
134

135 136
  def test_Ticket_CreateRelatedEvent(self):
    # test action to create a related event from a ticket
137
    event_module_url = self.portal.event_module.absolute_url()
138
    ticket = self.portal.meeting_module.newContent(portal_type='Meeting')
139 140
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
141
      # incoming
142 143 144 145 146 147
      ticket.Ticket_newEvent(direction='incoming',
                             portal_type=ptype,
                             title='Incoming Title',
                             description='New Desc')
      self.tic()
      new_event = ticket.getFollowUpRelatedValueList()[0]
148
      self.assertEquals('stopped', new_event.getSimulationState())
149 150

      # outgoing
151
      ticket.Ticket_newEvent(direction='outgoing',
152
                                        portal_type=ptype,
153
                                        title='Outgoing Title',
154
                                        description='New Desc')
155 156 157
      self.tic()
      new_event = [event for event in ticket.getFollowUpRelatedValueList() if\
                   event.getTitle() == 'Outgoing Title'][0]
158
      self.assertEquals('planned', new_event.getSimulationState())
159

160 161 162 163 164 165 166 167 168
  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')
Nicolas Delaby's avatar
Nicolas Delaby committed
169

170
  def test_PersonModule_CreateRelatedEventSelectionParams(self):
171
    # create related event from selected persons.
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    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'))
    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')
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    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()])
    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')

    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'))

237 238 239 240 241 242 243 244 245 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
  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())

281
  @expectedFailure
282 283 284
  def test_Event_AcknowledgeAndCreateEvent(self):
    """
    Make sure that when acknowledge event, we can create a new event.
285 286 287 288 289 290 291

    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.
292 293 294
    """
    portal_workflow = self.portal.portal_workflow

295
    event_type_list = [x for x in self.portal.getPortalEventTypeList() \
296
                       if x not in  ['Site Message', 'Acknowledgement']]
297

298
    # if create_event option is false, it does not create a new event.
299
    for portal_type in event_type_list:
300 301 302 303 304 305 306 307 308 309 310
      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)
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action', create_event=0)
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
Nicolas Delaby's avatar
Nicolas Delaby committed
311

312
    # if create_event option is true, it create a new event.
313
    for portal_type in event_type_list:
314 315 316 317 318 319 320 321 322 323 324 325 326 327
      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)
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action', create_event=1)
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)
      new_event = event.getCausalityRelatedValue()
      self.assertEqual(new_event.getFollowUp(), ticket_url)

328 329
    # if quote_original_message option is true, the new event content will be
    # the current event message quoted.
330
    for portal_type in event_type_list:
331 332 333 334 335 336 337
      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',
338
                                                  content_type='text/plain')
339 340 341 342 343 344 345 346 347 348
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action',
                                  create_event=1,
                                  quote_original_message=1)
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)
      new_event = event.getCausalityRelatedValue()
      self.assertEqual(new_event.getFollowUp(), ticket_url)
349
      self.assertEqual(new_event.getContentType(), 'text/plain')
350 351 352
      self.assertEqual(new_event.getTextContent(), '> Event Content')
      self.assertEqual(new_event.getTitle(), 'Re: Event Title')

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
  def test_SupportRequest_referenceAutomaticallyGenerated(self):
    """
      When you create or clone a Support Request document, it must 
      have the reference generated automatically.
    """
    portal_type = "Support Request"
    title = "Title of the Support Request"
    content = "This is the content of the Support Request"
    module = self.portal.support_request_module
    support_request = module.newContent(portal_type=portal_type,
                                        title=title,)
    self.stepTic()

    self.assertNotEquals(None, support_request.getReference())

    new_support_request = support_request.Base_createCloneDocument(
                                                                 batch_mode=1)
    self.assertEquals(new_support_request.getTitle(), title)
    self.assertNotEquals(None, support_request.getReference())
    self.assertNotEquals(support_request.getReference(), 
                                        new_support_request.getReference())


376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  @expectedFailure
  def test_Event_getResourceItemList(self):
    """Event_getResourceItemList returns
    category item list with base category in path, just
    like resource.getCategoryChildItemList(base=True) does.
    This is not the expected behaviour because it
    duplicates the base_category in categories_list:
      - resource/resource/my_category_id
    This test checks that relative_url return
    by Event_getResourceItemList are consistent.
    Check also the support of backward compatibility to not break UI
    if resource is already defined with base_category
    in its relative_url value.
    """
    # create resource categories.
    resource = self.portal.portal_categories.resource
    for i in range(3):
      resource.newContent(portal_type='Category',
                          title='Title%s' % i,
                          id=i)
    # create a person like a resource to declare it as a resource
    person = self.portal.person_module.newContent(portal_type='Person')
    # Configure system preference.
    portal_preferences = self.portal.portal_preferences
    system_preference = portal_preferences.getActiveSystemPreference()
    if system_preference is None:
      system_preference = portal_preferences.newContent(
                                              portal_type='System Preference')
      system_preference.enable()
    resource_list = [category.getRelativeUrl() \
                                      for category in resource.contentValues()]
    resource_list.append(person.getRelativeUrl())
    system_preference.setPreferredEventResourceList(resource_list)
    self.tic()
    # Then create One event and play with it
    portal_type = 'Visit'
    module = self.portal.getDefaultModule(portal_type)
    event = module.newContent(portal_type=portal_type,
                              resource='0')
    self.assertTrue(event.getResourceValue() is not None)
    self.assertTrue(event.getResource() in\
                       [item[1] for item in event.Event_getResourceItemList()])
    # Check Backward compatibility support
    # When base_category value is stored in categories_list
    # resource/resource/my_category_id instead of resource/my_category_id
    event.setResource('resource/0')
    self.assertTrue(event.getResourceValue() is not None)
    self.assertTrue(event.getResource() in\
                       [item[1] for item in event.Event_getResourceItemList()])

    # Check that relation with an object which
    # is not a Category works.
    event.setResourceValue(person)
    self.assertTrue(event.getResource() in\
                       [item[1] for item in event.Event_getResourceItemList()])
431

432
class TestCRMMailIngestion(BaseTestCRM):
Yusei Tahara's avatar
Yusei Tahara committed
433
  """Test Mail Ingestion for standalone CRM.
434
  """
435 436
  def getTitle(self):
    return "CRM Mail Ingestion"
437 438

  def getBusinessTemplateList(self):
439
    # Mail Ingestion must work with CRM alone.
440 441 442
    return ('erp5_core_proxy_field_legacy',
            'erp5_full_text_myisam_catalog',
            'erp5_base',
443
            'erp5_ingestion',
Yusei Tahara's avatar
Yusei Tahara committed
444 445
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_crm',
446
            )
447 448

  def afterSetUp(self):
449
    super(TestCRMMailIngestion, self).afterSetUp()
450
    portal = self.portal
451

452
    # create customer organisation and person
453 454 455 456
    portal.organisation_module.newContent(
            id='customer',
            portal_type='Organisation',
            title='Customer')
457
    customer_organisation = portal.organisation_module.customer
458 459 460 461 462
    portal.person_module.newContent(
            id='sender',
            title='Sender',
            subordination_value=customer_organisation,
            default_email_text='sender@customer.com')
463
    # also create the recipients
464 465 466 467 468 469 470 471
    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')
472

473 474
    # make sure customers are available to catalog
    self.tic()
475

Yusei Tahara's avatar
Yusei Tahara committed
476 477 478 479 480 481
  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):
482
    """ingest an email from the mail in data dir named `filename`"""
Yusei Tahara's avatar
Yusei Tahara committed
483 484
    if data is None:
      data=self._readTestData(filename)
485 486
    return self.portal.portal_contributions.newContent(
                    container_path='event_module',
Nicolas Delaby's avatar
Nicolas Delaby committed
487
                    filename='postfix_mail.eml',
488 489 490 491
                    data=data)

  def test_findTypeByName_MailMessage(self):
    # without this, ingestion will not work
492 493 494
    self.assertEquals(
      'Mail Message',
      self.portal.portal_contribution_registry.findPortalTypeName(
Nicolas Delaby's avatar
Nicolas Delaby committed
495
      filename='postfix_mail.eml', content_type='message/rfc822', data='Test'
496
      ))
497

498 499 500 501 502 503 504 505 506 507 508
  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']),
509 510
      # capitalised version
      ('"me@erp5.org,sEnder@CUSTOMER.cOm," <he@ERP5.OrG>', ['person_module/he']),
511 512 513 514 515 516 517 518 519 520 521 522 523
      # 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))

524 525 526 527 528 529
  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())
530 531
    self.assertEquals('text/plain', event.getContentType())
    self.assertEquals('message/rfc822', event._baseGetContentType())
532 533 534 535 536
    # 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)
537

538
  def test_title(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
539
    # title is found automatically, based on the Subject: header in the mail
540 541
    event = self._ingestMail('simple')
    self.assertEquals('Simple Mail Test', event.getTitle())
542
    self.assertEquals('Simple Mail Test', event.getTitleOrId())
543 544 545 546 547 548

  def test_asText(self):
    # asText requires portal_transforms
    event = self._ingestMail('simple')
    self.assertEquals('Hello,\nContent of the mail.\n', str(event.asText()))
 
549 550 551 552 553 554 555 556 557 558 559
  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
    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')
    self.tic()
560 561 562 563
    destination_list = event.getDestinationList()
    destination_list.sort()
    self.assertEquals(['person_module/he', 'person_module/me'],
                      destination_list)
564

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
  def test_clone(self):
    # cloning an event must keep title and text-content
    event = self._ingestMail('simple')
    self.tic()
    self.assertEquals('Simple Mail Test', event.getTitle())
    self.assertEquals('Simple Mail Test', event.getTitleOrId())
    self.assertEquals('Hello,\nContent of the mail.\n', str(event.asText()))
    self.assertEquals('Hello,\nContent of the mail.\n', str(event.getTextContent()))
    self.assertEquals('Mail Message', event.getPortalType())
    self.assertEquals('text/plain', event.getContentType())
    self.assertEquals('message/rfc822', event._baseGetContentType())
    # 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)
    new_event = event.Base_createCloneDocument(batch_mode=1)
    self.tic()
    self.assertEquals('Simple Mail Test', new_event.getTitle())
    self.assertEquals('Simple Mail Test', new_event.getTitleOrId())
    self.assertEquals('Hello,\nContent of the mail.\n', str(new_event.asText()))
    self.assertEquals('Hello,\nContent of the mail.\n', str(new_event.getTextContent()))
    self.assertEquals('Mail Message', new_event.getPortalType())
    self.assertEquals('text/plain', new_event.getContentType())

590 591 592 593
    # check that metadatas read from data are copied on cloned event
    self.assertEquals(new_event.getSourceList(), ['person_module/sender'])
    self.assertEquals(new_event.getDestinationList(), ['person_module/me',
                                                       'person_module/he'])
594

595 596 597 598 599 600 601 602 603 604
  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')
    self.tic()
    event = self._ingestMail('simple')
    self.tic()
    self.assertEquals(None, event.getFollowUp())
Yusei Tahara's avatar
Yusei Tahara committed
605 606 607 608 609 610

  def test_portal_type_determination(self):
    """
    Make sure that ingested email will be correctly converted to
    appropriate portal type by email metadata.
    """
611 612 613 614 615 616
    def getLastCreatedEvent(module):
      object_list = module.contentValues()
      object_list.sort(key=lambda e:e.getCreationDate())
      return object_list[-1]

    portal = self.portal
617
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
618 619
    message.replace_header('subject', 'Visit:Company A')
    data = message.as_string()
620 621 622
    self._ingestMail(data=data)
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
623
    self.assertEqual(document.getPortalType(), 'Visit')
Yusei Tahara's avatar
Yusei Tahara committed
624

625
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
626 627
    message.replace_header('subject', 'Fax:Company B')
    data = message.as_string()
628 629 630
    self._ingestMail(data=data)
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
631
    self.assertEqual(document.getPortalType(), 'Fax Message')
Yusei Tahara's avatar
Yusei Tahara committed
632

633
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
634 635
    message.replace_header('subject', 'TEST:Company B')
    data = message.as_string()
636 637 638
    self._ingestMail(data=data)
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
639
    self.assertEqual(document.getPortalType(), 'Mail Message')
Yusei Tahara's avatar
Yusei Tahara committed
640

641
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
642 643
    message.replace_header('subject', 'visit:Company A')
    data = message.as_string()
644 645 646
    self._ingestMail(data=data)
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
647
    self.assertEqual(document.getPortalType(), 'Visit')
Yusei Tahara's avatar
Yusei Tahara committed
648

649
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
650 651
    message.replace_header('subject', 'phone:Company B')
    data = message.as_string()
652 653 654
    self._ingestMail(data=data)
    self.tic()
    document = portal.event_module[portal.event_module.objectIds()[-1]]
Nicolas Delaby's avatar
Nicolas Delaby committed
655
    self.assertEqual(document.getPortalType(), 'Phone Call')
Yusei Tahara's avatar
Yusei Tahara committed
656

657
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
658 659
    message.replace_header('subject', 'LETTER:Company C')
    data = message.as_string()
660 661 662
    self._ingestMail(data=data)
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
663
    self.assertEqual(document.getPortalType(), 'Letter')
Yusei Tahara's avatar
Yusei Tahara committed
664

665
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
666 667 668
    body = message.get_payload()
    message.set_payload('Visit:%s' % body)
    data = message.as_string()
669 670 671
    self._ingestMail(data=data)
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
672
    self.assertEqual(document.getPortalType(), 'Visit')
Yusei Tahara's avatar
Yusei Tahara committed
673

674
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
675 676 677
    body = message.get_payload()
    message.set_payload('PHONE CALL:%s' % body)
    data = message.as_string()
678 679 680
    self._ingestMail(data=data)
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
681
    self.assertEqual(document.getPortalType(), 'Phone Call')
Yusei Tahara's avatar
Yusei Tahara committed
682

Yusei Tahara's avatar
Yusei Tahara committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696
  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')

    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')
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711

  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')

    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
712

713 714 715 716 717 718 719 720 721 722 723 724 725 726
  def test_encoding(self):
    document = self._ingestMail(filename='encoded')

    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
727

728 729 730 731 732 733 734 735 736 737 738 739 740
  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')
    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))
741
    self.assertEquals('text/html', document.getContentType())
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    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')
    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())
757
    self.assertEquals('text/plain', mixed_document.getContentType())
758

759 760 761 762 763 764 765 766 767 768 769 770 771
  def test_flawed_html_attachment(self):
    portal_type = 'Mail Message'
    event = self.portal.getDefaultModule(portal_type).newContent(portal_type=portal_type)
    # build message content with flwd attachment
    plain_text_message = 'You can read this'
    html_filename = 'broken_html.html'
    file_path = '%s/test_data/%s' % (__file__.rstrip('c').replace(__name__+'.py', ''),
                                     html_filename,)
    html_message = open(file_path, 'r').read()
    message = MIMEMultipart('alternative')
    message.attach(MIMEText('text plain content', _charset='utf-8'))
    part = MIMEBase('text', 'html')
    part.set_payload(html_message)
772
    encoders.encode_base64(part)
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789

    part.add_header('Content-Disposition', 'attachment',
                    filename=html_filename)
    part.add_header('Content-ID', '<%s>' % \
                    ''.join(['%s' % ord(i) for i in html_filename]))
    message.attach(part)
    event.setData(message.as_string())
    self.tic()
    self.assertTrue('html' in event.getTextContent())
    self.assertEquals(len(event.getAttachmentInformationList()), 2)
    self.assertTrue(bool(event.getAttachmentData(1)))
    self.assertTrue(bool(event.getAttachmentData(2)))





790

791 792 793 794 795
## TODO:
##
##  def test_attachements(self):
##    event = self._ingestMail('with_attachements')
##
796

797
class TestCRMMailSend(BaseTestCRM):
Yusei Tahara's avatar
Yusei Tahara committed
798 799
  """Test Mail Sending for CRM
  """
800 801
  def getTitle(self):
    return "CRM Mail Sending"
Yusei Tahara's avatar
Yusei Tahara committed
802 803

  def getBusinessTemplateList(self):
Yusei Tahara's avatar
Yusei Tahara committed
804 805
    # In this test, We will attach some document portal types in event.
    # So we add DMS and Web.
806 807 808 809 810 811 812
    return ('erp5_base',
            'erp5_ingestion',
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_crm',
            'erp5_web',
            'erp5_dms',
            )
Yusei Tahara's avatar
Yusei Tahara committed
813 814

  def afterSetUp(self):
815
    super(TestCRMMailSend, self).afterSetUp()
Yusei Tahara's avatar
Yusei Tahara committed
816 817
    portal = self.portal
    # create customer organisation and person
818 819 820 821
    portal.organisation_module.newContent(
            id='customer',
            portal_type='Organisation',
            title='Customer')
822
    customer_organisation = portal.organisation_module.customer
823 824 825 826 827 828 829 830 831 832 833 834 835 836
    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
837 838 839

    # set preference
    default_pref = self.portal.portal_preferences.default_site_preference
840 841 842
    conversion_dict = _getConversionServerDict()
    default_pref.setPreferredOoodocServerAddress(conversion_dict['hostname'])
    default_pref.setPreferredOoodocServerPortNumber(conversion_dict['port'])
Nicolas Delaby's avatar
Nicolas Delaby committed
843
    default_pref.setPreferredDocumentFilenameRegularExpression(FILENAME_REGULAR_EXPRESSION)
Yusei Tahara's avatar
Yusei Tahara committed
844
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
845 846
    if default_pref.getPreferenceState() == 'disabled':
      default_pref.enable()
Yusei Tahara's avatar
Yusei Tahara committed
847 848 849 850

    # make sure customers are available to catalog
    self.tic()

851 852 853
  def test_MailFromMailMessageEvent(self):
    # passing start_action transition on event workflow will send an email to the
    # person as destination
854
    text_content = 'Mail Content'
855 856 857 858
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTitle('A Mail')
859
    event.setTextContent(text_content)
860 861 862 863 864 865
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
866 867
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
868
    self.assertEquals(event.getTextContent(), text_content)
869
    message = message_from_string(messageText)
870

871
    self.assertEquals('A Mail', decode_header(message['Subject'])[0][0])
872 873 874 875
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
876
    self.assertEqual(text_content, part.get_payload(decode=True))
877

878 879 880 881 882 883 884 885
    #
    # 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')
886
    event.setTextContent(text_content)
887 888 889 890 891 892
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
    self.tic()
    last_message_1, last_message_2 = self.portal.MailHost._message_list[-2:]
    self.assertNotEquals((), last_message_1)
    self.assertNotEquals((), last_message_2)
893 894
    # check last message 1 and last message 2 (the order is random)
    # both should have 'From: Me'
895
    self.assertEquals(['"Me," <me@erp5.org>', '"Me," <me@erp5.org>'],
896 897
                      [x[0] for x in (last_message_1, last_message_2)])
    # one should have 'To: Me' and the other should have 'To: Recipient'
898
    self.assertEquals([['"Me," <me@erp5.org>'], ['"Recipient," <recipient@example.com>']],
899
                      sorted([x[1] for x in (last_message_1, last_message_2)]))
900

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
  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)
    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()
920 921
        if t not in ('Mail Message', 'Document Ingestion Message',
          'Acknowledgement')]:
922 923 924 925 926 927 928 929 930 931 932
      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)

      self.tic()
      # this means no message have been set
      self.assertEquals((), self.portal.MailHost._last_message)

Rafael Monnerat's avatar
Rafael Monnerat committed
933
  def test_MailMarkPosted(self):
934 935 936
    # start_action transition without send_mail variable on event
    # simulation workflow will not send an email even if the portal
    # type is a Mail Message
937 938
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
Rafael Monnerat's avatar
Rafael Monnerat committed
939 940 941 942
      event = self.portal.event_module.newContent(portal_type=ptype)
      event.setSource('person_module/me')
      event.setDestination('person_module/recipient')
      event.setTextContent('Hello !')
943
      self.portal.portal_workflow.doActionFor(event, 'start_action')
Rafael Monnerat's avatar
Rafael Monnerat committed
944 945 946 947 948 949

      self.tic()
      # this means no message have been set
      self.assertEquals((), self.portal.MailHost._last_message)


950
  def test_MailMessageHTML(self):
951 952
    # test sending a mail message edited as HTML (the default with FCKEditor),
    # then the mail should have HTML.
953
    text_content = 'Hello<br />World'
954 955 956
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
957
    event.setContentType('text/html')
958
    event.setTextContent(text_content)
959 960 961
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
    self.tic()
962 963 964 965 966
    # The getTextContent() gets the content from the file data instead the
    # Attribute text_content.
    self.assertEquals(event.text_content, text_content)
    text_content_from_data = '<html><body>Hello<br />World</body></html>'
    self.assertEquals(event.getTextContent(), text_content_from_data)
967 968 969
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
970 971
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
972

973
    message = message_from_string(messageText)
974 975
    part = None
    for i in message.get_payload():
976
      if i.get_content_type()=='text/html':
977
        part = i
978
    self.assertNotEqual(part, None)
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
    self.assertEqual('<html><body>%s</body></html>' % text_content, part.get_payload(decode=True))

  @expectedFailure
  def test_MailMessageHTMLbis(self):
    # test sending a mail message edited as HTML (the default with FCKEditor),
    # then the mail should have HTML
    text_content = 'Hello<br/>World'
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setContentType('text/html')
    event.setTextContent(text_content)
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
    self.tic()
    # This test fails because of known issue for outgoing emails.
    # there is conflict between properties from data
    # and properties from document.
    self.assertEquals(event.getContentType(), 'text/html')
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

  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)
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
1012 1013
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
1014
    
1015
    message = message_from_string(messageText)
1016

1017
    self.assertEquals('Héhé', decode_header(message['Subject'])[0][0])
1018 1019 1020 1021 1022 1023
    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
1024
  def test_MailAttachmentPdf(self):
Yusei Tahara's avatar
Yusei Tahara committed
1025 1026 1027
    """
    Make sure that pdf document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1028
    # Add a document which will be attached.
Yusei Tahara's avatar
Yusei Tahara committed
1029
    # pdf
Nicolas Delaby's avatar
Nicolas Delaby committed
1030 1031 1032
    filename = 'sample_attachment.pdf'
    file_object = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file_object)
Yusei Tahara's avatar
Yusei Tahara committed
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

    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',
1049
               destination='person_module/recipient',
Nicolas Delaby's avatar
Nicolas Delaby committed
1050
               aggregate=document.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
1051 1052 1053 1054 1055
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1056
    message = message_from_string(mail_text)
Yusei Tahara's avatar
Yusei Tahara committed
1057 1058 1059 1060 1061 1062 1063 1064
    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
Nicolas Delaby's avatar
Nicolas Delaby committed
1065
    self.assert_(filename in 
Yusei Tahara's avatar
Yusei Tahara committed
1066 1067 1068
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1069
      if i.get_filename()==filename:
Yusei Tahara's avatar
Yusei Tahara committed
1070
        part = i
Nicolas Delaby's avatar
Nicolas Delaby committed
1071
    self.assertEqual(part.get_payload(decode=True), str(document.getData()))
Yusei Tahara's avatar
Yusei Tahara committed
1072 1073

  def test_MailAttachmentText(self):
Yusei Tahara's avatar
Yusei Tahara committed
1074 1075 1076
    """
    Make sure that text document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1077
    # Add a document which will be attached.
Nicolas Delaby's avatar
Nicolas Delaby committed
1078 1079 1080
    filename = 'sample_attachment.odt'
    file_object = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file_object)
Yusei Tahara's avatar
Yusei Tahara committed
1081 1082 1083 1084

    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1085
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
Yusei Tahara's avatar
Yusei Tahara committed
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
                                                    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',
1096
               destination='person_module/recipient',
Nicolas Delaby's avatar
Nicolas Delaby committed
1097
               aggregate=document.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
1098 1099 1100 1101 1102
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1103
    message = message_from_string(mail_text)
Yusei Tahara's avatar
Yusei Tahara committed
1104 1105 1106 1107 1108 1109 1110
    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
1111
    # odt
Nicolas Delaby's avatar
Nicolas Delaby committed
1112
    self.assert_(filename in 
Yusei Tahara's avatar
Yusei Tahara committed
1113 1114 1115
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1116
      if i.get_filename() == filename:
Yusei Tahara's avatar
Yusei Tahara committed
1117 1118 1119
        part = i
    self.assert_(len(part.get_payload(decode=True))>0)

Yusei Tahara's avatar
Yusei Tahara committed
1120
  def test_MailAttachmentFile(self):
Yusei Tahara's avatar
Yusei Tahara committed
1121 1122 1123
    """
    Make sure that file document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1124
    # Add a document which will be attached.
Nicolas Delaby's avatar
Nicolas Delaby committed
1125 1126 1127
    filename = 'sample_attachment.zip'
    file_object = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file_object)
Yusei Tahara's avatar
Yusei Tahara committed
1128 1129 1130
    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1131
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
Yusei Tahara's avatar
Yusei Tahara committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
                                                    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',
1142
               destination='person_module/recipient',
Nicolas Delaby's avatar
Nicolas Delaby committed
1143
               aggregate=document.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
1144 1145 1146 1147
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)
    # Check mail text.
1148
    message = message_from_string(mail_text)
Yusei Tahara's avatar
Yusei Tahara committed
1149 1150 1151 1152 1153 1154 1155 1156
    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
Nicolas Delaby's avatar
Nicolas Delaby committed
1157
    self.assert_(filename in 
Yusei Tahara's avatar
Yusei Tahara committed
1158 1159 1160
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1161
      if i.get_filename() == filename:
Yusei Tahara's avatar
Yusei Tahara committed
1162 1163 1164 1165
        part = i
    self.assert_(len(part.get_payload(decode=True))>0)

  def test_MailAttachmentImage(self):
Yusei Tahara's avatar
Yusei Tahara committed
1166 1167 1168
    """
    Make sure that image document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1169
    # Add a document which will be attached.
Nicolas Delaby's avatar
Nicolas Delaby committed
1170 1171 1172
    filename = 'sample_attachment.gif'
    file_object = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file_object)
Yusei Tahara's avatar
Yusei Tahara committed
1173 1174 1175 1176

    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1177
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
Yusei Tahara's avatar
Yusei Tahara committed
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
                                                    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',
1188
               destination='person_module/recipient',
Nicolas Delaby's avatar
Nicolas Delaby committed
1189
               aggregate=document.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
1190 1191 1192 1193 1194
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1195
    message = message_from_string(mail_text)
Yusei Tahara's avatar
Yusei Tahara committed
1196 1197 1198 1199 1200 1201 1202 1203
    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
Nicolas Delaby's avatar
Nicolas Delaby committed
1204
    self.assert_(filename in 
Yusei Tahara's avatar
Yusei Tahara committed
1205 1206 1207
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1208
      if i.get_filename() == filename:
Yusei Tahara's avatar
Yusei Tahara committed
1209
        part = i
Nicolas Delaby's avatar
Nicolas Delaby committed
1210
    self.assertEqual(part.get_payload(decode=True), str(document.getData()))
Yusei Tahara's avatar
Yusei Tahara committed
1211 1212

  def test_MailAttachmentWebPage(self):
Yusei Tahara's avatar
Yusei Tahara committed
1213 1214 1215
    """
    Make sure that webpage document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1216
    # Add a document which will be attached.
Nicolas Delaby's avatar
Nicolas Delaby committed
1217 1218 1219 1220
    filename = 'sample_attachment.html'
    document = self.portal.portal_contributions.newContent(
                          data='<html><body>Hello world!</body></html>',
                          filename=filename)
Yusei Tahara's avatar
Yusei Tahara committed
1221 1222 1223
    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1224
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
Yusei Tahara's avatar
Yusei Tahara committed
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
                                                    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',
1235
               destination='person_module/recipient',
Nicolas Delaby's avatar
Nicolas Delaby committed
1236
               aggregate=document.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
1237 1238 1239 1240 1241
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1242
    message = message_from_string(mail_text)
Yusei Tahara's avatar
Yusei Tahara committed
1243 1244 1245 1246 1247 1248 1249 1250
    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
Nicolas Delaby's avatar
Nicolas Delaby committed
1251
    self.assert_(filename in 
Yusei Tahara's avatar
Yusei Tahara committed
1252 1253 1254
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1255
      if i.get_filename() == filename:
Yusei Tahara's avatar
Yusei Tahara committed
1256
        part = i
1257
    self.assertEqual(part.get_payload(decode=True),
Nicolas Delaby's avatar
Nicolas Delaby committed
1258
                     str(document.getTextContent()))
1259
    self.assertEqual(part.get_content_type(), 'text/html')
Yusei Tahara's avatar
Yusei Tahara committed
1260

Aurel's avatar
Aurel committed
1261 1262 1263 1264 1265
  def test_MailRespond(self):
    """
    Test we can answer an incoming event and quote it
    """
    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1266
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
Aurel's avatar
Aurel committed
1267 1268 1269 1270 1271 1272
                                                    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
1273

Aurel's avatar
Aurel committed
1274 1275 1276
    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1277
               destination='person_module/recipient',
Aurel's avatar
Aurel committed
1278 1279
               text_content='This is an advertisement mail.')
    first_event_id = event.getId()
1280 1281 1282 1283 1284
    event.Event_createResponse(response_event_portal_type='Mail Message',
                               response_event_title='Answer',
                               response_event_text_content='> This is an advertisement mail.',
                               response_workflow_action='send',
                               )
Aurel's avatar
Aurel committed
1285

1286
    self.assertEqual(event.getSimulationState(), "stopped")
1287

Aurel's avatar
Aurel committed
1288 1289 1290 1291 1292 1293 1294
    # 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
1295
    self.assertEqual(answer_event.getSimulationState(), "started")
Aurel's avatar
Aurel committed
1296 1297
    self.assertEqual(answer_event.getCausality(), event.getRelativeUrl())
    self.assertEqual(answer_event.getDestination(), 'person_module/me')
1298
    self.assertEqual(answer_event.getSource(), 'person_module/recipient')
Aurel's avatar
Aurel committed
1299
    self.assertEqual(answer_event.getTextContent(), '> This is an advertisement mail.')
1300 1301
    self.assertEqual(answer_event.getFollowUpValue(), ticket)
    self.assert_(answer_event.getData() is not None)
Yusei Tahara's avatar
Yusei Tahara committed
1302

1303 1304 1305 1306 1307 1308
  def test_MailAttachmentFileWithoutDMS(self):
    """
    Make sure that file document is correctly attached in email
    """
    # Add a document on a person which will be attached.

Nicolas Delaby's avatar
Nicolas Delaby committed
1309
    def add_document(filename, container, portal_type):
1310
      f = makeFileUpload(filename)
Nicolas Delaby's avatar
Nicolas Delaby committed
1311
      document = container.newContent(portal_type=portal_type)
1312 1313
      document.edit(file=f, reference=filename)
      return document
Nicolas Delaby's avatar
Nicolas Delaby committed
1314
    filename = 'sample_attachment.txt'
1315
    # txt
Nicolas Delaby's avatar
Nicolas Delaby committed
1316
    document_txt = add_document(filename,
1317
                                self.portal.person_module['me'], 'Embedded File')
1318 1319 1320 1321

    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1322
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
                                                    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',
1333
               destination='person_module/recipient',
1334 1335 1336 1337 1338 1339
               aggregate=document_txt.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1340
    message = message_from_string(mail_text)
1341 1342 1343 1344
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
1345
        break
1346 1347 1348 1349
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # txt
Nicolas Delaby's avatar
Nicolas Delaby committed
1350
    self.assert_(filename in 
1351 1352 1353
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1354
      if i.get_filename() == filename:
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
        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.

Nicolas Delaby's avatar
Nicolas Delaby committed
1366
    def add_document(filename, container, portal_type):
1367
      f = makeFileUpload(filename)
Nicolas Delaby's avatar
Nicolas Delaby committed
1368
      document = container.newContent(portal_type=portal_type)
1369 1370 1371 1372
      document.edit(file=f, reference=filename)
      return document

    # gif
Nicolas Delaby's avatar
Nicolas Delaby committed
1373 1374
    filename = 'sample_attachment.gif'
    document_gif = add_document(filename,
1375
                                self.portal.person_module['me'], 'Embedded File')
1376 1377 1378 1379

    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1380
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
                                                    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',
1391
               destination='person_module/recipient',
1392 1393 1394 1395 1396 1397
               aggregate=document_gif.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1398
    message = message_from_string(mail_text)
1399 1400 1401 1402 1403 1404 1405 1406
    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
Nicolas Delaby's avatar
Nicolas Delaby committed
1407
    self.assert_(filename in 
1408 1409 1410
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1411
      if i.get_filename() == filename:
1412 1413 1414
        part = i
    self.assertEqual(part.get_payload(decode=True), str(document_gif.getData()))

1415 1416 1417 1418 1419
  def test_cloneEvent(self):
    """
      All events uses after script and interaciton
      workflow add a test for clone
    """
1420 1421
    # XXX in the case of title, getTitle ignores the title attribute,
    # if any data is stored. In the case of text_content, getTextContent
1422
    # respects the behaviour is the same as Title.
1423 1424 1425 1426 1427
    portal_type = 'Mail Message'
    dummy_title = 'Dummy title'
    real_title = 'Real Title'
    dummy_content = 'Dummy content'
    real_content = 'Real content'
1428
    event = self.portal.event_module.newContent(portal_type=portal_type,
1429
                                                title=dummy_title,
1430
                                                text_content=dummy_content,)
1431 1432
    self.assertFalse(event.hasFile(), '%r has a file' % (event,))
    self.assertEquals(event.getTitle(), dummy_title)
1433
    self.assertEquals(event.getTextContent(), dummy_content)
1434

1435
    event.setData('Subject: %s\r\n\r\n%s' % (real_title, real_content))
1436 1437 1438
    self.assertTrue(event.hasFile(), '%r has no file' % (event,))
    self.assertEquals(event.getTitle(), real_title)
    self.assertEquals(event.getTextContent(), real_content)
1439

1440 1441
    self.stepTic()
    new_event = event.Base_createCloneDocument(batch_mode=1)
1442 1443 1444 1445
    self.assertFalse(new_event.hasFile(), '%r has a file' % (new_event,))
    self.assertEquals(new_event.getData(), '')
    self.assertEquals(new_event.getTitle(), real_title)
    self.assertEquals(new_event.getTextContent(), real_content)
1446

1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
  def test_cloneTicketAndEventList(self):
    """
      All events uses after script and interaciton
      workflow add a test for clone
    """
    portal = self.portal
    event_list = []
    destination_list = []
    for i in range (0,100):
      person = portal.person_module.newContent(
                 portal_type='Person',
                 title = 'Person %s' %i)
      destination_list.append(person)
    campaing = portal.campaign_module.newContent(
                 portal_type='Campaign', 
                 reference = 'Test')
    for i in range(0,3):
      event = portal.event_module.newContent(
                portal_type='Mail Message',
                title = 'Mail %s' %i, 
                follow_up = campaing.getRelativeUrl())
      event.setDestinationList([x.getRelativeUrl() for x in destination_list])
      event_list.append(event)
    self.stepTic()
    
    # use Ticket_cloneTicketAndEventList
    campaing.Ticket_cloneTicketAndEventList()
    self.stepTic()
    cloned_campaign = [x for x in portal.campaign_module.objectValues() if x!=campaing][0]
    cloned_event_list = [x for x in portal.event_module.objectValues() if x.getFollowUpValue()==cloned_campaign]
    self.assertEqual(campaing.getTitle(), cloned_campaign.getTitle())
    self.assertEqual(campaing.getReference(), cloned_campaign.getReference())

    for i in range(0,3):
      self.assertSameSet(event_list[i].getDestinationValueList(), cloned_event_list[i].getDestinationValueList())


Nicolas Delaby's avatar
Nicolas Delaby committed
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
  def test_Base_addEvent(self):
    """Check Base_addEvent script with a logged in user.
    """
    # create categories.
    resource = self.portal.portal_categories.resource
    for i in range(3):
      resource.newContent(portal_type='Category',
                          title='Title%s' % i,
                          id=i)
    self.portal.portal_categories.function.newContent(portal_type='Category',
                                                      id='crm_agent')
    # create user and configure security settings
    portal_type_list = self.portal.getPortalEventTypeList()\
                       + self.portal.getPortalEntityTypeList()\
                       + ('Event Module',)
    for portal_type in portal_type_list:
      portal_type_object = getattr(self.portal.portal_types, portal_type)
      portal_type_object.newContent(id='manager_role',
                                    portal_type='Role Information',
                                    role_name_list=('Manager',),
                                    role_category_list='function/crm_agent')
      portal_type_object.updateRoleMapping()
    user = self.createSimpleUser('Agent', 'crm_agent', 'crm_agent')
    self.tic()
    try:
      # create entites
      organisation_portal_type = 'Organisation'
      person_portal_type = 'Person'
      my_company = self.portal.getDefaultModule(organisation_portal_type)\
                              .newContent(portal_type=organisation_portal_type,
                                          title='Software provider')
      organisation = self.portal.getDefaultModule(organisation_portal_type)\
                              .newContent(portal_type=organisation_portal_type,
                                          title='Soap Service Express')
      person = self.portal.getDefaultModule(person_portal_type).newContent(
                              portal_type=person_portal_type,
                              first_name='John',
                              last_name='Doe',
                              default_email_text='john.doe@example.com',
                              default_career_subordination_value=organisation)
      another_person = self.portal.getDefaultModule(person_portal_type)\
                  .newContent(portal_type=person_portal_type,
                              first_name='Jane',
                              last_name='Doe',
                              default_email_text='jane.doe@example.com',
                              default_career_subordination_value=organisation)
      user.setDefaultCareerSubordinationValue(my_company)
      # log in user
      self.login('crm_agent')

      ### Incoming on Person ###
      # Submit the dialog on person
      title = 'Incoming email'
1537
      direction = 'incoming'
Nicolas Delaby's avatar
Nicolas Delaby committed
1538
      portal_type = 'Note'
Nicolas Delaby's avatar
Nicolas Delaby committed
1539
      resource = resource['1'].getCategoryRelativeUrl()
Nicolas Delaby's avatar
Nicolas Delaby committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
      person.Base_addEvent(title, direction, portal_type, resource)

      # Index Event
      self.tic()

      # check created Event
      event = person.getSourceRelatedValue()
      self.assertEquals(event.getTitle(), title)
      self.assertEquals(event.getResource(), resource)
      self.assertTrue(event.hasStartDate())
      self.assertEquals(event.getSource(), person.getRelativeUrl())
      self.assertEquals(event.getSourceSection(),
                        organisation.getRelativeUrl())
      self.assertEquals(event.getDestination(), user.getRelativeUrl())
      self.assertEquals(event.getDestinationSection(), user.getSubordination())

      ### Outgoing on Person ###
      # Check another direction
      title = 'Outgoing email'
1559
      direction = 'outgoing'
Nicolas Delaby's avatar
Nicolas Delaby committed
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
      another_person.Base_addEvent(title, direction, portal_type, resource)

      # Index Event
      self.tic()

      # check created Event
      event = another_person.getDestinationRelatedValue()
      self.assertEquals(event.getTitle(), title)
      self.assertEquals(event.getResource(), resource)
      self.assertTrue(event.hasStartDate())
      self.assertEquals(event.getDestination(),
                        another_person.getRelativeUrl())
      self.assertEquals(event.getDestinationSection(),
                        organisation.getRelativeUrl())
      self.assertEquals(event.getSource(), user.getRelativeUrl())
      self.assertEquals(event.getSourceSection(), user.getSubordination())

      ### Outgoing on Organisation ###
      # check on Organisation
      event = organisation.Base_addEvent(title, direction,
                                         portal_type, resource)

      # Index Event
      self.tic()

      # check created Event
      event = organisation.getDestinationSectionRelatedValue()
      self.assertEquals(event.getTitle(), title)
      self.assertEquals(event.getResource(), resource)
      self.assertTrue(event.hasStartDate())
      self.assertEquals(event.getDestination(),
                        organisation.getRelativeUrl())
      self.assertEquals(event.getDestinationSection(),
                        organisation.getRelativeUrl())
      self.assertEquals(event.getSource(), user.getRelativeUrl())
      self.assertEquals(event.getSourceSection(), user.getSubordination())

      ### Outgoing on Career ###
      # Now check Base_addEvent on any document (follow_up)
      career = person.default_career
      career.Base_addEvent(title, direction, portal_type, resource)

      # Index Event
      self.tic()

      # check created Event
      event = career.getFollowUpRelatedValue()
      self.assertEquals(event.getTitle(), title)
      self.assertEquals(event.getResource(), resource)
      self.assertTrue(event.hasStartDate())
      self.assertEquals(event.getSource(), user.getRelativeUrl())
      self.assertEquals(event.getSourceSection(), user.getSubordination())
    finally:
      # clean up created roles on portal_types
      for portal_type in portal_type_list:
        portal_type_object = getattr(self.portal.portal_types, portal_type)
        portal_type_object._delObject('manager_role')
        portal_type_object.updateRoleMapping()
      self.tic()
1619

1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
  def test_MailMessage_Event_send_generate_activity_list(self):
    """
      Check that after post a Mail Message, the activities are generated
      correctly
    """
    person = self.portal.person_module.newContent(portal_type="Person")
    person.edit(default_email_text="test@test.com", title="test%s" % person.getId())
    self.stepTic()
    mail_message = self.portal.event_module.newContent(portal_type="Mail Message")
    relative_url_list = [z.getRelativeUrl() for z in self.portal.person_module.searchFolder()]
    mail_message.setDestinationList(relative_url_list)
    mail_message.setSource(relative_url_list[0])
    mail_text_content = "Body Text Content"
    mail_message.setTextContent(mail_text_content)
    self.portal.portal_workflow.doActionFor(mail_message, "start_action")
    self.stepTic()
    mail_message.Event_send(packet_size=2)
1637
    self.commit()
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
    portal_activities = self.portal.portal_activities
    message_list = [i for i in portal_activities.getMessageList() \
                    if i.kw.has_key("event_relative_url")]
    try:
      self.assertEquals(2, len(message_list))
    finally:
      self.stepTic()
    last_message = self.portal.MailHost._last_message
    self.assertTrue(mail_text_content in last_message[-1])
    message = message_from_string(last_message[-1])
    last_message_date = DateTime(message.get("Date"))
    self.assertTrue(last_message_date.isCurrentDay())

  def test_MailMessage_Event_send_simple_case(self):
    """
      Check that the script Event_send send one email passing all parameters directly
      from_url, to_url, reply_url, subject, body, attachment_format, attachment_list
    """
    mail_message = self.portal.event_module.newContent(portal_type="Mail Message")
    self.stepTic()
    mail_message.Event_send(from_url='FG ER <eee@eee.com>',
                            to_url='Expert User <expert@in24.test>',
                            subject="Simple Case",
                            body="Body Simple Case",
                            attachment_list=[])
    self.stepTic()
    last_message = self.portal.MailHost._last_message[-1]
    self.assertTrue("Body Simple Case" in last_message)


1668 1669
def test_suite():
  suite = unittest.TestSuite()
1670
  suite.addTest(unittest.makeSuite(TestCRM))
1671
  suite.addTest(unittest.makeSuite(TestCRMMailIngestion))
Yusei Tahara's avatar
Yusei Tahara committed
1672
  suite.addTest(unittest.makeSuite(TestCRMMailSend))
1673
  return suite