Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-07-27-10-02-15
[civicrm-core.git] / ang / 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
36768f7e
TO
100 angular.module('crmMailing').factory('crmMailingMgr', function ($q, crmApi, crmFromAddresses, crmQueue) {
101 var qApi = crmQueue(crmApi);
4dd19229 102 var pickDefaultMailComponent = function pickDefaultMailComponent(type) {
8dfd5110 103 var mcs = _.where(CRM.crmMailing.headerfooterList, {
f4f103fa 104 component_type: type,
8dfd5110
TO
105 is_default: "1"
106 });
107 return (mcs.length >= 1) ? mcs[0].id : null;
108 };
109
110 return {
111 // @param scalar idExpr a number or the literal string 'new'
112 // @return Promise|Object Mailing (per APIv3)
4dd19229 113 getOrCreate: function getOrCreate(idExpr) {
8dfd5110
TO
114 return (idExpr == 'new') ? this.create() : this.get(idExpr);
115 },
116 // @return Promise Mailing (per APIv3)
4dd19229 117 get: function get(id) {
86c3a327
TO
118 var crmMailingMgr = this;
119 var mailing;
36768f7e 120 return qApi('Mailing', 'getsingle', {id: id})
86c3a327
TO
121 .then(function (getResult) {
122 mailing = getResult;
123 return $q.all([
124 crmMailingMgr._loadGroups(mailing),
125 crmMailingMgr._loadJobs(mailing)
126 ]);
127 })
128 .then(function () {
129 return mailing;
130 });
131 },
132 // Call MailingGroup.get and merge results into "mailing"
133 _loadGroups: function (mailing) {
134 return crmApi('MailingGroup', 'get', {mailing_id: mailing.id})
135 .then(function (groupResult) {
9cd4f489 136 mailing.recipients = {};
720c658b 137 mailing.recipients.groups = {include: [], exclude: [], base: []};
9cd4f489 138 mailing.recipients.mailings = {include: [], exclude: []};
f4f103fa 139 _.each(groupResult.values, function (mailingGroup) {
f78abdbe 140 var bucket = (/^civicrm_group/.test(mailingGroup.entity_table)) ? 'groups' : 'mailings';
89a50c67 141 var entityId = parseInt(mailingGroup.entity_id);
9cd4f489 142 mailing.recipients[bucket][mailingGroup.group_type.toLowerCase()].push(entityId);
8dfd5110 143 });
8dfd5110 144 });
86c3a327
TO
145 },
146 // Call MailingJob.get and merge results into "mailing"
147 _loadJobs: function (mailing) {
148 return crmApi('MailingJob', 'get', {mailing_id: mailing.id, is_test: 0})
149 .then(function (jobResult) {
150 mailing.jobs = mailing.jobs || {};
151 angular.extend(mailing.jobs, jobResult.values);
152 });
8dfd5110
TO
153 },
154 // @return Object Mailing (per APIv3)
657b8692
TO
155 create: function create(params) {
156 var defaults = {
86c3a327 157 jobs: {}, // {jobId: JobRecord}
9cd4f489 158 recipients: {
720c658b
TO
159 groups: {include: [], exclude: [], base: []},
160 mailings: {include: [], exclude: []}
9cd4f489 161 },
d78cc635 162 name: "",
8dfd5110 163 campaign_id: null,
8dfd5110 164 replyto_email: "",
d78cc635 165 subject: "",
13782061 166 body_html: "",
657b8692 167 body_text: ""
8dfd5110 168 };
657b8692 169 return angular.extend({}, defaults, params);
8dfd5110
TO
170 },
171
705c61e9
TO
172 // @param mailing Object (per APIv3)
173 // @return Promise
f4f103fa 174 'delete': function (mailing) {
705c61e9 175 if (mailing.id) {
36768f7e 176 return qApi('Mailing', 'delete', {id: mailing.id});
f4f103fa
TO
177 }
178 else {
705c61e9
TO
179 var d = $q.defer();
180 d.resolve();
181 return d.promise;
182 }
183 },
184
21fb26b8
TO
185 // Search the body, header, and footer for required tokens.
186 // ex: var msgs = findMissingTokens(mailing, 'body_html');
187 findMissingTokens: function(mailing, field) {
188 var missing = {};
d124a91f 189 if (!_.isEmpty(mailing[field]) && !CRM.crmMailing.disableMandatoryTokensCheck) {
21fb26b8
TO
190 var body = '';
191 if (mailing.footer_id) {
192 var footer = _.where(CRM.crmMailing.headerfooterList, {id: mailing.footer_id});
193 body = body + footer[0][field];
194
195 }
196 body = body + mailing[field];
197 if (mailing.header_id) {
198 var header = _.where(CRM.crmMailing.headerfooterList, {id: mailing.header_id});
199 body = body + header[0][field];
200 }
201
202 angular.forEach(CRM.crmMailing.requiredTokens, function(value, token) {
203 if (!_.isObject(value)) {
204 if (body.indexOf('{' + token + '}') < 0) {
205 missing[token] = value;
206 }
207 }
208 else {
209 var count = 0;
210 angular.forEach(value, function(nestedValue, nestedToken) {
211 if (body.indexOf('{' + nestedToken + '}') >= 0) {
212 count++;
213 }
214 });
d03e0d13 215 if (count === 0) {
21fb26b8
TO
216 angular.extend(missing, value);
217 }
218 }
219 });
220 }
221 return missing;
222 },
223
07fa6426
TO
224 // Copy all data fields in (mailingFrom) to (mailingTgt) -- except for (excludes)
225 // ex: crmMailingMgr.mergeInto(newMailing, mailingTemplate, ['subject']);
226 mergeInto: function mergeInto(mailingTgt, mailingFrom, excludes) {
227 var MAILING_FIELDS = [
70980d8e 228 // always exclude: 'id'
07fa6426
TO
229 'name',
230 'campaign_id',
231 'from_name',
232 'from_email',
233 'replyto_email',
234 'subject',
235 'dedupe_email',
9cd4f489 236 'recipients',
07fa6426
TO
237 'body_html',
238 'body_text',
239 'footer_id',
240 'header_id',
241 'visibility',
242 'url_tracking',
243 'dedupe_email',
244 'forward_replies',
245 'auto_responder',
246 'open_tracking',
247 'override_verp',
248 'optout_id',
249 'reply_id',
250 'resubscribe_id',
251 'unsubscribe_id'
252 ];
253 if (!excludes) {
254 excludes = [];
255 }
256 _.each(MAILING_FIELDS, function (field) {
257 if (!_.contains(excludes, field)) {
258 mailingTgt[field] = mailingFrom[field];
259 }
f2bad133 260 });
07fa6426
TO
261 },
262
493eb47a
TO
263 // @param mailing Object (per APIv3)
264 // @return Promise an object with "subject", "body_text", "body_html"
265 preview: function preview(mailing) {
360d6097 266 if (CRM.crmMailing.workflowEnabled && !CRM.checkPerm('create mailings') && !CRM.checkPerm('access CiviMail')) {
36768f7e 267 return qApi('Mailing', 'preview', {id: mailing.id}).then(function(result) {
3efe22a0
TO
268 return result.values;
269 });
270 }
271 else {
272 // Protect against races in saving and previewing by chaining create+preview.
273 var params = angular.extend({}, mailing, mailing.recipients, {
274 options: {force_rollback: 1},
275 'api.Mailing.preview': {
276 id: '$value.id'
277 }
278 });
279 delete params.recipients; // the content was merged in
36768f7e 280 return qApi('Mailing', 'create', params).then(function(result) {
3efe22a0
TO
281 // changes rolled back, so we don't care about updating mailing
282 return result.values[result.id]['api.Mailing.preview'].values;
283 });
284 }
493eb47a
TO
285 },
286
8dfd5110
TO
287 // @param mailing Object (per APIv3)
288 // @param int previewLimit
289 // @return Promise for a list of recipients (mailing_id, contact_id, api.contact.getvalue, api.email.getvalue)
4dd19229 290 previewRecipients: function previewRecipients(mailing, previewLimit) {
8dfd5110
TO
291 // To get list of recipients, we tentatively save the mailing and
292 // get the resulting recipients -- then rollback any changes.
9cd4f489 293 var params = angular.extend({}, mailing, mailing.recipients, {
13782061
TO
294 name: 'placeholder', // for previewing recipients on new, incomplete mailing
295 subject: 'placeholder', // for previewing recipients on new, incomplete mailing
f4f103fa 296 options: {force_rollback: 1},
7575b840 297 'api.mailing_job.create': 1, // note: exact match to API default
8dfd5110
TO
298 'api.MailingRecipients.get': {
299 mailing_id: '$value.id',
58dfba8d 300 options: {limit: previewLimit},
8dfd5110
TO
301 'api.contact.getvalue': {'return': 'display_name'},
302 'api.email.getvalue': {'return': 'email'}
303 }
304 });
9cd4f489 305 delete params.recipients; // the content was merged in
36768f7e 306 return qApi('Mailing', 'create', params).then(function (recipResult) {
beab9d1b 307 // changes rolled back, so we don't care about updating mailing
8dfd5110
TO
308 return recipResult.values[recipResult.id]['api.MailingRecipients.get'].values;
309 });
beab9d1b
TO
310 },
311
79d21cce
TO
312 previewRecipientCount: function previewRecipientCount(mailing) {
313 // To get list of recipients, we tentatively save the mailing and
314 // get the resulting recipients -- then rollback any changes.
315 var params = angular.extend({}, mailing, mailing.recipients, {
316 name: 'placeholder', // for previewing recipients on new, incomplete mailing
317 subject: 'placeholder', // for previewing recipients on new, incomplete mailing
318 options: {force_rollback: 1},
319 'api.mailing_job.create': 1, // note: exact match to API default
320 'api.MailingRecipients.getcount': {
321 mailing_id: '$value.id'
322 }
323 });
324 delete params.recipients; // the content was merged in
325 return qApi('Mailing', 'create', params).then(function (recipResult) {
326 // changes rolled back, so we don't care about updating mailing
327 return recipResult.values[recipResult.id]['api.MailingRecipients.getcount'];
328 });
329 },
330
43102e47 331 // Save a (draft) mailing
705c61e9
TO
332 // @param mailing Object (per APIv3)
333 // @return Promise
d78cc635 334 save: function(mailing) {
9cd4f489 335 var params = angular.extend({}, mailing, mailing.recipients);
43102e47 336
d78cc635
TO
337 // Angular ngModel sometimes treats blank fields as undefined.
338 angular.forEach(mailing, function(value, key) {
e72949ef 339 if (value === undefined || value === null) {
d78cc635
TO
340 mailing[key] = '';
341 }
342 });
343
43102e47
TO
344 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
345 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
346 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
347 delete params.scheduled_date;
348
86c3a327
TO
349 delete params.jobs;
350
9cd4f489
TO
351 delete params.recipients; // the content was merged in
352
36768f7e 353 return qApi('Mailing', 'create', params).then(function(result) {
f4f103fa
TO
354 if (result.id && !mailing.id) {
355 mailing.id = result.id;
356 } // no rollback, so update mailing.id
43102e47 357 // Perhaps we should reload mailing based on result?
86c3a327 358 return mailing;
705c61e9
TO
359 });
360 },
361
362 // Schedule/send the mailing
363 // @param mailing Object (per APIv3)
364 // @return Promise
43102e47 365 submit: function (mailing) {
86c3a327 366 var crmMailingMgr = this;
6818346a
TO
367 var params = {
368 id: mailing.id,
d3312ed5 369 approval_date: 'now',
370 scheduled_date: mailing.scheduled_date ? mailing.scheduled_date : 'now'
43102e47 371 };
36768f7e 372 return qApi('Mailing', 'submit', params)
86c3a327
TO
373 .then(function (result) {
374 angular.extend(mailing, result.values[result.id]); // Perhaps we should reload mailing based on result?
375 return crmMailingMgr._loadJobs(mailing);
376 })
377 .then(function () {
378 return mailing;
379 });
705c61e9
TO
380 },
381
382 // Immediately send a test message
beab9d1b 383 // @param mailing Object (per APIv3)
58dfba8d 384 // @param to Object with either key "email" (string) or "gid" (int)
beab9d1b 385 // @return Promise for a list of delivery reports
58dfba8d 386 sendTest: function (mailing, recipient) {
9cd4f489 387 var params = angular.extend({}, mailing, mailing.recipients, {
43102e47 388 // options: {force_rollback: 1}, // Test mailings include tracking features, so the mailing must be persistent
beab9d1b
TO
389 'api.Mailing.send_test': {
390 mailing_id: '$value.id',
58dfba8d
TO
391 test_email: recipient.email,
392 test_group: recipient.gid
beab9d1b
TO
393 }
394 });
43102e47
TO
395
396 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
397 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
398 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
399 delete params.scheduled_date;
400
86c3a327
TO
401 delete params.jobs;
402
9cd4f489
TO
403 delete params.recipients; // the content was merged in
404
36768f7e 405 return qApi('Mailing', 'create', params).then(function (result) {
f4f103fa
TO
406 if (result.id && !mailing.id) {
407 mailing.id = result.id;
408 } // no rollback, so update mailing.id
beab9d1b
TO
409 return result.values[result.id]['api.Mailing.send_test'].values;
410 });
8dfd5110
TO
411 }
412 };
413 });
58dfba8d
TO
414
415 // The preview manager performs preview actions while putting up a visible UI (e.g. dialogs & status alerts)
416 angular.module('crmMailing').factory('crmMailingPreviewMgr', function (dialogService, crmMailingMgr, crmStatus) {
417 return {
418 // @param mode string one of 'html', 'text', or 'full'
419 // @return Promise
420 preview: function preview(mailing, mode) {
421 var templates = {
fd9c35ce
TO
422 html: '~/crmMailing/PreviewMgr/html.html',
423 text: '~/crmMailing/PreviewMgr/text.html',
424 full: '~/crmMailing/PreviewMgr/full.html'
58dfba8d
TO
425 };
426 var result = null;
427 var p = crmMailingMgr
428 .preview(mailing)
429 .then(function (content) {
b1fc510d 430 var options = CRM.utils.adjustDialogDefaults({
58dfba8d 431 autoOpen: false,
58dfba8d
TO
432 title: ts('Subject: %1', {
433 1: content.subject
434 })
b1fc510d 435 });
58dfba8d
TO
436 result = dialogService.open('previewDialog', templates[mode], content, options);
437 });
46233df6 438 crmStatus({start: ts('Previewing...'), success: ''}, p);
58dfba8d
TO
439 return result;
440 },
441
442 // @param to Object with either key "email" (string) or "gid" (int)
443 // @return Promise
444 sendTest: function sendTest(mailing, recipient) {
445 var promise = crmMailingMgr.sendTest(mailing, recipient)
446 .then(function (deliveryInfos) {
447 var count = Object.keys(deliveryInfos).length;
448 if (count === 0) {
449 CRM.alert(ts('Could not identify any recipients. Perhaps the group is empty?'));
450 }
451 })
452 ;
453 return crmStatus({start: ts('Sending...'), success: ts('Sent')}, promise);
454 }
455 };
456 });
457
7173e315
TO
458 angular.module('crmMailing').factory('crmMailingStats', function (crmApi, crmLegacy) {
459 var statTypes = [
460 // {name: 'Recipients', title: ts('Intended Recipients'), searchFilter: '', eventsFilter: '&event=queue'},
461 {name: 'Delivered', title: ts('Successful Deliveries'), searchFilter: '&mailing_delivery_status=Y', eventsFilter: '&event=delivered'},
462 {name: 'Opened', title: ts('Tracked Opens'), searchFilter: '&mailing_open_status=Y', eventsFilter: '&event=opened'},
463 {name: 'Unique Clicks', title: ts('Click-throughs'), searchFilter: '&mailing_click_status=Y', eventsFilter: '&event=click&distinct=1'},
464 // {name: 'Forward', title: ts('Forwards'), searchFilter: '&mailing_forward=1', eventsFilter: '&event=forward'},
465 // {name: 'Replies', title: ts('Replies'), searchFilter: '&mailing_reply_status=Y', eventsFilter: '&event=reply'},
466 {name: 'Bounces', title: ts('Bounces'), searchFilter: '&mailing_delivery_status=N', eventsFilter: '&event=bounce'},
467 {name: 'Unsubscribers', title: ts('Unsubscribes'), searchFilter: '&mailing_unsubscribe=1', eventsFilter: '&event=unsubscribe'}
468 // {name: 'OptOuts', title: ts('Opt-Outs'), searchFilter: '&mailing_optout=1', eventsFilter: '&event=optout'}
469 ];
470
471 return {
472 getStatTypes: function() {
473 return statTypes;
474 },
475
476 /**
477 * @param mailingIds object
478 * List of mailing IDs ({a: 123, b: 456})
479 * @return Promise
480 * List of stats for each mailing
481 * ({a: ...object..., b: ...object...})
482 */
483 getStats: function(mailingIds) {
484 var params = {};
485 angular.forEach(mailingIds, function(mailingId, name) {
486 params[name] = ['Mailing', 'stats', {mailing_id: mailingId}];
487 });
488 return crmApi(params).then(function(result) {
489 var stats = {};
490 angular.forEach(mailingIds, function(mailingId, name) {
491 stats[name] = result[name].values[mailingId];
492 });
493 return stats;
494 });
495 },
496
497 /**
498 * Determine the legacy URL for a report about a given mailing and stat.
499 *
500 * @param mailing object
501 * @param statType object (see statTypes above)
502 * @param view string ('search', 'event', 'report')
05381a97 503 * @param returnPath string|null Return path (relative to Angular base)
7173e315
TO
504 * @return string|null
505 */
05381a97 506 getUrl: function getUrl(mailing, statType, view, returnPath) {
7173e315
TO
507 switch (view) {
508 case 'events':
05381a97 509 var retParams = returnPath ? '&context=angPage&angPage=' + returnPath : '';
7173e315 510 return crmLegacy.url('civicrm/mailing/report/event',
05381a97 511 'reset=1&mid=' + mailing.id + statType.eventsFilter + retParams);
7173e315
TO
512
513 case 'search':
514 return crmLegacy.url('civicrm/contact/search/advanced',
515 'force=1&mailing_id=' + mailing.id + statType.searchFilter);
516
517 // TODO: case 'report':
518 default:
519 return null;
520 }
521 }
522 };
523 });
524
e908a393
TO
525 // crmMailingSimpleDirective is a template/factory-function for constructing very basic
526 // directives that accept a "mailing" argument. Please don't overload it. If one continues building
527 // this, it risks becoming a second system that violates Angular architecture (and prevents one
528 // from using standard Angular docs+plugins). So this really shouldn't do much -- it is really
529 // only for simple directives. For something complex, suck it up and write 10 lines of boilerplate.
530 angular.module('crmMailing').factory('crmMailingSimpleDirective', function ($q, crmMetadata, crmUiHelp) {
531 return function crmMailingSimpleDirective(directiveName, templateUrl) {
532 return {
533 scope: {
534 crmMailing: '@'
535 },
536 templateUrl: templateUrl,
537 link: function (scope, elm, attr) {
538 scope.$parent.$watch(attr.crmMailing, function(newValue){
539 scope.mailing = newValue;
540 });
541 scope.crmMailingConst = CRM.crmMailing;
542 scope.ts = CRM.ts(null);
543 scope.hs = crmUiHelp({file: 'CRM/Mailing/MailingUI'});
544 scope[directiveName] = attr[directiveName] ? scope.$parent.$eval(attr[directiveName]) : {};
545 $q.when(crmMetadata.getFields('Mailing'), function(fields) {
546 scope.mailingFields = fields;
547 });
548 }
549 };
550 };
551 });
552
8dfd5110 553})(angular, CRM.$, CRM._);