testCRM.py 67 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
import transaction

33
from Products.CMFCore.WorkflowCore import WorkflowException
34
from Products.ERP5Type.tests.utils import FileUpload
35 36
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase,\
                                                       _getConversionServerDict
Nicolas Delaby's avatar
Nicolas Delaby committed
37
from Products.ERP5OOo.tests.testIngestion import FILENAME_REGULAR_EXPRESSION
Yusei Tahara's avatar
Yusei Tahara committed
38
from Products.ERP5OOo.tests.testIngestion import REFERENCE_REGULAR_EXPRESSION
39
from Products.ERP5Type.tests.backportUnittest import expectedFailure
40 41 42 43 44
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
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 71 72

  def beforeTearDown(self):
    transaction.abort()
    # clear modules if necessary
73
    for module_name in clear_module_name_list:
74
      module = self.portal.unrestrictedTraverse(module_name)
75 76
      module.manage_delObjects(list(module.objectIds()))

77
    self.stepTic()
78 79 80
    super(BaseTestCRM, self).beforeTearDown()

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

84
  def getBusinessTemplateList(self):
85 86
    return ('erp5_base',
            'erp5_crm',)
87

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

      event.receive()
      event.respond()

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

103
      transaction.commit()
104 105 106 107 108 109 110
      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')

111
      transaction.commit()
112 113 114 115 116 117 118 119 120
      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')
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 148
      ticket.Ticket_newEvent(direction='incoming',
                             portal_type=ptype,
                             title='Incoming Title',
                             description='New Desc')
      transaction.commit()
      self.tic()
      new_event = ticket.getFollowUpRelatedValueList()[0]
149 150 151
      self.assertEquals('new', new_event.getSimulationState())

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

162 163 164 165 166 167 168 169 170
  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
171

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

194
    transaction.commit()
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    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()])
218
    transaction.commit()
219 220 221 222 223 224 225 226 227 228
    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')

229
    transaction.commit()
230 231 232 233 234 235 236 237 238 239 240 241 242
    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'))

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 281 282 283 284 285 286
  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())

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

    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.
297 298 299
    """
    portal_workflow = self.portal.portal_workflow

300
    event_type_list = [x for x in self.portal.getPortalEventTypeList() \
301
                       if x not in  ['Site Message', 'Acknowledgement']]
302

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

319
    # if create_event option is true, it create a new event.
320
    for portal_type in event_type_list:
321 322 323 324 325
      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)
326
      transaction.commit()
327 328 329 330
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action', create_event=1)
331
      transaction.commit()
332 333 334 335 336
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)
      new_event = event.getCausalityRelatedValue()
      self.assertEqual(new_event.getFollowUp(), ticket_url)

337 338
    # if quote_original_message option is true, the new event content will be
    # the current event message quoted.
339
    for portal_type in event_type_list:
340 341 342 343 344 345 346
      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',
347
                                                  content_type='text/plain')
348
      transaction.commit()
349 350 351 352 353 354
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action',
                                  create_event=1,
                                  quote_original_message=1)
355
      transaction.commit()
356 357 358 359
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)
      new_event = event.getCausalityRelatedValue()
      self.assertEqual(new_event.getFollowUp(), ticket_url)
360
      self.assertEqual(new_event.getContentType(), 'text/plain')
361 362 363
      self.assertEqual(new_event.getTextContent(), '> Event Content')
      self.assertEqual(new_event.getTitle(), 'Re: Event Title')

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  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())


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 431 432 433 434 435 436 437 438 439 440 441 442
  @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)
    transaction.commit()
    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()])
443

444
class TestCRMMailIngestion(BaseTestCRM):
Yusei Tahara's avatar
Yusei Tahara committed
445
  """Test Mail Ingestion for standalone CRM.
446
  """
447 448
  def getTitle(self):
    return "CRM Mail Ingestion"
449 450

  def getBusinessTemplateList(self):
451 452 453
    # Mail Ingestion must work with CRM alone.
    return ('erp5_base',
            'erp5_ingestion',
Yusei Tahara's avatar
Yusei Tahara committed
454 455
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_crm',
456
            )
457 458

  def afterSetUp(self):
459
    super(TestCRMMailIngestion, self).afterSetUp()
460
    portal = self.portal
461

462
    # create customer organisation and person
463 464 465 466
    portal.organisation_module.newContent(
            id='customer',
            portal_type='Organisation',
            title='Customer')
467
    customer_organisation = portal.organisation_module.customer
468 469 470 471 472
    portal.person_module.newContent(
            id='sender',
            title='Sender',
            subordination_value=customer_organisation,
            default_email_text='sender@customer.com')
473
    # also create the recipients
474 475 476 477 478 479 480 481
    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')
482

483
    # make sure customers are available to catalog
484
    transaction.commit()
485
    self.tic()
486

Yusei Tahara's avatar
Yusei Tahara committed
487 488 489 490 491 492
  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):
493
    """ingest an email from the mail in data dir named `filename`"""
Yusei Tahara's avatar
Yusei Tahara committed
494 495
    if data is None:
      data=self._readTestData(filename)
496 497
    return self.portal.portal_contributions.newContent(
                    container_path='event_module',
Nicolas Delaby's avatar
Nicolas Delaby committed
498
                    filename='postfix_mail.eml',
499 500 501 502
                    data=data)

  def test_findTypeByName_MailMessage(self):
    # without this, ingestion will not work
503 504 505
    self.assertEquals(
      'Mail Message',
      self.portal.portal_contribution_registry.findPortalTypeName(
Nicolas Delaby's avatar
Nicolas Delaby committed
506
      filename='postfix_mail.eml', content_type='message/rfc822', data='Test'
507
      ))
508

509 510 511 512 513 514 515 516 517 518 519
  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']),
520 521
      # capitalised version
      ('"me@erp5.org,sEnder@CUSTOMER.cOm," <he@ERP5.OrG>', ['person_module/he']),
522 523 524 525 526 527 528 529 530 531 532 533 534
      # 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))

535 536 537 538 539 540
  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())
541 542
    self.assertEquals('text/plain', event.getContentType())
    self.assertEquals('message/rfc822', event._baseGetContentType())
543 544 545 546 547
    # 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)
548

549
  def test_title(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
550
    # title is found automatically, based on the Subject: header in the mail
551 552
    event = self._ingestMail('simple')
    self.assertEquals('Simple Mail Test', event.getTitle())
553
    self.assertEquals('Simple Mail Test', event.getTitleOrId())
554 555 556 557 558 559

  def test_asText(self):
    # asText requires portal_transforms
    event = self._ingestMail('simple')
    self.assertEquals('Hello,\nContent of the mail.\n', str(event.asText()))
 
560 561 562 563
  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
564
    transaction.commit()
565 566 567 568 569 570
    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')
571
    transaction.commit()
572
    self.tic()
573 574 575 576
    destination_list = event.getDestinationList()
    destination_list.sort()
    self.assertEquals(['person_module/he', 'person_module/me'],
                      destination_list)
577

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
  def test_clone(self):
    # cloning an event must keep title and text-content
    event = self._ingestMail('simple')
    transaction.commit()
    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)
    transaction.commit()
    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())

605 606 607 608
    # 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'])
609

610 611 612 613 614 615
  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')
616
    transaction.commit()
617 618
    self.tic()
    event = self._ingestMail('simple')
619
    transaction.commit()
620 621
    self.tic()
    self.assertEquals(None, event.getFollowUp())
Yusei Tahara's avatar
Yusei Tahara committed
622 623 624 625 626 627

  def test_portal_type_determination(self):
    """
    Make sure that ingested email will be correctly converted to
    appropriate portal type by email metadata.
    """
628 629 630 631 632 633
    def getLastCreatedEvent(module):
      object_list = module.contentValues()
      object_list.sort(key=lambda e:e.getCreationDate())
      return object_list[-1]

    portal = self.portal
634
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
635 636
    message.replace_header('subject', 'Visit:Company A')
    data = message.as_string()
637 638 639 640
    self._ingestMail(data=data)
    transaction.commit()
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
641
    self.assertEqual(document.getPortalType(), 'Visit')
Yusei Tahara's avatar
Yusei Tahara committed
642

643
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
644 645
    message.replace_header('subject', 'Fax:Company B')
    data = message.as_string()
646 647 648 649
    self._ingestMail(data=data)
    transaction.commit()
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
650
    self.assertEqual(document.getPortalType(), 'Fax Message')
Yusei Tahara's avatar
Yusei Tahara committed
651

652
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
653 654
    message.replace_header('subject', 'TEST:Company B')
    data = message.as_string()
655 656 657 658
    self._ingestMail(data=data)
    transaction.commit()
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
659
    self.assertEqual(document.getPortalType(), 'Mail Message')
Yusei Tahara's avatar
Yusei Tahara committed
660

661
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
662 663
    message.replace_header('subject', 'visit:Company A')
    data = message.as_string()
664 665 666 667
    self._ingestMail(data=data)
    transaction.commit()
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
668
    self.assertEqual(document.getPortalType(), 'Visit')
Yusei Tahara's avatar
Yusei Tahara committed
669

670
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
671 672
    message.replace_header('subject', 'phone:Company B')
    data = message.as_string()
673 674 675 676
    self._ingestMail(data=data)
    transaction.commit()
    self.tic()
    document = portal.event_module[portal.event_module.objectIds()[-1]]
Nicolas Delaby's avatar
Nicolas Delaby committed
677
    self.assertEqual(document.getPortalType(), 'Phone Call')
Yusei Tahara's avatar
Yusei Tahara committed
678

679
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
680 681
    message.replace_header('subject', 'LETTER:Company C')
    data = message.as_string()
682 683 684 685
    self._ingestMail(data=data)
    transaction.commit()
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
686
    self.assertEqual(document.getPortalType(), 'Letter')
Yusei Tahara's avatar
Yusei Tahara committed
687

688
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
689 690 691
    body = message.get_payload()
    message.set_payload('Visit:%s' % body)
    data = message.as_string()
692 693 694 695
    self._ingestMail(data=data)
    transaction.commit()
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
696
    self.assertEqual(document.getPortalType(), 'Visit')
Yusei Tahara's avatar
Yusei Tahara committed
697

698
    message = message_from_string(self._readTestData('simple'))
Yusei Tahara's avatar
Yusei Tahara committed
699 700 701
    body = message.get_payload()
    message.set_payload('PHONE CALL:%s' % body)
    data = message.as_string()
702 703 704 705
    self._ingestMail(data=data)
    transaction.commit()
    self.tic()
    document = getLastCreatedEvent(portal.event_module)
Nicolas Delaby's avatar
Nicolas Delaby committed
706
    self.assertEqual(document.getPortalType(), 'Phone Call')
Yusei Tahara's avatar
Yusei Tahara committed
707

Yusei Tahara's avatar
Yusei Tahara committed
708 709 710 711 712 713 714 715
  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')

716
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
717 718 719 720 721 722
    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')
723 724 725 726 727 728 729 730 731

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

732
    transaction.commit()
733 734 735 736 737 738
    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
739

740 741 742
  def test_encoding(self):
    document = self._ingestMail(filename='encoded')

743
    transaction.commit()
744 745 746 747 748 749 750 751 752 753 754
    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
755

756 757 758 759 760 761 762 763 764 765 766 767 768 769
  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))
770
    self.assertEquals('text/html', document.getContentType())
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
    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())
787
    self.assertEquals('text/plain', mixed_document.getContentType())
788

789 790 791 792 793 794 795 796 797 798 799 800 801
  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)
802
    encoders.encode_base64(part)
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820

    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())
    transaction.commit()
    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)))





821

822 823 824 825 826
## TODO:
##
##  def test_attachements(self):
##    event = self._ingestMail('with_attachements')
##
827

828
class TestCRMMailSend(BaseTestCRM):
Yusei Tahara's avatar
Yusei Tahara committed
829 830
  """Test Mail Sending for CRM
  """
831 832
  def getTitle(self):
    return "CRM Mail Sending"
Yusei Tahara's avatar
Yusei Tahara committed
833 834

  def getBusinessTemplateList(self):
Yusei Tahara's avatar
Yusei Tahara committed
835 836
    # In this test, We will attach some document portal types in event.
    # So we add DMS and Web.
837 838 839 840 841 842 843
    return ('erp5_base',
            'erp5_ingestion',
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_crm',
            'erp5_web',
            'erp5_dms',
            )
Yusei Tahara's avatar
Yusei Tahara committed
844 845

  def afterSetUp(self):
846
    super(TestCRMMailSend, self).afterSetUp()
Yusei Tahara's avatar
Yusei Tahara committed
847 848 849
    portal = self.portal

    # create customer organisation and person
850 851 852 853
    portal.organisation_module.newContent(
            id='customer',
            portal_type='Organisation',
            title='Customer')
854
    customer_organisation = portal.organisation_module.customer
855 856 857 858 859 860 861 862 863 864 865 866 867 868
    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
869 870 871

    # set preference
    default_pref = self.portal.portal_preferences.default_site_preference
872 873 874
    conversion_dict = _getConversionServerDict()
    default_pref.setPreferredOoodocServerAddress(conversion_dict['hostname'])
    default_pref.setPreferredOoodocServerPortNumber(conversion_dict['port'])
Nicolas Delaby's avatar
Nicolas Delaby committed
875
    default_pref.setPreferredDocumentFilenameRegularExpression(FILENAME_REGULAR_EXPRESSION)
Yusei Tahara's avatar
Yusei Tahara committed
876
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
877 878
    if default_pref.getPreferenceState() == 'disabled':
      default_pref.enable()
Yusei Tahara's avatar
Yusei Tahara committed
879 880

    # make sure customers are available to catalog
881
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
882 883
    self.tic()

884 885 886
  def test_MailFromMailMessageEvent(self):
    # passing start_action transition on event workflow will send an email to the
    # person as destination
887
    text_content = 'Mail Content'
888 889 890 891
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTitle('A Mail')
892
    event.setTextContent(text_content)
893 894
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
895
    transaction.commit()
896 897 898 899
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
900 901
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
902
    self.assertEquals(event.getTextContent(), text_content)
903
    message = message_from_string(messageText)
904

905
    self.assertEquals('A Mail', decode_header(message['Subject'])[0][0])
906 907 908 909
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
910
    self.assertEqual(text_content, part.get_payload(decode=True))
911

912 913 914 915 916 917 918 919
    #
    # 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')
920
    event.setTextContent(text_content)
921 922
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
923
    transaction.commit()
924 925 926 927
    self.tic()
    last_message_1, last_message_2 = self.portal.MailHost._message_list[-2:]
    self.assertNotEquals((), last_message_1)
    self.assertNotEquals((), last_message_2)
928 929
    # check last message 1 and last message 2 (the order is random)
    # both should have 'From: Me'
930
    self.assertEquals(['"Me," <me@erp5.org>', '"Me," <me@erp5.org>'],
931 932
                      [x[0] for x in (last_message_1, last_message_2)])
    # one should have 'To: Me' and the other should have 'To: Recipient'
933
    self.assertEquals([['"Me," <me@erp5.org>'], ['"Recipient," <recipient@example.com>']],
934
                      sorted([x[1] for x in (last_message_1, last_message_2)]))
935

936 937 938 939 940 941 942 943 944 945 946
  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)
947
    transaction.commit()
948 949 950 951 952 953 954 955
    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()
956 957
        if t not in ('Mail Message', 'Document Ingestion Message',
          'Acknowledgement')]:
958 959 960 961 962 963 964
      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)

965
      transaction.commit()
966 967 968 969
      self.tic()
      # this means no message have been set
      self.assertEquals((), self.portal.MailHost._last_message)

Rafael Monnerat's avatar
Rafael Monnerat committed
970 971 972
  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
973 974
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
Rafael Monnerat's avatar
Rafael Monnerat committed
975 976 977 978 979 980 981
      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')

982
      transaction.commit()
Rafael Monnerat's avatar
Rafael Monnerat committed
983 984 985 986 987
      self.tic()
      # this means no message have been set
      self.assertEquals((), self.portal.MailHost._last_message)


988
  def test_MailMessageHTML(self):
989 990
    # test sending a mail message edited as HTML (the default with FCKEditor),
    # then the mail should have HTML.
991
    text_content = 'Hello<br />World'
992 993 994
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
995
    event.setContentType('text/html')
996
    event.setTextContent(text_content)
997 998
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
999
    transaction.commit()
1000
    self.tic()
1001 1002 1003 1004 1005
    # 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)
1006 1007 1008
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
1009 1010
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
1011

1012
    message = message_from_string(messageText)
1013 1014
    part = None
    for i in message.get_payload():
1015
      if i.get_content_type()=='text/html':
1016
        part = i
1017
    self.assertNotEqual(part, None)
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    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)
    transaction.commit()
    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')
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

  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)
1048
    transaction.commit()
1049 1050 1051 1052
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
1053 1054
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
1055
    
1056
    message = message_from_string(messageText)
1057

1058
    self.assertEquals('Héhé', decode_header(message['Subject'])[0][0])
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('Hàhà', part.get_payload(decode=True))

Yusei Tahara's avatar
Yusei Tahara committed
1065
  def test_MailAttachmentPdf(self):
Yusei Tahara's avatar
Yusei Tahara committed
1066 1067 1068
    """
    Make sure that pdf document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1069
    # Add a document which will be attached.
Yusei Tahara's avatar
Yusei Tahara committed
1070
    # pdf
Nicolas Delaby's avatar
Nicolas Delaby committed
1071 1072 1073
    filename = 'sample_attachment.pdf'
    file_object = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file_object)
Yusei Tahara's avatar
Yusei Tahara committed
1074

1075
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    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',
1091
               destination='person_module/recipient',
Nicolas Delaby's avatar
Nicolas Delaby committed
1092
               aggregate=document.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
1093 1094 1095 1096 1097
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1098
    message = message_from_string(mail_text)
Yusei Tahara's avatar
Yusei Tahara committed
1099 1100 1101 1102 1103 1104 1105 1106
    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
1107
    self.assert_(filename in 
Yusei Tahara's avatar
Yusei Tahara committed
1108 1109 1110
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1111
      if i.get_filename()==filename:
Yusei Tahara's avatar
Yusei Tahara committed
1112
        part = i
Nicolas Delaby's avatar
Nicolas Delaby committed
1113
    self.assertEqual(part.get_payload(decode=True), str(document.getData()))
Yusei Tahara's avatar
Yusei Tahara committed
1114 1115

  def test_MailAttachmentText(self):
Yusei Tahara's avatar
Yusei Tahara committed
1116 1117 1118
    """
    Make sure that text document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1119
    # Add a document which will be attached.
Nicolas Delaby's avatar
Nicolas Delaby committed
1120 1121 1122
    filename = 'sample_attachment.odt'
    file_object = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file_object)
Yusei Tahara's avatar
Yusei Tahara committed
1123

1124
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1125 1126 1127
    self.tic()

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

    mail_text = event.send(download=True)

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

Yusei Tahara's avatar
Yusei Tahara committed
1163
  def test_MailAttachmentFile(self):
Yusei Tahara's avatar
Yusei Tahara committed
1164 1165 1166
    """
    Make sure that file document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1167
    # Add a document which will be attached.
Nicolas Delaby's avatar
Nicolas Delaby committed
1168 1169 1170
    filename = 'sample_attachment.zip'
    file_object = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file_object)
1171
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1172 1173 1174
    self.tic()

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

    mail_text = event.send(download=True)

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

  def test_MailAttachmentImage(self):
Yusei Tahara's avatar
Yusei Tahara committed
1211 1212 1213
    """
    Make sure that image document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1214
    # Add a document which will be attached.
Nicolas Delaby's avatar
Nicolas Delaby committed
1215 1216 1217
    filename = 'sample_attachment.gif'
    file_object = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file_object)
Yusei Tahara's avatar
Yusei Tahara committed
1218

1219
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1220 1221 1222
    self.tic()

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

    mail_text = event.send(download=True)

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

  def test_MailAttachmentWebPage(self):
Yusei Tahara's avatar
Yusei Tahara committed
1259 1260 1261
    """
    Make sure that webpage document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1262
    # Add a document which will be attached.
Nicolas Delaby's avatar
Nicolas Delaby committed
1263 1264 1265 1266
    filename = 'sample_attachment.html'
    document = self.portal.portal_contributions.newContent(
                          data='<html><body>Hello world!</body></html>',
                          filename=filename)
1267
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1268 1269 1270
    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1271
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
Yusei Tahara's avatar
Yusei Tahara committed
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
                                                    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',
1282
               destination='person_module/recipient',
Nicolas Delaby's avatar
Nicolas Delaby committed
1283
               aggregate=document.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
1284 1285 1286 1287 1288
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1289
    message = message_from_string(mail_text)
Yusei Tahara's avatar
Yusei Tahara committed
1290 1291 1292 1293 1294 1295 1296 1297
    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
1298
    self.assert_(filename in 
Yusei Tahara's avatar
Yusei Tahara committed
1299 1300 1301
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1302
      if i.get_filename() == filename:
Yusei Tahara's avatar
Yusei Tahara committed
1303
        part = i
1304
    self.assertEqual(part.get_payload(decode=True),
Nicolas Delaby's avatar
Nicolas Delaby committed
1305
                     str(document.getTextContent()))
1306
    self.assertEqual(part.get_content_type(), 'text/html')
Yusei Tahara's avatar
Yusei Tahara committed
1307

Aurel's avatar
Aurel committed
1308 1309 1310 1311 1312
  def test_MailRespond(self):
    """
    Test we can answer an incoming event and quote it
    """
    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1313
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
Aurel's avatar
Aurel committed
1314 1315 1316 1317 1318 1319
                                                    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
1320

Aurel's avatar
Aurel committed
1321 1322 1323
    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1324
               destination='person_module/recipient',
Aurel's avatar
Aurel committed
1325 1326 1327 1328 1329
               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",
1330
                                       respond_event_text_content="> This is an advertisement mail."
Aurel's avatar
Aurel committed
1331 1332 1333
                                       )

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

Aurel's avatar
Aurel committed
1335 1336 1337 1338 1339 1340 1341
    # 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
1342
    self.assertEqual(answer_event.getSimulationState(), "started")
Aurel's avatar
Aurel committed
1343 1344
    self.assertEqual(answer_event.getCausality(), event.getRelativeUrl())
    self.assertEqual(answer_event.getDestination(), 'person_module/me')
1345
    self.assertEqual(answer_event.getSource(), 'person_module/recipient')
Aurel's avatar
Aurel committed
1346
    self.assertEqual(answer_event.getTextContent(), '> This is an advertisement mail.')
1347 1348
    self.assertEqual(answer_event.getFollowUpValue(), ticket)
    self.assert_(answer_event.getData() is not None)
Yusei Tahara's avatar
Yusei Tahara committed
1349

1350 1351 1352 1353 1354 1355
  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
1356
    def add_document(filename, container, portal_type):
1357
      f = makeFileUpload(filename)
Nicolas Delaby's avatar
Nicolas Delaby committed
1358
      document = container.newContent(portal_type=portal_type)
1359 1360
      document.edit(file=f, reference=filename)
      return document
Nicolas Delaby's avatar
Nicolas Delaby committed
1361
    filename = 'sample_attachment.txt'
1362
    # txt
Nicolas Delaby's avatar
Nicolas Delaby committed
1363
    document_txt = add_document(filename,
1364
                                self.portal.person_module['me'], 'Embedded File')
1365

1366
    transaction.commit()
1367 1368 1369
    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1370
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
                                                    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',
1381
               destination='person_module/recipient',
1382 1383 1384 1385 1386 1387
               aggregate=document_txt.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1388
    message = message_from_string(mail_text)
1389 1390 1391 1392
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
1393
        break
1394 1395 1396 1397
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # txt
Nicolas Delaby's avatar
Nicolas Delaby committed
1398
    self.assert_(filename in 
1399 1400 1401
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1402
      if i.get_filename() == filename:
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
        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
1414
    def add_document(filename, container, portal_type):
1415
      f = makeFileUpload(filename)
Nicolas Delaby's avatar
Nicolas Delaby committed
1416
      document = container.newContent(portal_type=portal_type)
1417 1418 1419 1420
      document.edit(file=f, reference=filename)
      return document

    # gif
Nicolas Delaby's avatar
Nicolas Delaby committed
1421 1422
    filename = 'sample_attachment.gif'
    document_gif = add_document(filename,
1423
                                self.portal.person_module['me'], 'Embedded File')
1424

1425
    transaction.commit()
1426 1427 1428
    self.tic()

    # Add a ticket
Nicolas Delaby's avatar
Nicolas Delaby committed
1429
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
                                                    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',
1440
               destination='person_module/recipient',
1441 1442 1443 1444 1445 1446
               aggregate=document_gif.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
1447
    message = message_from_string(mail_text)
1448 1449 1450 1451 1452 1453 1454 1455
    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
1456
    self.assert_(filename in 
1457 1458 1459
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
Nicolas Delaby's avatar
Nicolas Delaby committed
1460
      if i.get_filename() == filename:
1461 1462 1463
        part = i
    self.assertEqual(part.get_payload(decode=True), str(document_gif.getData()))

1464 1465 1466 1467 1468
  def test_cloneEvent(self):
    """
      All events uses after script and interaciton
      workflow add a test for clone
    """
1469 1470
    # XXX in the case of title, getTitle ignores the title attribute,
    # if any data is stored. In the case of text_content, getTextContent
1471
    # respects the behaviour is the same as Title.
1472 1473 1474 1475 1476
    portal_type = 'Mail Message'
    dummy_title = 'Dummy title'
    real_title = 'Real Title'
    dummy_content = 'Dummy content'
    real_content = 'Real content'
1477
    event = self.portal.event_module.newContent(portal_type=portal_type,
1478
                                                title=dummy_title,
1479
                                                text_content=dummy_content,)
1480 1481
    self.assertFalse(event.hasFile(), '%r has a file' % (event,))
    self.assertEquals(event.getTitle(), dummy_title)
1482
    self.assertEquals(event.getTextContent(), dummy_content)
1483

1484
    event.setData('Subject: %s\r\n\r\n%s' % (real_title, real_content))
1485 1486 1487
    self.assertTrue(event.hasFile(), '%r has no file' % (event,))
    self.assertEquals(event.getTitle(), real_title)
    self.assertEquals(event.getTextContent(), real_content)
1488

1489 1490
    self.stepTic()
    new_event = event.Base_createCloneDocument(batch_mode=1)
1491 1492 1493 1494
    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)
1495

Nicolas Delaby's avatar
Nicolas Delaby committed
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 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
  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')
    transaction.commit()
    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'
1550
      direction = 'incoming'
Nicolas Delaby's avatar
Nicolas Delaby committed
1551
      portal_type = 'Note'
Nicolas Delaby's avatar
Nicolas Delaby committed
1552
      resource = resource['1'].getCategoryRelativeUrl()
Nicolas Delaby's avatar
Nicolas Delaby committed
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
      person.Base_addEvent(title, direction, portal_type, resource)

      # Index Event
      transaction.commit()
      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'
1573
      direction = 'outgoing'
Nicolas Delaby's avatar
Nicolas Delaby committed
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 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
      another_person.Base_addEvent(title, direction, portal_type, resource)

      # Index Event
      transaction.commit()
      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
      transaction.commit()
      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
      transaction.commit()
      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()
      transaction.commit()
      self.tic()
1637

1638 1639
def test_suite():
  suite = unittest.TestSuite()
1640
  suite.addTest(unittest.makeSuite(TestCRM))
1641
  suite.addTest(unittest.makeSuite(TestCRMMailIngestion))
Yusei Tahara's avatar
Yusei Tahara committed
1642
  suite.addTest(unittest.makeSuite(TestCRMMailSend))
1643
  return suite