1 (function (angular
, $, _
) {
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"
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)'
17 function first(array
) {
18 return (array
.length
=== 0) ? null : array
[0];
22 getAll
: function getAll() {
25 getByAuthorEmail
: function getByAuthorEmail(author
, email
, autocreate
) {
27 _
.each(addrs
, function (addr
) {
28 if (addr
.author
== author
&& addr
.email
== email
) {
32 if (!result
&& autocreate
) {
34 label
: '(INVALID) "' + author
+ '" <' + email
+ '>',
42 getByEmail
: function getByEmail(email
) {
43 return first(_
.where(addrs
, {email
: email
}));
45 getByLabel: function (label
) {
46 return first(_
.where(addrs
, {label
: label
}));
48 getDefault
: function getDefault() {
49 return first(_
.where(addrs
, {is_default
: "1"}));
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)
61 var lastModifiedTpl
= null;
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",
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
) {
78 tpl
.id
= '' + response
.id
; //parseInt(response.id);
81 lastModifiedTpl
= tpl
;
85 // @return Object MessageTemplate (per APIv3)
86 getLastModifiedTpl: function () {
87 return lastModifiedTpl
;
89 getAll
: function getAll() {
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
,
103 return (mcs
.length
>= 1) ? mcs
[0].id
: null;
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
);
112 // @return Promise Mailing (per APIv3)
113 get: function get(id
) {
114 var crmMailingMgr
= this;
116 return qApi('Mailing', 'getsingle', {id
: id
})
117 .then(function (getResult
) {
120 crmMailingMgr
._loadGroups(mailing
),
121 crmMailingMgr
._loadJobs(mailing
)
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
);
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
);
150 // @return Object Mailing (per APIv3)
151 create
: function create(params
) {
153 jobs
: {}, // {jobId: JobRecord}
155 groups
: {include
: [], exclude
: [], base
: []},
156 mailings
: {include
: [], exclude
: []}
158 template_type
: "traditional",
159 // Workaround CRM-19756 w/template_options.nonce
160 template_options
: {nonce
: 1},
168 return angular
.extend({}, defaults
, params
);
171 // @param mailing Object (per APIv3)
173 'delete': function (mailing
) {
175 return qApi('Mailing', 'delete', {id
: mailing
.id
});
184 // Search the body, header, and footer for required tokens.
185 // ex: var msgs = findMissingTokens(mailing, 'body_html');
186 findMissingTokens: function(mailing
, field
) {
188 if (!_
.isEmpty(mailing
[field
]) && !CRM
.crmMailing
.disableMandatoryTokensCheck
) {
190 if (mailing
.footer_id
) {
191 var footer
= _
.where(CRM
.crmMailing
.headerfooterList
, {id
: mailing
.footer_id
});
192 body
= body
+ footer
[0][field
];
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
];
201 angular
.forEach(CRM
.crmMailing
.requiredTokens
, function(value
, token
) {
202 if (!_
.isObject(value
)) {
203 if (body
.indexOf('{' + token
+ '}') < 0) {
204 missing
[token
] = value
;
209 angular
.forEach(value
, function(nestedValue
, nestedToken
) {
210 if (body
.indexOf('{' + nestedToken
+ '}') >= 0) {
215 angular
.extend(missing
, value
);
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'
255 _
.each(MAILING_FIELDS
, function (field
) {
256 if (!_
.contains(excludes
, field
)) {
257 mailingTgt
[field
] = mailingFrom
[field
];
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
;
271 // Protect against races in saving and previewing by chaining create+preview.
272 var params
= angular
.extend({}, mailing
, mailing
.recipients
, {
273 options
: {force_rollback
: 1},
274 'api.Mailing.preview': {
278 delete params
.recipients
; // the content was merged in
279 return qApi('Mailing', 'create', params
).then(function(result
) {
280 mailing
.modified_date
= result
.values
[result
.id
].modified_date
;
281 // changes rolled back, so we don't care about updating mailing
282 return result
.values
[result
.id
]['api.Mailing.preview'].values
;
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)
290 previewRecipients
: function previewRecipients(mailing
, previewLimit
) {
291 // To get list of recipients, we tentatively save the mailing and
292 // get the resulting recipients -- then rollback any changes.
293 var params
= angular
.extend({}, mailing
, mailing
.recipients
, {
294 name
: 'placeholder', // for previewing recipients on new, incomplete mailing
295 subject
: 'placeholder', // for previewing recipients on new, incomplete mailing
296 options
: {force_rollback
: 1},
297 'api.mailing_job.create': 1, // note: exact match to API default
298 'api.MailingRecipients.get': {
299 mailing_id
: '$value.id',
300 options
: {limit
: previewLimit
},
301 'api.contact.getvalue': {'return': 'display_name'},
302 'api.email.getvalue': {'return': 'email'}
305 delete params
.recipients
; // the content was merged in
306 return qApi('Mailing', 'create', params
).then(function (recipResult
) {
307 // changes rolled back, so we don't care about updating mailing
308 mailing
.modified_date
= recipResult
.values
[recipResult
.id
].modified_date
;
309 return recipResult
.values
[recipResult
.id
]['api.MailingRecipients.get'].values
;
313 previewRecipientCount
: function previewRecipientCount(mailing
, crmMailingCache
, rebuild
) {
314 var cachekey
= 'mailing-' + mailing
.id
+ '-recipient-count';
315 var recipientCount
= crmMailingCache
.get(cachekey
);
316 if (rebuild
|| _
.isEmpty(recipientCount
)) {
317 // To get list of recipients, we tentatively save the mailing and
318 // get the resulting recipients -- then rollback any changes.
319 var params
= angular
.extend({}, mailing
, mailing
.recipients
, {
320 name
: 'placeholder', // for previewing recipients on new, incomplete mailing
321 subject
: 'placeholder', // for previewing recipients on new, incomplete mailing
322 options
: {force_rollback
: 1},
323 'api.mailing_job.create': 1, // note: exact match to API default
324 'api.MailingRecipients.getcount': {
325 mailing_id
: '$value.id'
328 // if this service is executed on rebuild then also fetch the recipients list
330 params
= angular
.extend(params
, {
331 'api.MailingRecipients.get': {
332 mailing_id
: '$value.id',
333 options
: {limit
: 50},
334 'api.contact.getvalue': {'return': 'display_name'},
335 'api.email.getvalue': {'return': 'email'}
338 crmMailingCache
.put('mailing-' + mailing
.id
+ '-recipient-params', params
.recipients
);
340 delete params
.recipients
; // the content was merged in
341 recipientCount
= qApi('Mailing', 'create', params
).then(function (recipResult
) {
342 // changes rolled back, so we don't care about updating mailing
343 mailing
.modified_date
= recipResult
.values
[recipResult
.id
].modified_date
;
345 crmMailingCache
.put('mailing-' + mailing
.id
+ '-recipient-list', recipResult
.values
[recipResult
.id
]['api.MailingRecipients.get'].values
);
347 return recipResult
.values
[recipResult
.id
]['api.MailingRecipients.getcount'];
349 crmMailingCache
.put(cachekey
, recipientCount
);
352 return recipientCount
;
355 // Save a (draft) mailing
356 // @param mailing Object (per APIv3)
358 save: function(mailing
) {
359 var params
= angular
.extend({}, mailing
, mailing
.recipients
);
361 // Angular ngModel sometimes treats blank fields as undefined.
362 angular
.forEach(mailing
, function(value
, key
) {
363 if (value
=== undefined || value
=== null) {
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
;
375 delete params
.recipients
; // the content was merged in
377 return qApi('Mailing', 'create', params
).then(function(result
) {
378 if (result
.id
&& !mailing
.id
) {
379 mailing
.id
= result
.id
;
380 } // no rollback, so update mailing.id
381 // Perhaps we should reload mailing based on result?
382 mailing
.modified_date
= result
.values
[result
.id
].modified_date
;
387 // Schedule/send the mailing
388 // @param mailing Object (per APIv3)
390 submit: function (mailing
) {
391 var crmMailingMgr
= this;
394 approval_date
: 'now',
395 scheduled_date
: mailing
.scheduled_date
? mailing
.scheduled_date
: 'now'
397 return qApi('Mailing', 'submit', params
)
398 .then(function (result
) {
399 angular
.extend(mailing
, result
.values
[result
.id
]); // Perhaps we should reload mailing based on result?
400 return crmMailingMgr
._loadJobs(mailing
);
407 // Immediately send a test message
408 // @param mailing Object (per APIv3)
409 // @param to Object with either key "email" (string) or "gid" (int)
410 // @return Promise for a list of delivery reports
411 sendTest: function (mailing
, recipient
) {
412 var params
= angular
.extend({}, mailing
, mailing
.recipients
, {
413 // options: {force_rollback: 1}, // Test mailings include tracking features, so the mailing must be persistent
414 'api.Mailing.send_test': {
415 mailing_id
: '$value.id',
416 test_email
: recipient
.email
,
417 test_group
: recipient
.gid
421 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
422 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
423 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
424 delete params
.scheduled_date
;
428 delete params
.recipients
; // the content was merged in
430 return qApi('Mailing', 'create', params
).then(function (result
) {
431 if (result
.id
&& !mailing
.id
) {
432 mailing
.id
= result
.id
;
433 } // no rollback, so update mailing.id
434 mailing
.modified_date
= result
.values
[result
.id
].modified_date
;
435 return result
.values
[result
.id
]['api.Mailing.send_test'].values
;
441 // The preview manager performs preview actions while putting up a visible UI (e.g. dialogs & status alerts)
442 angular
.module('crmMailing').factory('crmMailingPreviewMgr', function (dialogService
, crmMailingMgr
, crmStatus
) {
444 // @param mode string one of 'html', 'text', or 'full'
446 preview
: function preview(mailing
, mode
) {
448 html
: '~/crmMailing/PreviewMgr/html.html',
449 text
: '~/crmMailing/PreviewMgr/text.html',
450 full
: '~/crmMailing/PreviewMgr/full.html'
453 var p
= crmMailingMgr
455 .then(function (content
) {
456 var options
= CRM
.utils
.adjustDialogDefaults({
458 title
: ts('Subject: %1', {
462 result
= dialogService
.open('previewDialog', templates
[mode
], content
, options
);
464 crmStatus({start
: ts('Previewing...'), success
: ''}, p
);
468 // @param to Object with either key "email" (string) or "gid" (int)
470 sendTest
: function sendTest(mailing
, recipient
) {
471 var promise
= crmMailingMgr
.sendTest(mailing
, recipient
)
472 .then(function (deliveryInfos
) {
473 var count
= Object
.keys(deliveryInfos
).length
;
475 CRM
.alert(ts('Could not identify any recipients. Perhaps the group is empty?'));
479 return crmStatus({start
: ts('Sending...'), success
: ts('Sent')}, promise
);
484 angular
.module('crmMailing').factory('crmMailingStats', function (crmApi
, crmLegacy
) {
486 // {name: 'Recipients', title: ts('Intended Recipients'), searchFilter: '', eventsFilter: '&event=queue', reportType: 'detail', reportFilter: ''},
487 {name
: 'Delivered', title
: ts('Successful Deliveries'), searchFilter
: '&mailing_delivery_status=Y', eventsFilter
: '&event=delivered', reportType
: 'detail', reportFilter
: '&delivery_status_value=successful'},
488 {name
: 'Opened', title
: ts('Tracked Opens'), searchFilter
: '&mailing_open_status=Y', eventsFilter
: '&event=opened', reportType
: 'opened', reportFilter
: ''},
489 {name
: 'Unique Clicks', title
: ts('Click-throughs'), searchFilter
: '&mailing_click_status=Y', eventsFilter
: '&event=click&distinct=1', reportType
: 'clicks', reportFilter
: ''},
490 // {name: 'Forward', title: ts('Forwards'), searchFilter: '&mailing_forward=1', eventsFilter: '&event=forward', reportType: 'detail', reportFilter: '&is_forwarded_value=1'},
491 // {name: 'Replies', title: ts('Replies'), searchFilter: '&mailing_reply_status=Y', eventsFilter: '&event=reply', reportType: 'detail', reportFilter: '&is_replied_value=1'},
492 {name
: 'Bounces', title
: ts('Bounces'), searchFilter
: '&mailing_delivery_status=N', eventsFilter
: '&event=bounce', reportType
: 'bounce', reportFilter
: ''},
493 {name
: 'Unsubscribers', title
: ts('Unsubscribes'), searchFilter
: '&mailing_unsubscribe=1', eventsFilter
: '&event=unsubscribe', reportType
: 'detail', reportFilter
: '&is_unsubscribed_value=1'},
494 // {name: 'OptOuts', title: ts('Opt-Outs'), searchFilter: '&mailing_optout=1', eventsFilter: '&event=optout', reportType: 'detail', reportFilter: ''}
498 getStatTypes: function() {
503 * @param mailingIds object
504 * List of mailing IDs ({a: 123, b: 456})
506 * List of stats for each mailing
507 * ({a: ...object..., b: ...object...})
509 getStats: function(mailingIds
) {
511 angular
.forEach(mailingIds
, function(mailingId
, name
) {
512 params
[name
] = ['Mailing', 'stats', {mailing_id
: mailingId
, is_distinct
: 0}];
514 return crmApi(params
).then(function(result
) {
516 angular
.forEach(mailingIds
, function(mailingId
, name
) {
517 stats
[name
] = result
[name
].values
[mailingId
];
524 * Determine the legacy URL for a report about a given mailing and stat.
526 * @param mailing object
527 * @param statType object (see statTypes above)
528 * @param view string ('search', 'event', 'report')
529 * @param returnPath string|null Return path (relative to Angular base)
530 * @return string|null
532 getUrl
: function getUrl(mailing
, statType
, view
, returnPath
) {
535 var retParams
= returnPath
? '&context=angPage&angPage=' + returnPath
: '';
536 return crmLegacy
.url('civicrm/mailing/report/event',
537 'reset=1&mid=' + mailing
.id
+ statType
.eventsFilter
+ retParams
);
539 return crmLegacy
.url('civicrm/contact/search/advanced',
540 'force=1&mailing_id=' + mailing
.id
+ statType
.searchFilter
);
542 var reportIds
= CRM
.crmMailing
.reportIds
;
543 return crmLegacy
.url('civicrm/report/instance/' + reportIds
[statType
.reportType
],
544 'reset=1&mailing_id_value=' + mailing
.id
+ statType
.reportFilter
);
552 // crmMailingSimpleDirective is a template/factory-function for constructing very basic
553 // directives that accept a "mailing" argument. Please don't overload it. If one continues building
554 // this, it risks becoming a second system that violates Angular architecture (and prevents one
555 // from using standard Angular docs+plugins). So this really shouldn't do much -- it is really
556 // only for simple directives. For something complex, suck it up and write 10 lines of boilerplate.
557 angular
.module('crmMailing').factory('crmMailingSimpleDirective', function ($q
, crmMetadata
, crmUiHelp
) {
558 return function crmMailingSimpleDirective(directiveName
, templateUrl
) {
563 templateUrl
: templateUrl
,
564 link: function (scope
, elm
, attr
) {
565 scope
.$parent
.$watch(attr
.crmMailing
, function(newValue
){
566 scope
.mailing
= newValue
;
568 scope
.crmMailingConst
= CRM
.crmMailing
;
569 scope
.ts
= CRM
.ts(null);
570 scope
.hs
= crmUiHelp({file
: 'CRM/Mailing/MailingUI'});
571 scope
[directiveName
] = attr
[directiveName
] ? scope
.$parent
.$eval(attr
[directiveName
]) : {};
572 $q
.when(crmMetadata
.getFields('Mailing'), function(fields
) {
573 scope
.mailingFields
= fields
;
580 angular
.module('crmMailing').factory('crmMailingCache', ['$cacheFactory', function($cacheFactory
) {
581 return $cacheFactory('crmMailingCache');
584 })(angular
, CRM
.$, CRM
._
);