Merge pull request #5220 from totten/master-recip-grptype
[civicrm-core.git] / js / angular-crmMailing / services.js
CommitLineData
8dfd5110 1(function (angular, $, _) {
8dfd5110 2
a0214785
TO
3 // The representation of from/reply-to addresses is inconsistent in the mailing data-model,
4 // so the UI must do some adaptation. The crmFromAddresses provides a richer way to slice/dice
5 // the available "From:" addrs. Records are like the underlying OptionValues -- but add "email"
6 // and "author".
88e9e883 7 angular.module('crmMailing').factory('crmFromAddresses', function ($q, crmApi) {
6bcb856f 8 var emailRegex = /^"(.*)" <([^@>]*@[^@>]*)>$/;
f4f103fa 9 var addrs = _.map(CRM.crmMailing.fromAddress, function (addr) {
a0214785 10 var match = emailRegex.exec(addr.label);
86c3a327 11 return angular.extend({}, addr, {
a0214785
TO
12 email: match ? match[2] : '(INVALID)',
13 author: match ? match[1] : '(INVALID)'
14 });
15 });
f4f103fa 16
a0214785 17 function first(array) {
6bcb856f 18 return (array.length === 0) ? null : array[0];
52f515c6 19 }
a0214785
TO
20
21 return {
22 getAll: function getAll() {
23 return addrs;
24 },
25 getByAuthorEmail: function getByAuthorEmail(author, email, autocreate) {
26 var result = null;
f4f103fa 27 _.each(addrs, function (addr) {
a0214785
TO
28 if (addr.author == author && addr.email == email) {
29 result = addr;
30 }
31 });
32 if (!result && autocreate) {
33 result = {
34 label: '(INVALID) "' + author + '" <' + email + '>',
35 author: author,
36 email: email
37 };
38 addrs.push(result);
39 }
40 return result;
41 },
42 getByEmail: function getByEmail(email) {
43 return first(_.where(addrs, {email: email}));
44 },
f4f103fa 45 getByLabel: function (label) {
a0214785
TO
46 return first(_.where(addrs, {label: label}));
47 },
48 getDefault: function getDefault() {
49 return first(_.where(addrs, {is_default: "1"}));
50 }
51 };
52 });
53
88e9e883 54 angular.module('crmMailing').factory('crmMsgTemplates', function ($q, crmApi) {
f4f103fa 55 var tpls = _.map(CRM.crmMailing.mesTemplate, function (tpl) {
86c3a327 56 return angular.extend({}, tpl, {
744bebee
TO
57 //id: tpl parseInt(tpl.id)
58 });
59 });
60 window.tpls = tpls;
61 var lastModifiedTpl = null;
62 return {
63 // @return Promise MessageTemplate (per APIv3)
64 get: function get(id) {
f4f103fa 65 id = '' + id; // parseInt(id);
744bebee
TO
66 var dfr = $q.defer();
67 var tpl = _.where(tpls, {id: id});
68 if (id && tpl && tpl[0]) {
69 dfr.resolve(tpl[0]);
f4f103fa
TO
70 }
71 else {
744bebee
TO
72 dfr.reject(id);
73 }
74 return dfr.promise;
75 },
76 // Save a template
77 // @param tpl MessageTemplate (per APIv3) For new templates, omit "id"
78 // @return Promise MessageTemplate (per APIv3)
f4f103fa
TO
79 save: function (tpl) {
80 return crmApi('MessageTemplate', 'create', tpl).then(function (response) {
744bebee 81 if (!tpl.id) {
f4f103fa 82 tpl.id = '' + response.id; //parseInt(response.id);
744bebee
TO
83 tpls.push(tpl);
84 }
f2bad133 85 lastModifiedTpl = tpl;
744bebee
TO
86 return tpl;
87 });
88 },
89 // @return Object MessageTemplate (per APIv3)
f4f103fa 90 getLastModifiedTpl: function () {
744bebee
TO
91 return lastModifiedTpl;
92 },
93 getAll: function getAll() {
94 return tpls;
95 }
96 };
97 });
98
a0214785 99 // The crmMailingMgr service provides business logic for loading, saving, previewing, etc
8717390f 100 angular.module('crmMailing').factory('crmMailingMgr', function ($q, crmApi, crmFromAddresses, crmNow) {
4dd19229 101 var pickDefaultMailComponent = function pickDefaultMailComponent(type) {
8dfd5110 102 var mcs = _.where(CRM.crmMailing.headerfooterList, {
f4f103fa 103 component_type: type,
8dfd5110
TO
104 is_default: "1"
105 });
106 return (mcs.length >= 1) ? mcs[0].id : null;
107 };
108
109 return {
110 // @param scalar idExpr a number or the literal string 'new'
111 // @return Promise|Object Mailing (per APIv3)
4dd19229 112 getOrCreate: function getOrCreate(idExpr) {
8dfd5110
TO
113 return (idExpr == 'new') ? this.create() : this.get(idExpr);
114 },
115 // @return Promise Mailing (per APIv3)
4dd19229 116 get: function get(id) {
86c3a327
TO
117 var crmMailingMgr = this;
118 var mailing;
119 return crmApi('Mailing', 'getsingle', {id: id})
120 .then(function (getResult) {
121 mailing = getResult;
122 return $q.all([
123 crmMailingMgr._loadGroups(mailing),
124 crmMailingMgr._loadJobs(mailing)
125 ]);
126 })
127 .then(function () {
128 return mailing;
129 });
130 },
131 // Call MailingGroup.get and merge results into "mailing"
132 _loadGroups: function (mailing) {
133 return crmApi('MailingGroup', 'get', {mailing_id: mailing.id})
134 .then(function (groupResult) {
9cd4f489 135 mailing.recipients = {};
720c658b 136 mailing.recipients.groups = {include: [], exclude: [], base: []};
9cd4f489 137 mailing.recipients.mailings = {include: [], exclude: []};
f4f103fa 138 _.each(groupResult.values, function (mailingGroup) {
f78abdbe 139 var bucket = (/^civicrm_group/.test(mailingGroup.entity_table)) ? 'groups' : 'mailings';
89a50c67 140 var entityId = parseInt(mailingGroup.entity_id);
9cd4f489 141 mailing.recipients[bucket][mailingGroup.group_type.toLowerCase()].push(entityId);
8dfd5110 142 });
8dfd5110 143 });
86c3a327
TO
144 },
145 // Call MailingJob.get and merge results into "mailing"
146 _loadJobs: function (mailing) {
147 return crmApi('MailingJob', 'get', {mailing_id: mailing.id, is_test: 0})
148 .then(function (jobResult) {
149 mailing.jobs = mailing.jobs || {};
150 angular.extend(mailing.jobs, jobResult.values);
151 });
8dfd5110
TO
152 },
153 // @return Object Mailing (per APIv3)
657b8692
TO
154 create: function create(params) {
155 var defaults = {
86c3a327 156 jobs: {}, // {jobId: JobRecord}
9cd4f489 157 recipients: {
720c658b
TO
158 groups: {include: [], exclude: [], base: []},
159 mailings: {include: [], exclude: []}
9cd4f489 160 },
d78cc635 161 name: "",
8dfd5110 162 campaign_id: null,
8dfd5110 163 replyto_email: "",
d78cc635 164 subject: "",
13782061 165 body_html: "",
657b8692 166 body_text: ""
8dfd5110 167 };
657b8692 168 return angular.extend({}, defaults, params);
8dfd5110
TO
169 },
170
705c61e9
TO
171 // @param mailing Object (per APIv3)
172 // @return Promise
f4f103fa 173 'delete': function (mailing) {
705c61e9
TO
174 if (mailing.id) {
175 return crmApi('Mailing', 'delete', {id: mailing.id});
f4f103fa
TO
176 }
177 else {
705c61e9
TO
178 var d = $q.defer();
179 d.resolve();
180 return d.promise;
181 }
182 },
183
21fb26b8
TO
184 // Search the body, header, and footer for required tokens.
185 // ex: var msgs = findMissingTokens(mailing, 'body_html');
186 findMissingTokens: function(mailing, field) {
187 var missing = {};
188 if (!_.isEmpty(mailing[field])) {
189 var body = '';
190 if (mailing.footer_id) {
191 var footer = _.where(CRM.crmMailing.headerfooterList, {id: mailing.footer_id});
192 body = body + footer[0][field];
193
194 }
195 body = body + mailing[field];
196 if (mailing.header_id) {
197 var header = _.where(CRM.crmMailing.headerfooterList, {id: mailing.header_id});
198 body = body + header[0][field];
199 }
200
201 angular.forEach(CRM.crmMailing.requiredTokens, function(value, token) {
202 if (!_.isObject(value)) {
203 if (body.indexOf('{' + token + '}') < 0) {
204 missing[token] = value;
205 }
206 }
207 else {
208 var count = 0;
209 angular.forEach(value, function(nestedValue, nestedToken) {
210 if (body.indexOf('{' + nestedToken + '}') >= 0) {
211 count++;
212 }
213 });
d03e0d13 214 if (count === 0) {
21fb26b8
TO
215 angular.extend(missing, value);
216 }
217 }
218 });
219 }
220 return missing;
221 },
222
07fa6426
TO
223 // Copy all data fields in (mailingFrom) to (mailingTgt) -- except for (excludes)
224 // ex: crmMailingMgr.mergeInto(newMailing, mailingTemplate, ['subject']);
225 mergeInto: function mergeInto(mailingTgt, mailingFrom, excludes) {
226 var MAILING_FIELDS = [
70980d8e 227 // always exclude: 'id'
07fa6426
TO
228 'name',
229 'campaign_id',
230 'from_name',
231 'from_email',
232 'replyto_email',
233 'subject',
234 'dedupe_email',
9cd4f489 235 'recipients',
07fa6426
TO
236 'body_html',
237 'body_text',
238 'footer_id',
239 'header_id',
240 'visibility',
241 'url_tracking',
242 'dedupe_email',
243 'forward_replies',
244 'auto_responder',
245 'open_tracking',
246 'override_verp',
247 'optout_id',
248 'reply_id',
249 'resubscribe_id',
250 'unsubscribe_id'
251 ];
252 if (!excludes) {
253 excludes = [];
254 }
255 _.each(MAILING_FIELDS, function (field) {
256 if (!_.contains(excludes, field)) {
257 mailingTgt[field] = mailingFrom[field];
258 }
f2bad133 259 });
07fa6426
TO
260 },
261
493eb47a
TO
262 // @param mailing Object (per APIv3)
263 // @return Promise an object with "subject", "body_text", "body_html"
264 preview: function preview(mailing) {
9cd4f489 265 var params = angular.extend({}, mailing, mailing.recipients, {
f4f103fa 266 options: {force_rollback: 1},
493eb47a 267 'api.Mailing.preview': {
52f515c6 268 id: '$value.id'
493eb47a
TO
269 }
270 });
9cd4f489 271 delete params.recipients; // the content was merged in
f4f103fa 272 return crmApi('Mailing', 'create', params).then(function (result) {
beab9d1b 273 // changes rolled back, so we don't care about updating mailing
493eb47a
TO
274 return result.values[result.id]['api.Mailing.preview'].values;
275 });
276 },
277
8dfd5110
TO
278 // @param mailing Object (per APIv3)
279 // @param int previewLimit
280 // @return Promise for a list of recipients (mailing_id, contact_id, api.contact.getvalue, api.email.getvalue)
4dd19229 281 previewRecipients: function previewRecipients(mailing, previewLimit) {
8dfd5110
TO
282 // To get list of recipients, we tentatively save the mailing and
283 // get the resulting recipients -- then rollback any changes.
9cd4f489 284 var params = angular.extend({}, mailing, mailing.recipients, {
13782061
TO
285 name: 'placeholder', // for previewing recipients on new, incomplete mailing
286 subject: 'placeholder', // for previewing recipients on new, incomplete mailing
f4f103fa 287 options: {force_rollback: 1},
7575b840 288 'api.mailing_job.create': 1, // note: exact match to API default
8dfd5110
TO
289 'api.MailingRecipients.get': {
290 mailing_id: '$value.id',
58dfba8d 291 options: {limit: previewLimit},
8dfd5110
TO
292 'api.contact.getvalue': {'return': 'display_name'},
293 'api.email.getvalue': {'return': 'email'}
294 }
295 });
9cd4f489 296 delete params.recipients; // the content was merged in
f4f103fa 297 return crmApi('Mailing', 'create', params).then(function (recipResult) {
beab9d1b 298 // changes rolled back, so we don't care about updating mailing
8dfd5110
TO
299 return recipResult.values[recipResult.id]['api.MailingRecipients.get'].values;
300 });
beab9d1b
TO
301 },
302
43102e47 303 // Save a (draft) mailing
705c61e9
TO
304 // @param mailing Object (per APIv3)
305 // @return Promise
d78cc635 306 save: function(mailing) {
9cd4f489 307 var params = angular.extend({}, mailing, mailing.recipients);
43102e47 308
d78cc635
TO
309 // Angular ngModel sometimes treats blank fields as undefined.
310 angular.forEach(mailing, function(value, key) {
e72949ef 311 if (value === undefined || value === null) {
d78cc635
TO
312 mailing[key] = '';
313 }
314 });
315
43102e47
TO
316 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
317 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
318 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
319 delete params.scheduled_date;
320
86c3a327
TO
321 delete params.jobs;
322
9cd4f489
TO
323 delete params.recipients; // the content was merged in
324
d78cc635 325 return crmApi('Mailing', 'create', params).then(function(result) {
f4f103fa
TO
326 if (result.id && !mailing.id) {
327 mailing.id = result.id;
328 } // no rollback, so update mailing.id
43102e47 329 // Perhaps we should reload mailing based on result?
86c3a327 330 return mailing;
705c61e9
TO
331 });
332 },
333
334 // Schedule/send the mailing
335 // @param mailing Object (per APIv3)
336 // @return Promise
43102e47 337 submit: function (mailing) {
86c3a327 338 var crmMailingMgr = this;
6818346a
TO
339 var params = {
340 id: mailing.id,
8717390f
TO
341 approval_date: crmNow(),
342 scheduled_date: mailing.scheduled_date ? mailing.scheduled_date : crmNow()
43102e47 343 };
86c3a327
TO
344 return crmApi('Mailing', 'submit', params)
345 .then(function (result) {
346 angular.extend(mailing, result.values[result.id]); // Perhaps we should reload mailing based on result?
347 return crmMailingMgr._loadJobs(mailing);
348 })
349 .then(function () {
350 return mailing;
351 });
705c61e9
TO
352 },
353
354 // Immediately send a test message
beab9d1b 355 // @param mailing Object (per APIv3)
58dfba8d 356 // @param to Object with either key "email" (string) or "gid" (int)
beab9d1b 357 // @return Promise for a list of delivery reports
58dfba8d 358 sendTest: function (mailing, recipient) {
9cd4f489 359 var params = angular.extend({}, mailing, mailing.recipients, {
43102e47 360 // options: {force_rollback: 1}, // Test mailings include tracking features, so the mailing must be persistent
beab9d1b
TO
361 'api.Mailing.send_test': {
362 mailing_id: '$value.id',
58dfba8d
TO
363 test_email: recipient.email,
364 test_group: recipient.gid
beab9d1b
TO
365 }
366 });
43102e47
TO
367
368 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
369 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
370 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
371 delete params.scheduled_date;
372
86c3a327
TO
373 delete params.jobs;
374
9cd4f489
TO
375 delete params.recipients; // the content was merged in
376
f4f103fa
TO
377 return crmApi('Mailing', 'create', params).then(function (result) {
378 if (result.id && !mailing.id) {
379 mailing.id = result.id;
380 } // no rollback, so update mailing.id
beab9d1b
TO
381 return result.values[result.id]['api.Mailing.send_test'].values;
382 });
8dfd5110
TO
383 }
384 };
385 });
58dfba8d
TO
386
387 // The preview manager performs preview actions while putting up a visible UI (e.g. dialogs & status alerts)
388 angular.module('crmMailing').factory('crmMailingPreviewMgr', function (dialogService, crmMailingMgr, crmStatus) {
389 return {
390 // @param mode string one of 'html', 'text', or 'full'
391 // @return Promise
392 preview: function preview(mailing, mode) {
393 var templates = {
ef5d18a1
TO
394 html: '~/crmMailing/dialog/previewHtml.html',
395 text: '~/crmMailing/dialog/previewText.html',
396 full: '~/crmMailing/dialog/previewFull.html'
58dfba8d
TO
397 };
398 var result = null;
399 var p = crmMailingMgr
400 .preview(mailing)
401 .then(function (content) {
b1fc510d 402 var options = CRM.utils.adjustDialogDefaults({
58dfba8d 403 autoOpen: false,
58dfba8d
TO
404 title: ts('Subject: %1', {
405 1: content.subject
406 })
b1fc510d 407 });
58dfba8d
TO
408 result = dialogService.open('previewDialog', templates[mode], content, options);
409 });
410 crmStatus({start: ts('Previewing'), success: ''}, p);
411 return result;
412 },
413
414 // @param to Object with either key "email" (string) or "gid" (int)
415 // @return Promise
416 sendTest: function sendTest(mailing, recipient) {
417 var promise = crmMailingMgr.sendTest(mailing, recipient)
418 .then(function (deliveryInfos) {
419 var count = Object.keys(deliveryInfos).length;
420 if (count === 0) {
421 CRM.alert(ts('Could not identify any recipients. Perhaps the group is empty?'));
422 }
423 })
424 ;
425 return crmStatus({start: ts('Sending...'), success: ts('Sent')}, promise);
426 }
427 };
428 });
429
7173e315
TO
430 angular.module('crmMailing').factory('crmMailingStats', function (crmApi, crmLegacy) {
431 var statTypes = [
432 // {name: 'Recipients', title: ts('Intended Recipients'), searchFilter: '', eventsFilter: '&event=queue'},
433 {name: 'Delivered', title: ts('Successful Deliveries'), searchFilter: '&mailing_delivery_status=Y', eventsFilter: '&event=delivered'},
434 {name: 'Opened', title: ts('Tracked Opens'), searchFilter: '&mailing_open_status=Y', eventsFilter: '&event=opened'},
435 {name: 'Unique Clicks', title: ts('Click-throughs'), searchFilter: '&mailing_click_status=Y', eventsFilter: '&event=click&distinct=1'},
436 // {name: 'Forward', title: ts('Forwards'), searchFilter: '&mailing_forward=1', eventsFilter: '&event=forward'},
437 // {name: 'Replies', title: ts('Replies'), searchFilter: '&mailing_reply_status=Y', eventsFilter: '&event=reply'},
438 {name: 'Bounces', title: ts('Bounces'), searchFilter: '&mailing_delivery_status=N', eventsFilter: '&event=bounce'},
439 {name: 'Unsubscribers', title: ts('Unsubscribes'), searchFilter: '&mailing_unsubscribe=1', eventsFilter: '&event=unsubscribe'}
440 // {name: 'OptOuts', title: ts('Opt-Outs'), searchFilter: '&mailing_optout=1', eventsFilter: '&event=optout'}
441 ];
442
443 return {
444 getStatTypes: function() {
445 return statTypes;
446 },
447
448 /**
449 * @param mailingIds object
450 * List of mailing IDs ({a: 123, b: 456})
451 * @return Promise
452 * List of stats for each mailing
453 * ({a: ...object..., b: ...object...})
454 */
455 getStats: function(mailingIds) {
456 var params = {};
457 angular.forEach(mailingIds, function(mailingId, name) {
458 params[name] = ['Mailing', 'stats', {mailing_id: mailingId}];
459 });
460 return crmApi(params).then(function(result) {
461 var stats = {};
462 angular.forEach(mailingIds, function(mailingId, name) {
463 stats[name] = result[name].values[mailingId];
464 });
465 return stats;
466 });
467 },
468
469 /**
470 * Determine the legacy URL for a report about a given mailing and stat.
471 *
472 * @param mailing object
473 * @param statType object (see statTypes above)
474 * @param view string ('search', 'event', 'report')
475 * @return string|null
476 */
477 getUrl: function getUrl(mailing, statType, view) {
478 switch (view) {
479 case 'events':
480 return crmLegacy.url('civicrm/mailing/report/event',
481 'reset=1&mid=' + mailing.id + statType.eventsFilter);
482
483 case 'search':
484 return crmLegacy.url('civicrm/contact/search/advanced',
485 'force=1&mailing_id=' + mailing.id + statType.searchFilter);
486
487 // TODO: case 'report':
488 default:
489 return null;
490 }
491 }
492 };
493 });
494
8dfd5110 495})(angular, CRM.$, CRM._);