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;
63 // @return Promise MessageTemplate (per APIv3)
64 get: function get(id
) {
65 id
= '' + id
; // parseInt(id);
67 var tpl
= _
.where(tpls
, {id
: id
});
68 if (id
&& tpl
&& tpl
[0]) {
77 // @param tpl MessageTemplate (per APIv3) For new templates, omit "id"
78 // @return Promise MessageTemplate (per APIv3)
79 save: function (tpl
) {
80 return crmApi('MessageTemplate', 'create', tpl
).then(function (response
) {
82 tpl
.id
= '' + response
.id
; //parseInt(response.id);
85 lastModifiedTpl
= tpl
;
89 // @return Object MessageTemplate (per APIv3)
90 getLastModifiedTpl: function () {
91 return lastModifiedTpl
;
93 getAll
: function getAll() {
99 // The crmMailingMgr service provides business logic for loading, saving, previewing, etc
100 angular
.module('crmMailing').factory('crmMailingMgr', function ($q
, crmApi
, crmFromAddresses
, crmQueue
) {
101 var qApi
= crmQueue(crmApi
);
102 var pickDefaultMailComponent
= function pickDefaultMailComponent(type
) {
103 var mcs
= _
.where(CRM
.crmMailing
.headerfooterList
, {
104 component_type
: type
,
107 return (mcs
.length
>= 1) ? mcs
[0].id
: null;
111 // @param scalar idExpr a number or the literal string 'new'
112 // @return Promise|Object Mailing (per APIv3)
113 getOrCreate
: function getOrCreate(idExpr
) {
114 return (idExpr
== 'new') ? this.create() : this.get(idExpr
);
116 // @return Promise Mailing (per APIv3)
117 get: function get(id
) {
118 var crmMailingMgr
= this;
120 return qApi('Mailing', 'getsingle', {id
: id
})
121 .then(function (getResult
) {
124 crmMailingMgr
._loadGroups(mailing
),
125 crmMailingMgr
._loadJobs(mailing
)
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
) {
136 mailing
.recipients
= {};
137 mailing
.recipients
.groups
= {include
: [], exclude
: [], base
: []};
138 mailing
.recipients
.mailings
= {include
: [], exclude
: []};
139 _
.each(groupResult
.values
, function (mailingGroup
) {
140 var bucket
= (/^civicrm_group/.test(mailingGroup
.entity_table
)) ? 'groups' : 'mailings';
141 var entityId
= parseInt(mailingGroup
.entity_id
);
142 mailing
.recipients
[bucket
][mailingGroup
.group_type
.toLowerCase()].push(entityId
);
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
);
154 // @return Object Mailing (per APIv3)
155 create
: function create(params
) {
157 jobs
: {}, // {jobId: JobRecord}
159 groups
: {include
: [], exclude
: [], base
: []},
160 mailings
: {include
: [], exclude
: []}
169 return angular
.extend({}, defaults
, params
);
172 // @param mailing Object (per APIv3)
174 'delete': function (mailing
) {
176 return qApi('Mailing', 'delete', {id
: mailing
.id
});
185 // Search the body, header, and footer for required tokens.
186 // ex: var msgs = findMissingTokens(mailing, 'body_html');
187 findMissingTokens: function(mailing
, field
) {
189 if (!_
.isEmpty(mailing
[field
]) && !CRM
.crmMailing
.disableMandatoryTokensCheck
) {
191 if (mailing
.footer_id
) {
192 var footer
= _
.where(CRM
.crmMailing
.headerfooterList
, {id
: mailing
.footer_id
});
193 body
= body
+ footer
[0][field
];
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
];
202 angular
.forEach(CRM
.crmMailing
.requiredTokens
, function(value
, token
) {
203 if (!_
.isObject(value
)) {
204 if (body
.indexOf('{' + token
+ '}') < 0) {
205 missing
[token
] = value
;
210 angular
.forEach(value
, function(nestedValue
, nestedToken
) {
211 if (body
.indexOf('{' + nestedToken
+ '}') >= 0) {
216 angular
.extend(missing
, value
);
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
= [
228 // always exclude: 'id'
256 _
.each(MAILING_FIELDS
, function (field
) {
257 if (!_
.contains(excludes
, field
)) {
258 mailingTgt
[field
] = mailingFrom
[field
];
263 // @param mailing Object (per APIv3)
264 // @return Promise an object with "subject", "body_text", "body_html"
265 preview
: function preview(mailing
) {
266 if (CRM
.crmMailing
.workflowEnabled
&& !CRM
.checkPerm('create mailings') && !CRM
.checkPerm('access CiviMail')) {
267 return qApi('Mailing', 'preview', {id
: mailing
.id
}).then(function(result
) {
268 return result
.values
;
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': {
279 delete params
.recipients
; // the content was merged in
280 return qApi('Mailing', 'create', params
).then(function(result
) {
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 return recipResult
.values
[recipResult
.id
]['api.MailingRecipients.get'].values
;
312 // Save a (draft) mailing
313 // @param mailing Object (per APIv3)
315 save: function(mailing
) {
316 var params
= angular
.extend({}, mailing
, mailing
.recipients
);
318 // Angular ngModel sometimes treats blank fields as undefined.
319 angular
.forEach(mailing
, function(value
, key
) {
320 if (value
=== undefined || value
=== null) {
325 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
326 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
327 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
328 delete params
.scheduled_date
;
332 delete params
.recipients
; // the content was merged in
334 return qApi('Mailing', 'create', params
).then(function(result
) {
335 if (result
.id
&& !mailing
.id
) {
336 mailing
.id
= result
.id
;
337 } // no rollback, so update mailing.id
338 // Perhaps we should reload mailing based on result?
343 // Schedule/send the mailing
344 // @param mailing Object (per APIv3)
346 submit: function (mailing
) {
347 var crmMailingMgr
= this;
350 approval_date
: 'now',
351 scheduled_date
: mailing
.scheduled_date
? mailing
.scheduled_date
: 'now'
353 return qApi('Mailing', 'submit', params
)
354 .then(function (result
) {
355 angular
.extend(mailing
, result
.values
[result
.id
]); // Perhaps we should reload mailing based on result?
356 return crmMailingMgr
._loadJobs(mailing
);
363 // Immediately send a test message
364 // @param mailing Object (per APIv3)
365 // @param to Object with either key "email" (string) or "gid" (int)
366 // @return Promise for a list of delivery reports
367 sendTest: function (mailing
, recipient
) {
368 var params
= angular
.extend({}, mailing
, mailing
.recipients
, {
369 // options: {force_rollback: 1}, // Test mailings include tracking features, so the mailing must be persistent
370 'api.Mailing.send_test': {
371 mailing_id
: '$value.id',
372 test_email
: recipient
.email
,
373 test_group
: recipient
.gid
377 // WORKAROUND: Mailing.create (aka CRM_Mailing_BAO_Mailing::create()) interprets scheduled_date
378 // as an *intent* to schedule and creates tertiary records. Saving a draft with a scheduled_date
379 // is therefore not allowed. Remove this after fixing Mailing.create's contract.
380 delete params
.scheduled_date
;
384 delete params
.recipients
; // the content was merged in
386 return qApi('Mailing', 'create', params
).then(function (result
) {
387 if (result
.id
&& !mailing
.id
) {
388 mailing
.id
= result
.id
;
389 } // no rollback, so update mailing.id
390 return result
.values
[result
.id
]['api.Mailing.send_test'].values
;
396 // The preview manager performs preview actions while putting up a visible UI (e.g. dialogs & status alerts)
397 angular
.module('crmMailing').factory('crmMailingPreviewMgr', function (dialogService
, crmMailingMgr
, crmStatus
) {
399 // @param mode string one of 'html', 'text', or 'full'
401 preview
: function preview(mailing
, mode
) {
403 html
: '~/crmMailing/PreviewMgr/html.html',
404 text
: '~/crmMailing/PreviewMgr/text.html',
405 full
: '~/crmMailing/PreviewMgr/full.html'
408 var p
= crmMailingMgr
410 .then(function (content
) {
411 var options
= CRM
.utils
.adjustDialogDefaults({
413 title
: ts('Subject: %1', {
417 result
= dialogService
.open('previewDialog', templates
[mode
], content
, options
);
419 crmStatus({start
: ts('Previewing'), success
: ''}, p
);
423 // @param to Object with either key "email" (string) or "gid" (int)
425 sendTest
: function sendTest(mailing
, recipient
) {
426 var promise
= crmMailingMgr
.sendTest(mailing
, recipient
)
427 .then(function (deliveryInfos
) {
428 var count
= Object
.keys(deliveryInfos
).length
;
430 CRM
.alert(ts('Could not identify any recipients. Perhaps the group is empty?'));
434 return crmStatus({start
: ts('Sending...'), success
: ts('Sent')}, promise
);
439 angular
.module('crmMailing').factory('crmMailingStats', function (crmApi
, crmLegacy
) {
441 // {name: 'Recipients', title: ts('Intended Recipients'), searchFilter: '', eventsFilter: '&event=queue'},
442 {name
: 'Delivered', title
: ts('Successful Deliveries'), searchFilter
: '&mailing_delivery_status=Y', eventsFilter
: '&event=delivered'},
443 {name
: 'Opened', title
: ts('Tracked Opens'), searchFilter
: '&mailing_open_status=Y', eventsFilter
: '&event=opened'},
444 {name
: 'Unique Clicks', title
: ts('Click-throughs'), searchFilter
: '&mailing_click_status=Y', eventsFilter
: '&event=click&distinct=1'},
445 // {name: 'Forward', title: ts('Forwards'), searchFilter: '&mailing_forward=1', eventsFilter: '&event=forward'},
446 // {name: 'Replies', title: ts('Replies'), searchFilter: '&mailing_reply_status=Y', eventsFilter: '&event=reply'},
447 {name
: 'Bounces', title
: ts('Bounces'), searchFilter
: '&mailing_delivery_status=N', eventsFilter
: '&event=bounce'},
448 {name
: 'Unsubscribers', title
: ts('Unsubscribes'), searchFilter
: '&mailing_unsubscribe=1', eventsFilter
: '&event=unsubscribe'}
449 // {name: 'OptOuts', title: ts('Opt-Outs'), searchFilter: '&mailing_optout=1', eventsFilter: '&event=optout'}
453 getStatTypes: function() {
458 * @param mailingIds object
459 * List of mailing IDs ({a: 123, b: 456})
461 * List of stats for each mailing
462 * ({a: ...object..., b: ...object...})
464 getStats: function(mailingIds
) {
466 angular
.forEach(mailingIds
, function(mailingId
, name
) {
467 params
[name
] = ['Mailing', 'stats', {mailing_id
: mailingId
}];
469 return crmApi(params
).then(function(result
) {
471 angular
.forEach(mailingIds
, function(mailingId
, name
) {
472 stats
[name
] = result
[name
].values
[mailingId
];
479 * Determine the legacy URL for a report about a given mailing and stat.
481 * @param mailing object
482 * @param statType object (see statTypes above)
483 * @param view string ('search', 'event', 'report')
484 * @param returnPath string|null Return path (relative to Angular base)
485 * @return string|null
487 getUrl
: function getUrl(mailing
, statType
, view
, returnPath
) {
490 var retParams
= returnPath
? '&context=angPage&angPage=' + returnPath
: '';
491 return crmLegacy
.url('civicrm/mailing/report/event',
492 'reset=1&mid=' + mailing
.id
+ statType
.eventsFilter
+ retParams
);
495 return crmLegacy
.url('civicrm/contact/search/advanced',
496 'force=1&mailing_id=' + mailing
.id
+ statType
.searchFilter
);
498 // TODO: case 'report':
506 // crmMailingSimpleDirective is a template/factory-function for constructing very basic
507 // directives that accept a "mailing" argument. Please don't overload it. If one continues building
508 // this, it risks becoming a second system that violates Angular architecture (and prevents one
509 // from using standard Angular docs+plugins). So this really shouldn't do much -- it is really
510 // only for simple directives. For something complex, suck it up and write 10 lines of boilerplate.
511 angular
.module('crmMailing').factory('crmMailingSimpleDirective', function ($q
, crmMetadata
, crmUiHelp
) {
512 return function crmMailingSimpleDirective(directiveName
, templateUrl
) {
517 templateUrl
: templateUrl
,
518 link: function (scope
, elm
, attr
) {
519 scope
.$parent
.$watch(attr
.crmMailing
, function(newValue
){
520 scope
.mailing
= newValue
;
522 scope
.crmMailingConst
= CRM
.crmMailing
;
523 scope
.ts
= CRM
.ts(null);
524 scope
.hs
= crmUiHelp({file
: 'CRM/Mailing/MailingUI'});
525 scope
[directiveName
] = attr
[directiveName
] ? scope
.$parent
.$eval(attr
[directiveName
]) : {};
526 $q
.when(crmMetadata
.getFields('Mailing'), function(fields
) {
527 scope
.mailingFields
= fields
;
534 })(angular
, CRM
.$, CRM
._
);