SearchKit - Add CiviMail integration
[civicrm-core.git] / ext / search_kit / ang / crmSearchTasks / crmSearchTaskMailing.ctrl.js
1 (function(angular, $, _) {
2 "use strict";
3
4 angular.module('crmSearchTasks').controller('crmSearchTaskMailing', function($scope, crmApi4, searchTaskBaseTrait) {
5 var ts = $scope.ts = CRM.ts('org.civicrm.search_kit'),
6 // Combine this controller with model properties (ids, entity, entityInfo) and searchTaskBaseTrait
7 ctrl = angular.extend(this, $scope.model, searchTaskBaseTrait),
8 templateTypes;
9
10 this.entityTitle = this.getEntityTitle();
11
12 // This option is needed to determine whether the mailing will be handled by CiviMail or Mosaico
13 crmApi4({
14 templateTypes: ['Mailing', 'getFields', {
15 loadOptions: ['id'],
16 where: [['name', '=', 'template_type']]
17 }, ['options']],
18 recipientCount: ['Contact', 'get', {
19 select: ['row_count'],
20 join: [['Email AS email', 'INNER', ['id', '=', 'email.contact_id']]],
21 where: [['id', 'IN', ctrl.ids], ['do_not_email', '!=', true], ['is_opt_out', '!=', true], ['email.on_hold', '=', 0]],
22 groupBy: ['id']
23 }]
24 }).then(function(results) {
25 templateTypes = results.templateTypes[0];
26 ctrl.recipientCount = results.recipientCount.count;
27 });
28
29 this.submit = function() {
30 var contacts = _.transform(ctrl.ids, function(records, cid) {
31 records.push({contact_id: cid});
32 });
33 ctrl.start({
34 values: {
35 title: 'Hidden Group ' + Date.now(),
36 is_hidden: true,
37 'group_type:name': ['Mailing List'],
38 },
39 chain: {
40 contacts: ['GroupContact', 'save', {
41 defaults: {group_id: '$id'},
42 records: contacts
43 }],
44 mailing: ['Mailing', 'create', {
45 values: {
46 name: ctrl.name,
47 template_type: templateTypes[0].id
48 }
49 }, 0],
50 mailingGroup: ['MailingGroup', 'create', {
51 values: {
52 group_type: 'Include',
53 'entity_table:name': 'Group',
54 entity_id: '$id',
55 mailing_id: '$mailing.id'
56 },
57 }, 0]
58 }
59 });
60 };
61
62
63 this.onSuccess = function(result) {
64 window.location = CRM.url('civicrm/a#/mailing/' + result[0].mailing.id);
65 };
66
67 this.onError = function() {
68 CRM.alert(ts('An error occurred while attempting to create mailing.'), ts('Error'), 'error');
69 this.cancel();
70 };
71
72 });
73 })(angular, CRM.$, CRM._);