-
Notifications
You must be signed in to change notification settings - Fork 0
/
request-demo.js
364 lines (343 loc) · 12.9 KB
/
request-demo.js
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
console.log("v1");
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
document.addEventListener("DOMContentLoaded", () => {
(function (windowRef, documentRef, fileLocation, functionName) {
windowRef["LeanDataCalendaringObjName"] = functionName;
windowRef[functionName] = (...args) => {
windowRef[functionName].variables = args;
};
const scriptElement = documentRef.createElement("script");
const targetScript = document.getElementsByTagName("script")[0];
const targetHead = document.getElementsByTagName("head")[0];
scriptElement.async = 1;
scriptElement.src = fileLocation;
if (targetScript) {
targetScript.parentNode.insertBefore(scriptElement, targetScript);
} else if (targetHead) {
targetHead.append(scriptElement);
}
})(
window,
document,
"https://app.leandata.com/js-snippet/ld_calendaring.js",
"LDBookIt"
);
// TODO: replace values below with your SFDC id and BookIt node name
LDBookIt("00D5I000000Fr4cUAC", "New Inbound Lead", false, {
apiRoutingOn: true,
popupModalOn: true,
});
let enrichedData = null;
(function () {
let isSubmitting = false;
// Attaching BookIt process to your form submit button
const attachToForm = () => {
let registered = false;
console.log("Attempting to attach to form");
const myForm = document.querySelector("#email-form");
if (myForm != null) {
registered = true;
// TODO: Verify selector below
myForm
.querySelector('input[type="submit"]')
.addEventListener("click", async (event) => {
if (!isSubmitting) {
event.preventDefault();
const isFormValid = myForm.checkValidity();
if (!isFormValid) {
myForm.reportValidity();
return;
}
const invalidDomains = [
"gmail.",
"yahoo.",
"hotmail.",
"outlook.",
"msn.",
"icloud.",
"mail.",
"aol.",
"qq.",
];
// validate email field
// get the email field
const email = $(".business-only-email-field");
// split email at '@' character to get domain
let emailValue = email.val();
let domainPart = emailValue.split("@")[1] || "";
// convert the domain to lowercase before comparing, just in case the user typed it in caps
domainPart = domainPart.toLowerCase();
// check if the domain starts with any invalid domain
let isInvalid = invalidDomains.some((invalidDomain) =>
domainPart.startsWith(invalidDomain)
);
// if the domain exists in the invalidDomains array
if (isInvalid) {
// add the 'has-error' class to show the error message
email.addClass("has-error");
// focus the email field
email.focus();
email.on("input", () => {
// remove error message when user restarts typing
email.removeClass("has-error");
$(".no-pea-message").hide();
});
$(".no-pea-message").show();
// prevent form submission
return false;
} else {
// else if email is not invalid
const loadingScreen = document.querySelector(".loading-screen");
const emailErrorMsg = document.querySelector(
".email-form-error-message"
);
loadingScreen.style.display = "flex";
loadingScreen.style.opacity = 1;
emailErrorMsg.style.display = "none";
email.removeClass("has-error");
setTimeout(
() =>
(loadingScreen.querySelector(
".loading-text"
).style.opacity = 0.5),
2000
);
// remove the 'no-pea-message' class and hide the error message
$(".no-pea-message").hide();
let data = null;
let emailStatus = null;
try {
// make a POST fetch request to validate the email
const response = await fetch(
"https://app.amplemarket.com/api/v1/amplemarket_inbounds/validate_email",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email: email.val() }),
}
);
// get the JSON response
data = await response.json();
emailStatus = data?.status;
// if the request returns a 400 status or a "valid"=false response, don't proceed any further
if (response.status === 400 || data?.valid === false) {
loadingScreen.style.display = "none";
// set the error message
emailErrorMsg.style.display = "block";
email.addClass("has-error");
// focus the email field
email.focus();
email.on("input", () => {
// remove error message when user restarts typing
email.removeClass("has-error");
emailErrorMsg.style.display = "none";
});
return false;
}
} catch (error) {
console.log(error);
}
let enrichRes;
try {
const enrichReq = await fetch(
`https://app.amplemarket.com/api/v1/amplemarket_inbounds/enrich_person?email=${encodeURIComponent(
email.val()
)}`
);
if (!enrichReq.ok) throw new Error("Failed to fetch");
enrichRes = await enrichReq.json();
} catch (error) {
console.error("Error fetching enriched data:", error);
enrichRes = null;
}
let partnerKey = growsumo.data.partner_key;
let hiddenField = $(".last-name").val();
enrichedData = {
title: enrichRes ? enrichRes.title : null,
person_location: enrichRes ? enrichRes.location : null,
size:
enrichRes && enrichRes.company
? enrichRes.company.size
: null,
sales_team_size_enriched:
enrichRes &&
enrichRes.company &&
enrichRes.company.department_headcount
? enrichRes.company.department_headcount.sales
: null,
industry:
enrichRes && enrichRes.company
? enrichRes.company.industry
: null,
company_location:
enrichRes && enrichRes.company
? enrichRes.company.location
: null,
is_b2b:
enrichRes && enrichRes.company
? enrichRes.company.is_b2b
: null,
is_b2c:
enrichRes && enrichRes.company
? enrichRes.company.is_b2c
: null,
partner_key: partnerKey,
hidden_field: hiddenField,
email_status: emailStatus,
// technologies: enrichRes && enrichRes.company ? enrichRes.company.technologies.join(', ') : null,
};
// run bookit code
BookItAPIRouting(myForm);
}
} else {
isSubmitting = false;
}
});
}
if (!registered) {
setTimeout(() => {
attachToForm();
}, 1000);
}
};
const BookItAPIRouting = (myForm) => {
let options = {
MAType: "Custom",
formHandle: myForm,
onError: (error) => {
// TODO: Add Zap flow trigger here
postFullRequestData();
},
afterSubmit: async (formData) => {
growsumo.data.name = formData["Name"];
growsumo.data.email = formData["Company-Email"];
let domainPart = formData["Company-Email"].split("@")[1];
domainPart = domainPart.toLowerCase();
growsumo.data.customer_key = domainPart;
await growsumo.createSignup();
setTimeout(() => {
window.location.href = "/thanks-demo";
}, 150);
},
afterRouting: (formData, responseData) => {
window.localStorage.setItem(
`LDCalendaring_custom_calendarLink`,
responseData.calendarLink
);
window.localStorage.setItem(
`LDCalendaring_custom_formInput`,
JSON.stringify(responseData.formInput)
);
window.localStorage.setItem(
`LDCalendaring_custom_newTab`,
responseData.newTab
);
},
customValidation: () => {
// TODO: Add form validation to stop LD from routing invalid data. Sample validation provided below.
const requiredFields = myForm.querySelectorAll("[required]");
console.log(requiredFields);
let isValid = true;
requiredFields.forEach((field) => {
if (field.value === "") {
isValid = false;
}
});
return isValid;
},
formDataCollector: (hiddenFieldNames) => {
let formData, formHiddenFieldNames;
[formData, formHiddenFieldNames] = CollectFormData(myForm);
//splits Name field into first and last by first space
let name = formData.Name.trim();
if (name.includes(" ")) {
const [firstName, ...lastName] = name.split(" ");
formData.firstname = firstName;
formData.lastname = lastName.join(" ");
} else {
formData.firstname = name;
formData.lastname = "";
}
// Merge enrichedData with formData
if (enrichedData) {
formData = { ...formData, ...enrichedData };
}
return formData;
},
hiddenFieldSetter: (
options,
formData,
responseData,
hiddenFieldNames
) => {
// TODO: Use this function to set the log id field on your form so it gets passed to your MA.
const logIdField = myForm.querySelector(
'input[name="ld_bookit_log_id"]'
);
logIdField.value = responseData.formInput.ld_bookit_log_id;
},
beforeSubmit: (formData, responseData) => {
// TODO: Add Zap flow trigger here
postFullRequestData();
},
/* afterSubmit: (formData, responseData) => {
if (responseData.calendarLink) {
LDBookIt.redirect(options);
}
}, */
formSubmitter: () => {
isSubmitting = true;
console.log("is submitting");
// TODO: Verify selector below
myForm.querySelector('input[type="submit"]').click();
},
};
LDBookIt.submit(options);
};
attachToForm();
})();
const CollectFormData = (myForm) => {
let formData = {};
let hiddenFieldNames = new Set();
const elements = myForm.elements;
// get all form data - this errs on getting too many fields
for (let i = 0; i < elements.length; i++) {
let elem = elements[i];
let apiName = elem.name;
switch (elem.type) {
case "text":
case "textarea":
case "number":
case "email":
formData[apiName] = elem.value;
break;
O;
case "select-one":
const selectedIndex = elem.selectedIndex;
apiName = elem.name;
formData[apiName] = selectedIndex
? elem.options[elem.selectedIndex].value
: "";
break;
case "checkbox":
formData[apiName] = elem.checked;
break;
case "radio":
if (elem.checked && elem.nextElementSibling) {
formData[apiName] = elem.nextElementSibling.textContent;
}
break;
case "hidden":
formData[apiName] = elem.value;
hiddenFieldNames.add(apiName);
break;
}
}
// TODO: ensure you are getting all the data you need from the form
console.log("formData", formData);
console.log("hiddenFieldNames", hiddenFieldNames);
return [formData, hiddenFieldNames];
};
});