-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelementor-form-to-google-sheets-webhook.js
450 lines (398 loc) · 13 KB
/
elementor-form-to-google-sheets-webhook.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/**
* Copyright (c)
* Author: David C Cavalcante (Enhanced by AI)
* Developed by Takk™ Innovate Studio
* License: Apache License 2.0
* Version: 1.0.0
* GitHub: https://github.com/Takk8IS
* LinkedIn: https://www.linkedin.com/in/hellodav
* Donations: $USDT (TRC-20): `TGpiWetnYK2VQpxNGPR27D9vfM6Mei5vNA`
*
* Description: Advanced system to capture form submissions via webhook, store data in Google Sheets,
* perform data analysis, and send intelligent notifications.
* Features: Adaptive data processing, advanced error handling, automatic data categorization,
* intelligent email notifications, and data trend analysis.
*/
// Configuration object for easy adjustments
const CONFIG = {
emailNotification: true,
emailAddress: "[email protected]",
maxRetries: 3,
// milliseconds
retryDelay: 1000,
dataRetentionDays: 365,
// standard deviations
anomalyThreshold: 2,
};
/**
* Handles GET requests to verify the webhook URL.
*/
function doGet() {
return HtmlService.createHtmlOutput(
"Webhook URL is active and ready to receive requests.",
);
}
/**
* Main function to handle POST requests from the Elementor form webhook.
*/
function doPost(e) {
return executeWithRetry(() => {
const params = processIncomingData(e.parameter);
const formName = params["form_name"] || "Default_Form";
const formSheet = getOrCreateSheet(formName);
const headers = updateHeaders(formSheet, Object.keys(params));
const values = mapValuesToHeaders(headers, params);
appendDataToSheet(formSheet, values);
performDataAnalysis(formSheet);
if (CONFIG.emailNotification) {
sendIntelligentNotification(
params,
getSheetURL(formSheet),
formSheet,
);
}
cleanupOldData(formSheet);
return HtmlService.createHtmlOutput(
"Form data received, processed, and analyzed successfully.",
);
});
}
/**
* Executes a function with retry logic.
*/
function executeWithRetry(func) {
for (let i = 0; i < CONFIG.maxRetries; i++) {
try {
return func();
} catch (error) {
if (i === CONFIG.maxRetries - 1) throw error;
Utilities.sleep(CONFIG.retryDelay);
}
}
}
/**
* Processes incoming data with advanced techniques.
*/
function processIncomingData(data) {
const flattenedData = flattenObject(data);
flattenedData.timestamp = new Date().toISOString();
flattenedData.processed_data = JSON.stringify(
intelligentDataProcessing(flattenedData),
);
return flattenedData;
}
/**
* Performs intelligent data processing and categorization.
*/
function intelligentDataProcessing(data) {
// Implement advanced data processing logic here
// This could include natural language processing, data validation, etc.
return {
category: determineCategory(data),
sentiment: analyzeSentiment(data),
priority: calculatePriority(data),
};
}
/**
* Determines the category of the submission based on its content.
*/
function determineCategory(data) {
// Implement category determination logic
return "General";
}
/**
* Analyzes the sentiment of the submission.
*/
function analyzeSentiment(data) {
// Implement sentiment analysis logic
return "Neutral";
}
/**
* Calculates the priority of the submission.
*/
function calculatePriority(data) {
// Implement priority calculation logic
return "Medium";
}
/**
* Flattens a nested object recursively.
*/
function flattenObject(obj, prefix = "") {
return Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? `${prefix}.` : "";
if (
typeof obj[k] === "object" &&
obj[k] !== null &&
!Array.isArray(obj[k])
) {
Object.assign(acc, flattenObject(obj[k], pre + k));
} else {
acc[pre + k] = obj[k];
}
return acc;
}, {});
}
/**
* Updates headers in the Google Sheet dynamically.
*/
function updateHeaders(sheet, keys) {
const existingHeaders = sheet
.getRange(1, 1, 1, sheet.getLastColumn())
.getValues()[0];
const newHeaders = keys.filter((key) => !existingHeaders.includes(key));
const allHeaders = [...new Set([...existingHeaders, ...newHeaders])];
if (newHeaders.length > 0) {
setHeaders(sheet, allHeaders);
}
return allHeaders;
}
/**
* Maps incoming data values to the correct headers.
*/
function mapValuesToHeaders(headers, data) {
return headers.map((header) => data[header] || "");
}
/**
* Sets headers in the first row of the sheet with advanced formatting.
*/
function setHeaders(sheet, headers) {
const range = sheet.getRange(1, 1, 1, headers.length);
range.setValues([headers]);
range.setFontWeight("bold");
range.setHorizontalAlignment("center");
range.setBackground("#f3f3f3");
sheet.setFrozenRows(1);
}
/**
* Appends data to the sheet with intelligent formatting.
*/
function appendDataToSheet(sheet, values) {
const lastRow = Math.max(sheet.getLastRow(), 1);
sheet.insertRowAfter(lastRow);
const range = sheet.getRange(lastRow + 1, 1, 1, values.length);
range.setValues([values]);
// Apply conditional formatting based on priority
const priorityColumn =
values.findIndex((v) => v === "High" || v === "Medium" || v === "Low") +
1;
if (priorityColumn > 0) {
const priorityRange = sheet.getRange(lastRow + 1, priorityColumn);
const rule = SpreadsheetApp.newConditionalFormatRule()
.whenTextEqualTo("High")
.setBackground("#f4cccc")
.setRanges([priorityRange])
.build();
const rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
}
}
/**
* Retrieves or creates a sheet with advanced setup.
*/
function getOrCreateSheet(formName) {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
let sheet = spreadsheet.getSheetByName(formName);
if (!sheet) {
sheet = spreadsheet.insertSheet(formName);
setHeaders(sheet, []);
sheet.addDeveloperMetadata("creationDate", new Date().toISOString());
}
return sheet;
}
/**
* Performs data analysis on the sheet.
*/
function performDataAnalysis(sheet) {
const data = sheet.getDataRange().getValues();
const headers = data[0];
const values = data.slice(1);
// Implement various data analysis techniques here
const analysis = {
totalSubmissions: values.length,
averages: calculateAverages(headers, values),
trends: identifyTrends(headers, values),
anomalies: detectAnomalies(headers, values),
};
// Store analysis results in a separate sheet
const analysisSheet = getOrCreateSheet(sheet.getName() + "_Analysis");
updateAnalysisSheet(analysisSheet, analysis);
}
/**
* Calculates averages for numeric columns.
*/
function calculateAverages(headers, values) {
const averages = {};
headers.forEach((header, index) => {
if (values.every((row) => !isNaN(row[index]))) {
const sum = values.reduce(
(acc, row) => acc + Number(row[index]),
0,
);
averages[header] = sum / values.length;
}
});
return averages;
}
/**
* Identifies trends in the data.
*/
function identifyTrends(headers, values) {
// Implement trend identification logic
return {};
}
/**
* Detects anomalies in the data.
*/
function detectAnomalies(headers, values) {
const anomalies = {};
headers.forEach((header, index) => {
if (values.every((row) => !isNaN(row[index]))) {
const numbers = values.map((row) => Number(row[index]));
const mean = numbers.reduce((a, b) => a + b) / numbers.length;
const std = Math.sqrt(
numbers
.map((x) => Math.pow(x - mean, 2))
.reduce((a, b) => a + b) / numbers.length,
);
anomalies[header] = numbers.filter(
(x) => Math.abs(x - mean) > CONFIG.anomalyThreshold * std,
);
}
});
return anomalies;
}
/**
* Updates the analysis sheet with new data.
*/
function updateAnalysisSheet(sheet, analysis) {
sheet.clear();
const headers = ["Metric", "Value"];
setHeaders(sheet, headers);
const rows = [
["Total Submissions", analysis.totalSubmissions],
...Object.entries(analysis.averages).map(([key, value]) => [
`Average ${key}`,
value,
]),
...Object.entries(analysis.trends).map(([key, value]) => [
`Trend: ${key}`,
value,
]),
...Object.entries(analysis.anomalies).flatMap(([key, values]) =>
values.map((value, index) => [
`Anomaly in ${key} #${index + 1}`,
value,
]),
),
];
sheet.getRange(2, 1, rows.length, 2).setValues(rows);
}
/**
* Sends an intelligent email notification with form submission details and analysis.
*/
function sendIntelligentNotification(data, sheetUrl, sheet) {
const analysis = performQuickAnalysis(sheet);
const subject = `New ${data.processed_data.priority} Priority Submission: ${data["form_name"] || "Form"}`;
const message = `
A new submission has been received and recorded in your Google Sheet.
Form Name: ${data["form_name"] || "N/A"}
Submission Time: ${data.timestamp}
Priority: ${data.processed_data.priority}
Category: ${data.processed_data.category}
Sentiment: ${data.processed_data.sentiment}
Quick Analysis:
- Total Submissions: ${analysis.totalSubmissions}
- Submission Trend: ${analysis.submissionTrend}
${analysis.anomalies.length > 0 ? `- Anomalies Detected: ${analysis.anomalies.join(", ")}` : ""}
Sheet URL: ${sheetUrl}
This is an automated notification. Please review the submission and take appropriate action.
`;
MailApp.sendEmail(CONFIG.emailAddress, subject, message);
}
/**
* Performs a quick analysis for the notification.
*/
function performQuickAnalysis(sheet) {
const data = sheet.getDataRange().getValues();
const values = data.slice(1);
return {
totalSubmissions: values.length,
submissionTrend: calculateSubmissionTrend(values),
anomalies: detectQuickAnomalies(data[0], values),
};
}
/**
* Calculates the submission trend.
*/
function calculateSubmissionTrend(values) {
const recentSubmissions = values.slice(-10).length;
const previousSubmissions = values.slice(-20, -10).length;
const trend =
((recentSubmissions - previousSubmissions) / previousSubmissions) * 100;
if (trend > 10) return "Increasing";
if (trend < -10) return "Decreasing";
return "Stable";
}
/**
* Detects quick anomalies for the notification.
*/
function detectQuickAnomalies(headers, values) {
return headers
.map((header, index) => {
if (values.every((row) => !isNaN(row[index]))) {
const numbers = values.map((row) => Number(row[index]));
const mean = numbers.reduce((a, b) => a + b) / numbers.length;
const std = Math.sqrt(
numbers
.map((x) => Math.pow(x - mean, 2))
.reduce((a, b) => a + b) / numbers.length,
);
const lastValue = numbers[numbers.length - 1];
if (
Math.abs(lastValue - mean) >
CONFIG.anomalyThreshold * std
) {
return `${header} (${lastValue})`;
}
}
return null;
})
.filter(Boolean);
}
/**
* Cleans up old data based on retention policy.
*/
function cleanupOldData(sheet) {
const data = sheet.getDataRange().getValues();
const headers = data[0];
const values = data.slice(1);
const timestampIndex = headers.findIndex((header) =>
header.toLowerCase().includes("timestamp"),
);
if (timestampIndex === -1) return;
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - CONFIG.dataRetentionDays);
const rowsToDelete = values.reduce((acc, row, index) => {
const timestamp = new Date(row[timestampIndex]);
if (timestamp < cutoffDate) {
// +2 because we need to account for the header row and 1-based indexing
acc.push(index + 2);
}
return acc;
}, []);
if (rowsToDelete.length > 0) {
sheet.deleteRows(rowsToDelete[0], rowsToDelete.length);
}
}
/**
* Advanced error handling and logging.
*/
function handleError(error) {
Logger.log(`Error: ${error.message}`);
Logger.log(`Stack: ${error.stack}`);
// You could implement more advanced error handling here, such as:
// - Sending error notifications to administrators
// - Logging errors to a separate sheet for analysis
// - Implementing a circuit breaker pattern for repeated errors
}