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
, crmNow
) {
101 var pickDefaultMailComponent
= function pickDefaultMailComponent(type
) {
102 var mcs
= _
.where(CRM
.crmMailing
.headerfooterList
, {
103 component_type
: type
,
106 return (mcs
.length
>= 1) ? mcs
[0].id
: null;
110 // @param scalar idExpr a number or the literal string 'new'
111 // @return Promise|Object Mailing (per APIv3)
112 getOrCreate
: function getOrCreate(idExpr
) {
113 return (idExpr
== 'new') ? this.create() : this.get(idExpr
);
115 // @return Promise Mailing (per APIv3)
116 get: function get(id
) {
117 var crmMailingMgr
= this;
119 return crmApi('Mailing', 'getsingle', {id
: id
})
120 .then(function (getResult
) {
123 crmMailingMgr
._loadGroups(mailing
),
124 crmMailingMgr
._loadJobs(mailing
)
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
) {
135 mailing
.recipients
= {};
136 mailing
.recipients
.groups
= {include
: [], exclude
: [], base
: []};
137 mailing
.recipients
.mailings
= {include
: [], exclude
: []};
138 _
.each(groupResult
.values
, function (mailingGroup
) {
139 var bucket
= (/^civicrm_group/.test(mailingGroup
.entity_table
)) ? 'groups' : 'mailings';
140 var entityId
= parseInt(mailingGroup
.entity_id
);
141 mailing
.recipients
[bucket
][mailingGroup
.group_type
.toLowerCase()].push(entityId
);
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
);
153 // @return Object Mailing (per APIv3)
154 create
: function create(params
) {
156 jobs
: {}, // {jobId: JobRecord}
158 groups
: {include
: [], exclude
: [], base
: []},
159 mailings
: {include
: [], exclude
: []}
168 return angular
.extend({}, defaults
, params
);
171 // @param mailing Object (per APIv3)
173 'delete': function (mailing
) {
175 return crmApi('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
])) {
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 var params
= angular
.extend({}, mailing
, mailing
.recipients
, {
266 options
: {force_rollback
: 1},
267 'api.Mailing.preview': {
271 delete params
.recipients
; // the content was merged in
272 return crmApi('Mailing', 'create', params
).then(function (result
) {
273 // changes rolled back, so we don't care about updating mailing
274 return result
.values
[result
.id
]['api.Mailing.preview'].values
;
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)
281 previewRecipients
: function previewRecipients(mailing
, previewLimit
) {
282 // To get list of recipients, we tentatively save the mailing and
283 // get the resulting recipients -- then rollback any changes.
284 var params
= angular
.extend({}, mailing
, mailing
.recipients
, {
285 name
: 'placeholder', // for previewing recipients on new, incomplete mailing
286 subject
: 'placeholder', // for previewing recipients on new, incomplete mailing
287 options
: {force_rollback
: 1},
288 'api.mailing_job.create': 1, // note: exact match to API default
289 'api.MailingRecipients.get': {
290 mailing_id
: '$value.id',
291 options
: {limit
: previewLimit
},
292 'api.contact.getvalue': {'return': 'display_name'},
293 'api.email.getvalue': {'return': 'email'}
296 delete params
.recipients
; // the content was merged in
297 return crmApi('Mailing', 'create', params
).then(function (recipResult
) {
298 // changes rolled back, so we don't care about updating mailing
299 return recipResult
.values
[recipResult
.id
]['api.MailingRecipients.get'].values
;
303 // Save a (draft) mailing
304 // @param mailing Object (per APIv3)
306 save: function(mailing
) {
307 var params
= angular
.extend({}, mailing
, mailing
.recipients
);
309 // Angular ngModel sometimes treats blank fields as undefined.
310 angular
.forEach(mailing
, function(value
, key
) {
311 if (value
=== undefined || value
=== null) {
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
;
323 delete params
.recipients
; // the content was merged in
325 return crmApi('Mailing', 'create', params
).then(function(result
) {
326 if (result
.id
&& !mailing
.id
) {
327 mailing
.id
= result
.id
;
328 } // no rollback, so update mailing.id
329 // Perhaps we should reload mailing based on result?
334 // Schedule/send the mailing
335 // @param mailing Object (per APIv3)
337 submit: function (mailing
) {
338 var crmMailingMgr
= this;
341 approval_date
: crmNow(),
342 scheduled_date
: mailing
.scheduled_date
? mailing
.scheduled_date
: crmNow()
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
);
354 // Immediately send a test message
355 // @param mailing Object (per APIv3)
356 // @param to Object with either key "email" (string) or "gid" (int)
357 // @return Promise for a list of delivery reports
358 sendTest: function (mailing
, recipient
) {
359 var params
= angular
.extend({}, mailing
, mailing
.recipients
, {
360 // options: {force_rollback: 1}, // Test mailings include tracking features, so the mailing must be persistent
361 'api.Mailing.send_test': {
362 mailing_id
: '$value.id',
363 test_email
: recipient
.email
,
364 test_group
: recipient
.gid
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 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
381 return result
.values
[result
.id
]['api.Mailing.send_test'].values
;
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
) {
390 // @param mode string one of 'html', 'text', or 'full'
392 preview
: function preview(mailing
, mode
) {
394 html
: '~/crmMailing/dialog/previewHtml.html',
395 text
: '~/crmMailing/dialog/previewText.html',
396 full
: '~/crmMailing/dialog/previewFull.html'
399 var p
= crmMailingMgr
401 .then(function (content
) {
402 var options
= CRM
.utils
.adjustDialogDefaults({
404 title
: ts('Subject: %1', {
408 result
= dialogService
.open('previewDialog', templates
[mode
], content
, options
);
410 crmStatus({start
: ts('Previewing'), success
: ''}, p
);
414 // @param to Object with either key "email" (string) or "gid" (int)
416 sendTest
: function sendTest(mailing
, recipient
) {
417 var promise
= crmMailingMgr
.sendTest(mailing
, recipient
)
418 .then(function (deliveryInfos
) {
419 var count
= Object
.keys(deliveryInfos
).length
;
421 CRM
.alert(ts('Could not identify any recipients. Perhaps the group is empty?'));
425 return crmStatus({start
: ts('Sending...'), success
: ts('Sent')}, promise
);
430 angular
.module('crmMailing').factory('crmMailingStats', function (crmApi
, crmLegacy
) {
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'}
444 getStatTypes: function() {
449 * @param mailingIds object
450 * List of mailing IDs ({a: 123, b: 456})
452 * List of stats for each mailing
453 * ({a: ...object..., b: ...object...})
455 getStats: function(mailingIds
) {
457 angular
.forEach(mailingIds
, function(mailingId
, name
) {
458 params
[name
] = ['Mailing', 'stats', {mailing_id
: mailingId
}];
460 return crmApi(params
).then(function(result
) {
462 angular
.forEach(mailingIds
, function(mailingId
, name
) {
463 stats
[name
] = result
[name
].values
[mailingId
];
470 * Determine the legacy URL for a report about a given mailing and stat.
472 * @param mailing object
473 * @param statType object (see statTypes above)
474 * @param view string ('search', 'event', 'report')
475 * @return string|null
477 getUrl
: function getUrl(mailing
, statType
, view
) {
480 return crmLegacy
.url('civicrm/mailing/report/event',
481 'reset=1&mid=' + mailing
.id
+ statType
.eventsFilter
);
484 return crmLegacy
.url('civicrm/contact/search/advanced',
485 'force=1&mailing_id=' + mailing
.id
+ statType
.searchFilter
);
487 // TODO: case 'report':
495 })(angular
, CRM
.$, CRM
._
);