-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathActiveCampaignContactsWorkflow.cs
More file actions
167 lines (130 loc) · 6.62 KB
/
Copy pathActiveCampaignContactsWorkflow.cs
File metadata and controls
167 lines (130 loc) · 6.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Text.Json;
using Umbraco.Forms.Core;
using Umbraco.Forms.Core.Enums;
using Umbraco.Forms.Core.Persistence.Dtos;
using Umbraco.Forms.Integrations.Crm.ActiveCampaign.Configuration;
using Umbraco.Forms.Integrations.Crm.ActiveCampaign.Models.Dtos;
using Umbraco.Forms.Integrations.Crm.ActiveCampaign.Services;
namespace Umbraco.Forms.Integrations.Crm.ActiveCampaign
{
public class ActiveCampaignContactsWorkflow : WorkflowType
{
private readonly ActiveCampaignSettings _settings;
private readonly IAccountService _accountService;
private readonly IContactService _contactService;
private readonly ILogger<ActiveCampaignContactsWorkflow> _logger;
[Core.Attributes.Setting("Account",
Description = "Please select an account",
View = "~/App_Plugins/UmbracoForms.Integrations/Crm/ActiveCampaign/accountpicker.html")]
public string Account { get; set; }
[Core.Attributes.Setting("Contact Mappings",
Description = "Map contact details with form fields",
View = "~/App_Plugins/UmbracoForms.Integrations/Crm/ActiveCampaign/contact-mapper.html")]
public string ContactMappings { get; set; }
[Core.Attributes.Setting("Custom Field Mappings",
Description = "Map contact custom fields with form fields",
View = "~/App_Plugins/UmbracoForms.Integrations/Crm/ActiveCampaign/customfield-mapper.html")]
public string CustomFieldMappings { get; set; }
public ActiveCampaignContactsWorkflow(IOptions<ActiveCampaignSettings> options,
IAccountService accountService, IContactService contactService,
ILogger<ActiveCampaignContactsWorkflow> logger)
{
Id = new Guid(Constants.WorkflowId);
Name = "ActiveCampaign Contacts Workflow";
Description = "Submit form data to ActiveCampaign Contacts";
Icon = "icon-users";
_settings = options.Value;
_accountService = accountService;
_contactService = contactService;
_logger = logger;
}
public override WorkflowExecutionStatus Execute(WorkflowExecutionContext context)
{
try
{
var mappings = JsonSerializer.Deserialize<List<ContactMappingDto>>(ContactMappings);
var email = context.Record.RecordFields[Guid.Parse(mappings.First(p => p.ContactField == "email").FormField.Id)]
.ValuesAsString();
// Check if contact exists.
var contacts = _contactService.Get(email).ConfigureAwait(false).GetAwaiter().GetResult();
if(contacts.Contacts.Count > 0 && !_settings.AllowContactUpdate)
{
_logger.LogInformation("Contact already exists in ActiveCampaign and workflow is configured to not apply updates, so update of information was skipped.");
return WorkflowExecutionStatus.Completed;
}
var requestDto = new ContactDetailDto { Contact = Build(context.Record) };
if (contacts.Contacts.Count > 0) requestDto.Contact.Id = contacts.Contacts.First().Id;
// Set contact custom fields.
if (!string.IsNullOrEmpty(CustomFieldMappings))
{
var customFieldMappings = JsonSerializer.Deserialize<List<CustomFieldMappingDto>>(CustomFieldMappings);
requestDto.Contact.FieldValues = customFieldMappings.Select(p => new CustomFieldValueDto
{
Field = p.CustomField.Id,
Value = context.Record.RecordFields[Guid.Parse(p.FormField.Id)].ValuesAsString()
}).ToList();
}
var contactId = _contactService.CreateOrUpdate(requestDto, contacts.Contacts.Count > 0)
.ConfigureAwait(false).GetAwaiter().GetResult();
if (string.IsNullOrEmpty(contactId))
{
_logger.LogError($"Failed to create/update contact: {email}");
return WorkflowExecutionStatus.Failed;
}
// Associate contact with account if last one is specified.
if (!string.IsNullOrEmpty(Account))
{
var associationResponse = _accountService.CreateAssociation(int.Parse(Account), int.Parse(contactId))
.ConfigureAwait(false).GetAwaiter().GetResult();
}
return WorkflowExecutionStatus.Completed;
}
catch(Exception ex)
{
_logger.LogError(ex, ex.Message);
return WorkflowExecutionStatus.Failed;
}
}
public override List<Exception> ValidateSettings()
{
var list = new List<Exception>();
if (string.IsNullOrEmpty(ContactMappings))
list.Add(new Exception("Contact mappings are required."));
var mappings = JsonSerializer.Deserialize<List<ContactMappingDto>>(ContactMappings);
foreach(var contactField in _settings.ContactFields.Where(p => p.Required))
{
if(!mappings.Any(p => p.ContactField == contactField.Name))
{
list.Add(new Exception("Invalid contact mappings. Please make sure the mandatory fields are mapped."));
break;
}
}
return list;
}
/// <summary>
/// Create Contact instance using the mapped details and record fields
/// </summary>
/// <param name="record"></param>
/// <returns></returns>
private ContactDto Build(Record record)
{
var mappings = JsonSerializer.Deserialize<List<ContactMappingDto>>(ContactMappings);
return new ContactDto
{
Email = ReadMappingValue(record, mappings, "email"),
FirstName = ReadMappingValue(record, mappings, "firstName"),
LastName = ReadMappingValue(record, mappings, "lastName"),
Phone = ReadMappingValue(record, mappings, "phone")
};
}
private string ReadMappingValue(Record record, List<ContactMappingDto> mappings, string name)
{
var mappingItem = mappings.FirstOrDefault(p => p.ContactField == name);
return mappingItem != null
? record.RecordFields[Guid.Parse(mappingItem.FormField.Id)].ValuesAsString()
: string.Empty;
}
}
}