Merge pull request #11553 from civicrm/4.7.30-rc
[civicrm-core.git] / ang / crmMailing / services.js
1 (function (angular, $, _) {
2
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".
7 angular.module('crmMailing').factory('crmFromAddresses', function ($q, crmApi) {
8 var emailRegex = /^"(.*)" <([^@>]*@[^@>]*)>$/;
9 var addrs = _.map(CRM.crmMailing.fromAddress, function (addr) {
10 var match = emailRegex.exec(addr.label);
11 return angular.extend({}, addr, {
12 email: match ? match[2] : '(INVALID)',
13 author: match ? match[1] : '(INVALID)'
14 });
15 });
16
17 function first(array) {
18 return (array.length === 0) ? null : array[0];
19 }
20
21 return {
22 getAll: function getAll() {
23 return addrs;
24 },
25 getByAuthorEmail: function getByAuthorEmail(author, email, autocreate) {
26 var result = null;
27 _.each(addrs, function (addr) {
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 },
45 getByLabel: function (label) {
46 return first(_.where(addrs, {label: label}));
47 },
48 getDefault: function getDefault() {
49 return first(_.where(addrs, {is_default: "1"}));
50 }
51 };
52 });
53
54 angular.module('crmMailing').factory('crmMsgTemplates', function ($q, crmApi) {
55 var tpls = _.map(CRM.crmMailing.mesTemplate, function (tpl) {
56 return angular.extend({}, tpl, {
57 //id: tpl parseInt(tpl.id)
58 });
59 });
60 window.tpls = tpls;
61 var lastModifiedTpl = null;
62 return {
63 // Get a template
64 // @param id MessageTemplate id (per APIv3)
65 // @return Promise MessageTemplate (per APIv3)
66 get: function get(id) {
67 return crmApi('MessageTemplate', 'getsingle', {
68 "return": "id,msg_subject,msg_html,msg_title,msg_text",
69 "id": id
70 });
71 },
72 // Save a template
73 // @param tpl MessageTemplate (per APIv3) For new templates, omit "id"
74 // @return Promise MessageTemplate (per APIv3)
75 save: function (tpl) {
76 return crmApi('MessageTemplate', 'create', tpl).then(function (response) {
77 if (!tpl.id) {
78 tpl.id = '' + response.id; //parseInt(response.id);
79 tpls.push(tpl);
80 }
81 lastModifiedTpl = tpl;
82 return tpl;
83 });
84 },
85 // @return Object MessageTemplate (per APIv3)
86 getLastModifiedTpl: function () {
87 return lastModifiedTpl;
88 },
89 getAll: function getAll() {
90 return tpls;
91 }
92 };
93 });
94
95 // The crmMailingMgr service provides business logic for loading, saving, previewing, etc
96 angular.module('crmMailing').factory('crmMailingMgr', function ($q, crmApi, crmFromAddresses, crmQueue) {
97 var qApi = crmQueue(crmApi);
98 var pickDefaultMailComponent = function pickDefaultMailComponent(type) {
99 var mcs = _.where(CRM.crmMailing.headerfooterList, {
100 component_type: type,
101 is_default: "1"
102 });
103 return (mcs.length >= 1) ? mcs[0].id : null;
104 };
105
106 return {
107 // @param scalar idExpr a number or the literal string 'new'
108 // @return Promise|Object Mailing (per APIv3)
109 getOrCreate: function getOrCreate(idExpr) {
110 return (idExpr == 'new') ? this.create() : this.get(idExpr);
111 },
112 // @return Promise Mailing (per APIv3)
113 get: function get(id) {
114 var crmMailingMgr = this;
115 var mailing;
116 return qApi('Mailing', 'getsingle', {id: id})
117 .then(function (getResult) {
118 mailing = getResult;
119 return $q.all([
120 crmMailingMgr._loadGroups(mailing),
121 crmMailingMgr._loadJobs(mailing)
122 ]);
123 })
124 .then(function () {
125 return mailing;
126 });
127 },
128 // Call MailingGroup.get and merge results into "mailing"
129 _loadGroups: function (mailing) {
130 return crmApi('MailingGroup', 'get', {mailing_id: mailing.id})
131 .then(function (groupResult) {
132 mailing.recipients = {};
133 mailing.recipients.groups = {include: [], exclude: [], base: []};
134 mailing.recipients.mailings = {include: [], exclude: []};
135 _.each(groupResult.values, function (mailingGroup) {
136 var bucket = (/^civicrm_group/.test(mailingGroup.entity_table)) ? 'groups' : 'mailings';
137 var entityId = parseInt(mailingGroup.entity_id);
138 mailing.recipients[bucket][mailingGroup.group_type.toLowerCase()].push(entityId);
139 });
140 });
141 },
142 // Call MailingJob.get and merge results into "mailing"
143 _loadJobs: function (mailing) {
144 return crmApi('MailingJob', 'get', {mailing_id: mailing.id, is_test: 0})
145 .then(function (jobResult) {
146 mailing.jobs = mailing.jobs || {};
147 angular.extend(mailing.jobs, jobResult.values);
148 });
149 },
150 // @return Object Mailing (per APIv3)
151 create: function create(params) {
152 var defaults = {
153 jobs: {}, // {jobId: JobRecord}
154 recipients: {
155 groups: {include: [], exclude: [], base: []},
156 mailings: {include: [], exclude: []}
157 },
158 template_type: "traditional",
159 // Workaround CRM-19756 w/template_options.nonce
160 template_options: {nonce: 1},
161 name: "",
162 campaign_id: null,
163 replyto_email: "",
164 subject: "",
165 body_html: "",
166 body_text: ""
167 };
168 return angular.extend({}, defaults, params);
169 },
170
171 // @param mailing Object (per APIv3)
172 // @return Promise
173 'delete': function (mailing) {
174 if (mailing.id) {
175 return qApi('Mailing', 'delete', {id: mailing.id});
176 }
177 else {
178 var d = $q.defer();
179 d.resolve();
180 return d.promise;
181 }
182 },
183
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]) && !CRM.crmMailing.disableMandatoryTokensCheck) {
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 });
214 if (count === 0) {
215 angular.extend(missing, value);
216 }
217 }
218 });
219 }
220 return missing;
221 },
222
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 = [
227 // always exclude: 'id'
228 'name',
229 'campaign_id',
230 'from_name',
231 'from_email',
232 'replyto_email',
233 'subject',
234 'dedupe_email',
235 'recipients',
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 }
259 });
260 },
261
262 // @param mailing Object (per APIv3)
263 // @return Promise an object with "subject", "body_text", "body_html"
264 preview: function preview(mailing) {
265 if (CRM.crmMailing.workflowEnabled && !CRM.checkPerm('create mailings') && !CRM.checkPerm('access CiviMail')) {
266 return qApi('Mailing', 'preview', {id: mailing.id}).then(function(result) {
267 return result.values;
268 });
269 }
270 else {
271 // Protect against races in saving and previewing by chaining create+preview.
272 var params = angular.extend({}, mailing, mailing.recipients, {
273 id: mailing.id,
274 'api.Mailing.preview': {
275 id: '$value.id'
276 }
277 });
278 delete params.recipients; // the content was merged in
279 params._skip_evil_bao_auto_recipients_ = 1; // skip recipient rebuild on mail preview
280 return qApi('Mailing', 'create', params).then(function(result) {
281 mailing.modified_date = result.values[result.id].modified_date;
282 // changes rolled back, so we don't care about updating mailing
283 return result.values[result.id]['api.Mailing.preview'].values;
284 });
285 }
286 },
287
288 // @param mailing Object (per APIv3)
289 // @param int previewLimit
290 // @return Promise for a list of recipients (mailing_id, contact_id, api.contact.getvalue, api.email.getvalue)
291 previewRecipients: function previewRecipients(mailing, previewLimit) {
292 // To get list of recipients, we tentatively save the mailing and
293 // get the resulting recipients -- then rollback any changes.
294 var params = angular.extend({}, mailing.recipients, {
295 id: mailing.id,
296 'api.MailingRecipients.get': {
297 mailing_id: '$value.id',
298 options: {limit: previewLimit},
299 'api.contact.getvalue': {'return': 'display_name'},
300 'api.email.getvalue': {'return': 'email'}
301 }
302 });
303 delete params.recipients; // the content was merged in
304 return qApi('Mailing', 'create', params).then(function (recipResult) {
305 // changes rolled back, so we don't care about updating mailing
306 mailing.modified_date = recipResult.values[recipResult.id].modified_date;
307 return recipResult.values[recipResult.id]['api.MailingRecipients.get'].values;
308 });
309 },
310
311 previewRecipientCount: function previewRecipientCount(mailing, crmMailingCache, rebuild) {
312 var cachekey = 'mailing-' + mailing.id + '-recipient-count';
313 var recipientCount = crmMailingCache.get(cachekey);
314 if (rebuild || _.isEmpty(recipientCount)) {
315 // To get list of recipients, we tentatively save the mailing and
316 // get the resulting recipients -- then rollback any changes.
317 var params = angular.extend({}, mailing, mailing.recipients, {
318 id: mailing.id,
319 'api.MailingRecipients.getcount': {
320 mailing_id: '$value.id'
321 }
322 });
323 // if this service is executed on rebuild then also fetch the recipients list
324 if (rebuild) {
325 params = angular.extend(params, {
326 'api.MailingRecipients.get': {
327 mailing_id: '$value.id',
328 options: {limit: 50},
329 'api.contact.getvalue': {'return': 'display_name'},
330 'api.email.getvalue': {'return': 'email'}
331 }
332 });
333 crmMailingCache.put('mailing-' + mailing.id + '-recipient-params', params.recipients);
334 }
335 delete params.recipients; // the content was merged in
336 recipientCount = qApi('Mailing', 'create', params).then(function (recipResult) {
337 // changes rolled back, so we don't care about updating mailing
338 mailing.modified_date = recipResult.values[recipResult.id].modified_date;
339 if (rebuild) {
340 crmMailingCache.put('mailing-' + mailing.id + '-recipient-list', recipResult.values[recipResult.id]['api.MailingRecipients.get'].values);
341 }
342 return recipResult.values[recipResult.id]['api.MailingRecipients.getcount'];
343 });
344 crmMailingCache.put(cachekey, recipientCount);
345 }
346
347 return recipientCount;
348 },
349
350 // Save a (draft) mailing
351 // @param mailing Object (per APIv3)
352 // @return Promise
353 save: function(mailing) {
354 var params = angular.extend({}, mailing, mailing.recipients);
355
356 // Angular ngModel sometimes treats blank fields as undefined.
357 angular.forEach(mailing, function(value, key) {
358 if (value === undefined || value === null) {
359 mailing[key] = '';
360 }
361 });
362
363 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
364 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
365 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
366 delete params.scheduled_date;
367
368 delete params.jobs;
369
370 delete params.recipients; // the content was merged in
371 params._skip_evil_bao_auto_recipients_ = 1; // skip recipient rebuild on simple save
372 return qApi('Mailing', 'create', params).then(function(result) {
373 if (result.id && !mailing.id) {
374 mailing.id = result.id;
375 } // no rollback, so update mailing.id
376 // Perhaps we should reload mailing based on result?
377 mailing.modified_date = result.values[result.id].modified_date;
378 return mailing;
379 });
380 },
381
382 // Schedule/send the mailing
383 // @param mailing Object (per APIv3)
384 // @return Promise
385 submit: function (mailing) {
386 var crmMailingMgr = this;
387 var params = {
388 id: mailing.id,
389 approval_date: 'now',
390 scheduled_date: mailing.scheduled_date ? mailing.scheduled_date : 'now'
391 };
392 return qApi('Mailing', 'submit', params)
393 .then(function (result) {
394 angular.extend(mailing, result.values[result.id]); // Perhaps we should reload mailing based on result?
395 return crmMailingMgr._loadJobs(mailing);
396 })
397 .then(function () {
398 return mailing;
399 });
400 },
401
402 // Immediately send a test message
403 // @param mailing Object (per APIv3)
404 // @param to Object with either key "email" (string) or "gid" (int)
405 // @return Promise for a list of delivery reports
406 sendTest: function (mailing, recipient) {
407 var params = angular.extend({}, mailing, mailing.recipients, {
408 // options: {force_rollback: 1}, // Test mailings include tracking features, so the mailing must be persistent
409 'api.Mailing.send_test': {
410 mailing_id: '$value.id',
411 test_email: recipient.email,
412 test_group: recipient.gid
413 }
414 });
415
416 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
417 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
418 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
419 delete params.scheduled_date;
420
421 delete params.jobs;
422
423 delete params.recipients; // the content was merged in
424
425 params._skip_evil_bao_auto_recipients_ = 1; // skip recipient rebuild while sending test mail
426
427 return qApi('Mailing', 'create', params).then(function (result) {
428 if (result.id && !mailing.id) {
429 mailing.id = result.id;
430 } // no rollback, so update mailing.id
431 mailing.modified_date = result.values[result.id].modified_date;
432 return result.values[result.id]['api.Mailing.send_test'].values;
433 });
434 }
435 };
436 });
437
438 // The preview manager performs preview actions while putting up a visible UI (e.g. dialogs & status alerts)
439 angular.module('crmMailing').factory('crmMailingPreviewMgr', function (dialogService, crmMailingMgr, crmStatus) {
440 return {
441 // @param mode string one of 'html', 'text', or 'full'
442 // @return Promise
443 preview: function preview(mailing, mode) {
444 var templates = {
445 html: '~/crmMailing/PreviewMgr/html.html',
446 text: '~/crmMailing/PreviewMgr/text.html',
447 full: '~/crmMailing/PreviewMgr/full.html'
448 };
449 var result = null;
450 var p = crmMailingMgr
451 .preview(mailing)
452 .then(function (content) {
453 var options = CRM.utils.adjustDialogDefaults({
454 autoOpen: false,
455 title: ts('Subject: %1', {
456 1: content.subject
457 })
458 });
459 result = dialogService.open('previewDialog', templates[mode], content, options);
460 });
461 crmStatus({start: ts('Previewing...'), success: ''}, p);
462 return result;
463 },
464
465 // @param to Object with either key "email" (string) or "gid" (int)
466 // @return Promise
467 sendTest: function sendTest(mailing, recipient) {
468 var promise = crmMailingMgr.sendTest(mailing, recipient)
469 .then(function (deliveryInfos) {
470 var count = Object.keys(deliveryInfos).length;
471 if (count === 0) {
472 CRM.alert(ts('Could not identify any recipients. Perhaps the group is empty?'));
473 }
474 })
475 ;
476 return crmStatus({start: ts('Sending...'), success: ts('Sent')}, promise);
477 }
478 };
479 });
480
481 angular.module('crmMailing').factory('crmMailingStats', function (crmApi, crmLegacy) {
482 var statTypes = [
483 // {name: 'Recipients', title: ts('Intended Recipients'), searchFilter: '', eventsFilter: '&event=queue', reportType: 'detail', reportFilter: ''},
484 {name: 'Delivered', title: ts('Successful Deliveries'), searchFilter: '&mailing_delivery_status=Y', eventsFilter: '&event=delivered', reportType: 'detail', reportFilter: '&delivery_status_value=successful'},
485 {name: 'Opened', title: ts('Tracked Opens'), searchFilter: '&mailing_open_status=Y', eventsFilter: '&event=opened', reportType: 'opened', reportFilter: ''},
486 {name: 'Unique Clicks', title: ts('Click-throughs'), searchFilter: '&mailing_click_status=Y', eventsFilter: '&event=click&distinct=1', reportType: 'clicks', reportFilter: ''},
487 // {name: 'Forward', title: ts('Forwards'), searchFilter: '&mailing_forward=1', eventsFilter: '&event=forward', reportType: 'detail', reportFilter: '&is_forwarded_value=1'},
488 // {name: 'Replies', title: ts('Replies'), searchFilter: '&mailing_reply_status=Y', eventsFilter: '&event=reply', reportType: 'detail', reportFilter: '&is_replied_value=1'},
489 {name: 'Bounces', title: ts('Bounces'), searchFilter: '&mailing_delivery_status=N', eventsFilter: '&event=bounce', reportType: 'bounce', reportFilter: ''},
490 {name: 'Unsubscribers', title: ts('Unsubscribes'), searchFilter: '&mailing_unsubscribe=1', eventsFilter: '&event=unsubscribe', reportType: 'detail', reportFilter: '&is_unsubscribed_value=1'},
491 // {name: 'OptOuts', title: ts('Opt-Outs'), searchFilter: '&mailing_optout=1', eventsFilter: '&event=optout', reportType: 'detail', reportFilter: ''}
492 ];
493
494 return {
495 getStatTypes: function() {
496 return statTypes;
497 },
498
499 /**
500 * @param mailingIds object
501 * List of mailing IDs ({a: 123, b: 456})
502 * @return Promise
503 * List of stats for each mailing
504 * ({a: ...object..., b: ...object...})
505 */
506 getStats: function(mailingIds) {
507 var params = {};
508 angular.forEach(mailingIds, function(mailingId, name) {
509 params[name] = ['Mailing', 'stats', {mailing_id: mailingId, is_distinct: 0}];
510 });
511 return crmApi(params).then(function(result) {
512 var stats = {};
513 angular.forEach(mailingIds, function(mailingId, name) {
514 stats[name] = result[name].values[mailingId];
515 });
516 return stats;
517 });
518 },
519
520 /**
521 * Determine the legacy URL for a report about a given mailing and stat.
522 *
523 * @param mailing object
524 * @param statType object (see statTypes above)
525 * @param view string ('search', 'event', 'report')
526 * @param returnPath string|null Return path (relative to Angular base)
527 * @return string|null
528 */
529 getUrl: function getUrl(mailing, statType, view, returnPath) {
530 switch (view) {
531 case 'events':
532 var retParams = returnPath ? '&context=angPage&angPage=' + returnPath : '';
533 return crmLegacy.url('civicrm/mailing/report/event',
534 'reset=1&mid=' + mailing.id + statType.eventsFilter + retParams);
535 case 'search':
536 return crmLegacy.url('civicrm/contact/search/advanced',
537 'force=1&mailing_id=' + mailing.id + statType.searchFilter);
538 case 'report':
539 var reportIds = CRM.crmMailing.reportIds;
540 return crmLegacy.url('civicrm/report/instance/' + reportIds[statType.reportType],
541 'reset=1&mailing_id_value=' + mailing.id + statType.reportFilter);
542 default:
543 return null;
544 }
545 }
546 };
547 });
548
549 // crmMailingSimpleDirective is a template/factory-function for constructing very basic
550 // directives that accept a "mailing" argument. Please don't overload it. If one continues building
551 // this, it risks becoming a second system that violates Angular architecture (and prevents one
552 // from using standard Angular docs+plugins). So this really shouldn't do much -- it is really
553 // only for simple directives. For something complex, suck it up and write 10 lines of boilerplate.
554 angular.module('crmMailing').factory('crmMailingSimpleDirective', function ($q, crmMetadata, crmUiHelp) {
555 return function crmMailingSimpleDirective(directiveName, templateUrl) {
556 return {
557 scope: {
558 crmMailing: '@'
559 },
560 templateUrl: templateUrl,
561 link: function (scope, elm, attr) {
562 scope.$parent.$watch(attr.crmMailing, function(newValue){
563 scope.mailing = newValue;
564 });
565 scope.crmMailingConst = CRM.crmMailing;
566 scope.ts = CRM.ts(null);
567 scope.hs = crmUiHelp({file: 'CRM/Mailing/MailingUI'});
568 scope[directiveName] = attr[directiveName] ? scope.$parent.$eval(attr[directiveName]) : {};
569 $q.when(crmMetadata.getFields('Mailing'), function(fields) {
570 scope.mailingFields = fields;
571 });
572 }
573 };
574 };
575 });
576
577 angular.module('crmMailing').factory('crmMailingCache', ['$cacheFactory', function($cacheFactory) {
578 return $cacheFactory('crmMailingCache');
579 }]);
580
581 })(angular, CRM.$, CRM._);