| 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 | // @return Promise MessageTemplate (per APIv3) |
| 64 | get: function get(id) { |
| 65 | id = '' + id; // parseInt(id); |
| 66 | var dfr = $q.defer(); |
| 67 | var tpl = _.where(tpls, {id: id}); |
| 68 | if (id && tpl && tpl[0]) { |
| 69 | dfr.resolve(tpl[0]); |
| 70 | } |
| 71 | else { |
| 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) |
| 79 | save: function (tpl) { |
| 80 | return crmApi('MessageTemplate', 'create', tpl).then(function (response) { |
| 81 | if (!tpl.id) { |
| 82 | tpl.id = '' + response.id; //parseInt(response.id); |
| 83 | tpls.push(tpl); |
| 84 | } |
| 85 | lastModifiedTpl = tpl; |
| 86 | return tpl; |
| 87 | }); |
| 88 | }, |
| 89 | // @return Object MessageTemplate (per APIv3) |
| 90 | getLastModifiedTpl: function () { |
| 91 | return lastModifiedTpl; |
| 92 | }, |
| 93 | getAll: function getAll() { |
| 94 | return tpls; |
| 95 | } |
| 96 | }; |
| 97 | }); |
| 98 | |
| 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, |
| 104 | is_default: "1" |
| 105 | }); |
| 106 | return (mcs.length >= 1) ? mcs[0].id : null; |
| 107 | }; |
| 108 | |
| 109 | return { |
| 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); |
| 114 | }, |
| 115 | // @return Promise Mailing (per APIv3) |
| 116 | get: function get(id) { |
| 117 | var crmMailingMgr = this; |
| 118 | var mailing; |
| 119 | return crmApi('Mailing', 'getsingle', {id: id}) |
| 120 | .then(function (getResult) { |
| 121 | mailing = getResult; |
| 122 | return $q.all([ |
| 123 | crmMailingMgr._loadGroups(mailing), |
| 124 | crmMailingMgr._loadJobs(mailing) |
| 125 | ]); |
| 126 | }) |
| 127 | .then(function () { |
| 128 | return mailing; |
| 129 | }); |
| 130 | }, |
| 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); |
| 142 | }); |
| 143 | }); |
| 144 | }, |
| 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); |
| 151 | }); |
| 152 | }, |
| 153 | // @return Object Mailing (per APIv3) |
| 154 | create: function create(params) { |
| 155 | var defaults = { |
| 156 | jobs: {}, // {jobId: JobRecord} |
| 157 | recipients: { |
| 158 | groups: {include: [], exclude: [], base: []}, |
| 159 | mailings: {include: [], exclude: []} |
| 160 | }, |
| 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 crmApi('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])) { |
| 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 | var params = angular.extend({}, mailing, mailing.recipients, { |
| 266 | options: {force_rollback: 1}, |
| 267 | 'api.Mailing.preview': { |
| 268 | id: '$value.id' |
| 269 | } |
| 270 | }); |
| 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; |
| 275 | }); |
| 276 | }, |
| 277 | |
| 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'} |
| 294 | } |
| 295 | }); |
| 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; |
| 300 | }); |
| 301 | }, |
| 302 | |
| 303 | // Save a (draft) mailing |
| 304 | // @param mailing Object (per APIv3) |
| 305 | // @return Promise |
| 306 | save: function(mailing) { |
| 307 | var params = angular.extend({}, mailing, mailing.recipients); |
| 308 | |
| 309 | // Angular ngModel sometimes treats blank fields as undefined. |
| 310 | angular.forEach(mailing, function(value, key) { |
| 311 | if (value === undefined || value === null) { |
| 312 | mailing[key] = ''; |
| 313 | } |
| 314 | }); |
| 315 | |
| 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; |
| 320 | |
| 321 | delete params.jobs; |
| 322 | |
| 323 | delete params.recipients; // the content was merged in |
| 324 | |
| 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? |
| 330 | return mailing; |
| 331 | }); |
| 332 | }, |
| 333 | |
| 334 | // Schedule/send the mailing |
| 335 | // @param mailing Object (per APIv3) |
| 336 | // @return Promise |
| 337 | submit: function (mailing) { |
| 338 | var crmMailingMgr = this; |
| 339 | var params = { |
| 340 | id: mailing.id, |
| 341 | approval_date: crmNow(), |
| 342 | scheduled_date: mailing.scheduled_date ? mailing.scheduled_date : crmNow() |
| 343 | }; |
| 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); |
| 348 | }) |
| 349 | .then(function () { |
| 350 | return mailing; |
| 351 | }); |
| 352 | }, |
| 353 | |
| 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 |
| 365 | } |
| 366 | }); |
| 367 | |
| 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; |
| 372 | |
| 373 | delete params.jobs; |
| 374 | |
| 375 | delete params.recipients; // the content was merged in |
| 376 | |
| 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; |
| 382 | }); |
| 383 | } |
| 384 | }; |
| 385 | }); |
| 386 | |
| 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) { |
| 389 | return { |
| 390 | // @param mode string one of 'html', 'text', or 'full' |
| 391 | // @return Promise |
| 392 | preview: function preview(mailing, mode) { |
| 393 | var templates = { |
| 394 | html: '~/crmMailing/dialog/previewHtml.html', |
| 395 | text: '~/crmMailing/dialog/previewText.html', |
| 396 | full: '~/crmMailing/dialog/previewFull.html' |
| 397 | }; |
| 398 | var result = null; |
| 399 | var p = crmMailingMgr |
| 400 | .preview(mailing) |
| 401 | .then(function (content) { |
| 402 | var options = CRM.utils.adjustDialogDefaults({ |
| 403 | autoOpen: false, |
| 404 | title: ts('Subject: %1', { |
| 405 | 1: content.subject |
| 406 | }) |
| 407 | }); |
| 408 | result = dialogService.open('previewDialog', templates[mode], content, options); |
| 409 | }); |
| 410 | crmStatus({start: ts('Previewing'), success: ''}, p); |
| 411 | return result; |
| 412 | }, |
| 413 | |
| 414 | // @param to Object with either key "email" (string) or "gid" (int) |
| 415 | // @return Promise |
| 416 | sendTest: function sendTest(mailing, recipient) { |
| 417 | var promise = crmMailingMgr.sendTest(mailing, recipient) |
| 418 | .then(function (deliveryInfos) { |
| 419 | var count = Object.keys(deliveryInfos).length; |
| 420 | if (count === 0) { |
| 421 | CRM.alert(ts('Could not identify any recipients. Perhaps the group is empty?')); |
| 422 | } |
| 423 | }) |
| 424 | ; |
| 425 | return crmStatus({start: ts('Sending...'), success: ts('Sent')}, promise); |
| 426 | } |
| 427 | }; |
| 428 | }); |
| 429 | |
| 430 | angular.module('crmMailing').factory('crmMailingStats', function (crmApi, crmLegacy) { |
| 431 | var statTypes = [ |
| 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'} |
| 441 | ]; |
| 442 | |
| 443 | return { |
| 444 | getStatTypes: function() { |
| 445 | return statTypes; |
| 446 | }, |
| 447 | |
| 448 | /** |
| 449 | * @param mailingIds object |
| 450 | * List of mailing IDs ({a: 123, b: 456}) |
| 451 | * @return Promise |
| 452 | * List of stats for each mailing |
| 453 | * ({a: ...object..., b: ...object...}) |
| 454 | */ |
| 455 | getStats: function(mailingIds) { |
| 456 | var params = {}; |
| 457 | angular.forEach(mailingIds, function(mailingId, name) { |
| 458 | params[name] = ['Mailing', 'stats', {mailing_id: mailingId}]; |
| 459 | }); |
| 460 | return crmApi(params).then(function(result) { |
| 461 | var stats = {}; |
| 462 | angular.forEach(mailingIds, function(mailingId, name) { |
| 463 | stats[name] = result[name].values[mailingId]; |
| 464 | }); |
| 465 | return stats; |
| 466 | }); |
| 467 | }, |
| 468 | |
| 469 | /** |
| 470 | * Determine the legacy URL for a report about a given mailing and stat. |
| 471 | * |
| 472 | * @param mailing object |
| 473 | * @param statType object (see statTypes above) |
| 474 | * @param view string ('search', 'event', 'report') |
| 475 | * @return string|null |
| 476 | */ |
| 477 | getUrl: function getUrl(mailing, statType, view) { |
| 478 | switch (view) { |
| 479 | case 'events': |
| 480 | return crmLegacy.url('civicrm/mailing/report/event', |
| 481 | 'reset=1&mid=' + mailing.id + statType.eventsFilter); |
| 482 | |
| 483 | case 'search': |
| 484 | return crmLegacy.url('civicrm/contact/search/advanced', |
| 485 | 'force=1&mailing_id=' + mailing.id + statType.searchFilter); |
| 486 | |
| 487 | // TODO: case 'report': |
| 488 | default: |
| 489 | return null; |
| 490 | } |
| 491 | } |
| 492 | }; |
| 493 | }); |
| 494 | |
| 495 | })(angular, CRM.$, CRM._); |