CRM-15578 - Mailing.create - Fix updates to "groups" and "mailings". Add test.
[civicrm-core.git] / tests / phpunit / api / v3 / MailingTest.php
1 <?php
2 /*
3 * File for the TestMailing class
4 *
5 * (PHP 5)
6 *
7 * @package CiviCRM
8 *
9 * This file is part of CiviCRM
10 *
11 * CiviCRM is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Affero General Public License
13 * as published by the Free Software Foundation; either version 3 of
14 * the License, or (at your option) any later version.
15 *
16 * CiviCRM is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Affero General Public License for more details.
20 *
21 * You should have received a copy of the GNU Affero General Public
22 * License along with this program. If not, see
23 * <http://www.gnu.org/licenses/>.
24 */
25
26 require_once 'CiviTest/CiviUnitTestCase.php';
27
28
29 /**
30 * Test APIv3 civicrm_mailing_* functions
31 *
32 * @package CiviCRM
33 */
34 class api_v3_MailingTest extends CiviUnitTestCase {
35 protected $_groupID;
36 protected $_email;
37 protected $_apiversion = 3;
38 protected $_params = array();
39 protected $_entity = 'Mailing';
40 protected $_contactID;
41
42 /**
43 * @return array
44 */
45 function get_info() {
46 return array(
47 'name' => 'Mailer',
48 'description' => 'Test all Mailer methods.',
49 'group' => 'CiviCRM API Tests',
50 );
51 }
52
53 function setUp() {
54 parent::setUp();
55 $this->useTransaction();
56 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
57 $this->_contactID = $this->individualCreate();
58 $this->_groupID = $this->groupCreate();
59 $this->_email = 'test@test.test';
60 $this->_params = array(
61 'subject' => 'Hello {contact.display_name}',
62 'body_text' => "This is {contact.display_name}",
63 'body_html' => "<p>This is {contact.display_name}</p>",
64 'name' => 'mailing name',
65 'created_id' => $this->_contactID,
66 );
67 }
68
69 function tearDown() {
70 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
71 parent::tearDown();
72 }
73
74 /**
75 * Test civicrm_mailing_create
76 */
77 public function testMailerCreateSuccess() {
78 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params, __FUNCTION__, __FILE__);
79 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
80 $this->assertEquals(1, $jobs['count']);
81 unset($this->_params['created_id']); // return isn't working on this in getAndCheck so lets not check it for now
82 $this->getAndCheck($this->_params, $result['id'], 'mailing');
83 }
84
85 /**
86 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
87 * Make sure these work
88 */
89 public function testMagicGroups_create_update() {
90 // BEGIN SAMPLE DATA
91 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
92 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
93 $contactIDs['a'] = $this->individualCreate(array('email' => 'include.me@example.org', 'first_name' => 'Includer', 'last_name' => 'Person'));
94 $contactIDs['b'] = $this->individualCreate(array('email' => 'exclude.me@example.org', 'last_name' => 'Excluder', 'last_name' => 'Excluder'));
95 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['a'], 'contact_id' => $contactIDs['a']));
96 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['b'], 'contact_id' => $contactIDs['b']));
97 // END SAMPLE DATA
98
99 // ** Pass 1: Create
100 $createParams = $this->_params;
101 $createParams['groups']['include'] = array($groupIDs['a']);
102 $createParams['groups']['exclude'] = array();
103 $createParams['mailings']['include'] = array();
104 $createParams['mailings']['exclude'] = array();
105 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
106 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
107 $getGroup1_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup1['values']));
108 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
109
110 // ** Pass 2: Update without any changes to groups[include]
111 $nullopParams = $createParams;
112 $nullopParams['id'] = $createResult['id'];
113 unset($nullopParams['groups']['include']);
114 $this->callAPISuccess('Mailing', 'create', $nullopParams);
115 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
116 $getGroup2_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup2['values']));
117 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
118
119 // ** Pass 3: Update with different groups[include]
120 $updateParams = $createParams;
121 $updateParams['id'] = $createResult['id'];
122 $updateParams['groups']['include'] = array($groupIDs['b']);
123 $this->callAPISuccess('Mailing', 'create', $updateParams);
124 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
125 $getGroup3_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup3['values']));
126 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
127 }
128
129 public function testMailerPreview() {
130 // BEGIN SAMPLE DATA
131 $contactID = $this->individualCreate();
132 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
133 $displayName = $displayName['values'][$contactID]['display_name'];
134 $this->assertTrue(!empty($displayName));
135
136 $params = $this->_params;
137 $params['api.Mailing.preview'] = array(
138 'id' => '$value.id',
139 'contact_id' => $contactID,
140 );
141 $params['options']['force_rollback'] = 1;
142 // END SAMPLE DATA
143
144 $maxIDs = array(
145 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
146 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
147 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
148 'recip' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
149 );
150 $result = $this->callAPISuccess('mailing', 'create', $params);
151 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
152 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
153 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
154 $this->assertDBQuery($maxIDs['recip'], 'SELECT MAX(id) FROM civicrm_mailing_recipients'); // 'Preview should not create any mailing_recipient records'
155
156 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
157 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
158 $this->assertEquals("This is $displayName", $previewResult['values']['body_text']);
159 $this->assertContains("<p>This is $displayName</p>", $previewResult['values']['body_html']);
160 }
161
162 public function testMailerPreviewRecipients() {
163 // BEGIN SAMPLE DATA
164 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
165 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
166 $contactIDs['includeme'] = $this->individualCreate(array('email' => 'include.me@example.org', 'first_name' => 'Includer', 'last_name' => 'Person'));
167 $contactIDs['excludeme'] = $this->individualCreate(array('email' => 'exclude.me@example.org', 'last_name' => 'Excluder', 'last_name' => 'Excluder'));
168 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['includeme']));
169 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['excludeme']));
170 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['exc'], 'contact_id' => $contactIDs['excludeme']));
171
172 $params = $this->_params;
173 $params['groups']['include'] = array($groupIDs['inc']);
174 $params['groups']['exclude'] = array($groupIDs['exc']);
175 $params['mailings']['include'] = array();
176 $params['mailings']['exclude'] = array();
177 $params['options']['force_rollback'] = 1;
178 $params['api.MailingRecipients.get'] = array(
179 'mailing_id' => '$value.id',
180 'api.contact.getvalue' => array(
181 'return' => 'display_name',
182 ),
183 'api.email.getvalue' => array(
184 'return' => 'email',
185 ),
186 );
187 // END SAMPLE DATA
188
189 $maxIDs = array(
190 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
191 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
192 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
193 );
194 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__, __FILE__);
195 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
196 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
197 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
198
199 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
200 $previewIds = array_values(CRM_Utils_Array::collect('contact_id', $preview['values']));
201 $this->assertEquals(array((string)$contactIDs['includeme']), $previewIds);
202 $previewEmails = array_values(CRM_Utils_Array::collect('api.email.getvalue', $preview['values']));
203 $this->assertEquals(array('include.me@example.org'), $previewEmails);
204 $previewNames = array_values(CRM_Utils_Array::collect('api.contact.getvalue', $preview['values']));
205 $this->assertTrue((bool)preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
206 }
207
208 public function testMailerSendTest_email() {
209 $contactIDs['alice'] = $this->individualCreate(array('email' => 'alice@example.org', 'first_name' => 'Alice', 'last_name' => 'Person'));
210
211 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
212
213 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
214 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
215 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
216
217 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
218 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
219
220 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
221 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
222 }
223
224 public function testMailerSendTest_group() {
225 // BEGIN SAMPLE DATA
226 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
227 $contactIDs['alice'] = $this->individualCreate(array('email' => 'alice@example.org', 'first_name' => 'Alice', 'last_name' => 'Person'));
228 $contactIDs['bob'] = $this->individualCreate(array('email' => 'bob@example.org', 'first_name' => 'Bob', 'last_name' => 'Person'));
229 $contactIDs['carol'] = $this->individualCreate(array('email' => 'carol@example.org', 'first_name' => 'Carol', 'last_name' => 'Person'));
230 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['alice']));
231 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['bob']));
232 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['carol']));
233 // END SAMPLE DATA
234
235 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
236 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', array(
237 'mailing_id' => $mail['id'],
238 'test_email' => NULL,
239 'test_group' => $groupIDs['inc'],
240 ));
241 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
242
243 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
244 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
245
246 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
247 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
248 }
249
250 public function testMailerStats() {
251 $result = $this->groupContactCreate($this->_groupID, 100);
252 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
253
254 //Create and send test mail first and change the mail job to live,
255 //because stats api only works on live mail
256 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
257 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID);
258 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
259 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
260
261 //Change the test mail into live
262 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
263 CRM_Core_DAO::executeQuery($sql);
264
265 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
266 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
267 (event_queue_id int, time_stamp datetime, delivered_id int)
268 SELECT event_queue_id, time_stamp, id
269 FROM civicrm_mailing_event_delivered
270 WHERE id IN ($deliveredIds)
271 ORDER BY RAND() LIMIT 0,20;";
272 CRM_Core_DAO::executeQuery($sql);
273
274 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
275 CRM_Core_DAO::executeQuery($sql);
276
277 if ($type == 'unsubscribe') {
278 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
279 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
280 }
281 else {
282 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
283 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
284 }
285 CRM_Core_DAO::executeQuery($sql);
286 }
287
288 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
289 $expectedResult = array(
290 'Delivered' => 80, //since among 100 mails 20 has been bounced
291 'Bounces' => 20,
292 'Opened' => 20,
293 'Unique Clicks' => 0,
294 'Unsubscribers' => 20
295 );
296 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
297 }
298 /**
299 * Test civicrm_mailing_delete
300 */
301 public function testMailerDeleteSuccess() {
302 $result = $this->callAPISuccess($this->_entity, 'create', $this->_params);
303 $jobs = $this->callAPIAndDocument($this->_entity, 'delete', array('id' => $result['id']), __FUNCTION__, __FILE__);
304 $this->assertAPIDeleted($this->_entity, $result['id']);
305 }
306
307 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
308
309 //------------ civicrm_mailing_event_bounce methods------------
310
311 /**
312 * Test civicrm_mailing_event_bounce with wrong params.
313 * Note that tests like this are slightly better than no test but an
314 * api function cannot be considered supported / 'part of the api' without a
315 * success test
316 */
317 public function testMailerBounceWrongParams() {
318 $params = array(
319 'job_id' => 'Wrong ID',
320 'event_queue_id' => 'Wrong ID',
321 'hash' => 'Wrong Hash',
322 'body' => 'Body...',
323 'time_stamp' => '20111109212100',
324 );
325 $result = $this->callAPIFailure('mailing_event', 'bounce', $params,
326 'Queue event could not be found'
327 );
328 }
329
330 //----------- civicrm_mailing_event_confirm methods -----------
331
332 /**
333 * Test civicrm_mailing_event_confirm with wrong params.
334 * Note that tests like this are slightly better than no test but an
335 * api function cannot be considered supported / 'part of the api' without a
336 * success test
337 */
338 public function testMailerConfirmWrongParams() {
339 $params = array(
340 'contact_id' => 'Wrong ID',
341 'subscribe_id' => 'Wrong ID',
342 'hash' => 'Wrong Hash',
343 'event_subscribe_id' => '123',
344 'time_stamp' => '20111111010101',
345 );
346 $result = $this->callAPIFailure('mailing_event', 'confirm', $params,
347 'Confirmation failed'
348 );
349 }
350
351 //---------- civicrm_mailing_event_reply methods -----------
352
353 /**
354 * Test civicrm_mailing_event_reply with wrong params.
355 *
356 * Note that tests like this are slightly better than no test but an
357 * api function cannot be considered supported / 'part of the api' without a
358 * success test
359 */
360 public function testMailerReplyWrongParams() {
361 $params = array(
362 'job_id' => 'Wrong ID',
363 'event_queue_id' => 'Wrong ID',
364 'hash' => 'Wrong Hash',
365 'bodyTxt' => 'Body...',
366 'replyTo' => $this->_email,
367 'time_stamp' => '20111111010101',
368 );
369 $result = $this->callAPIFailure('mailing_event', 'reply', $params,
370 'Queue event could not be found'
371 );
372 }
373
374
375 //----------- civicrm_mailing_event_forward methods ----------
376
377 /**
378 * Test civicrm_mailing_event_forward with wrong params.
379 * Note that tests like this are slightly better than no test but an
380 * api function cannot be considered supported / 'part of the api' without a
381 * success test
382 */
383 public function testMailerForwardWrongParams() {
384 $params = array(
385 'job_id' => 'Wrong ID',
386 'event_queue_id' => 'Wrong ID',
387 'hash' => 'Wrong Hash',
388 'email' => $this->_email,
389 'time_stamp' => '20111111010101',
390 );
391 $result = $this->callAPIFailure('mailing_event', 'forward', $params,
392 'Queue event could not be found'
393 );
394 }
395
396 //----------- civicrm_mailing_create ----------
397
398 }