-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathCode.js
More file actions
209 lines (194 loc) · 6.33 KB
/
Copy pathCode.js
File metadata and controls
209 lines (194 loc) · 6.33 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
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
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/equipment-requests
/*
Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Update this variable with the email address you want to send equipment requests to.
const REQUEST_NOTIFICATION_EMAIL = "request_intake@example.com";
// Update the following variables with your own equipment options.
const AVAILABLE_LAPTOPS = [
'15" high Performance Laptop (OS X)',
'15" high Performance Laptop (Windows)',
'15" high performance Laptop (Linux)',
'13" lightweight laptop (Windows)',
];
const AVAILABLE_DESKTOPS = [
"Standard workstation (Windows)",
"Standard workstation (Linux)",
"High performance workstation (Windows)",
"High performance workstation (Linux)",
"Mac Pro (OS X)",
];
const AVAILABLE_MONITORS = ['Single 27"', 'Single 32"', 'Dual 24"'];
// Form field titles, used for creating the form and as keys when handling
// responses.
/**
* Adds a custom menu to the spreadsheet.
*/
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("Equipment requests")
.addItem("Set up", "setup_")
.addItem("Clean up", "cleanup_")
.addToUi();
}
/**
* Creates the form and triggers for the workflow.
*/
function setup_() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (ss.getFormUrl()) {
const msg = "Form already exists. Unlink the form and try again.";
SpreadsheetApp.getUi().alert(msg);
return;
}
const form = FormApp.create("Equipment Requests")
.setCollectEmail(true)
.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId())
.setLimitOneResponsePerUser(false);
form.addTextItem().setTitle("Employee name").setRequired(true);
form.addTextItem().setTitle("Desk location").setRequired(true);
form.addDateItem().setTitle("Due date").setRequired(true);
form.addListItem().setTitle("Laptop").setChoiceValues(AVAILABLE_LAPTOPS);
form.addListItem().setTitle("Desktop").setChoiceValues(AVAILABLE_DESKTOPS);
form.addListItem().setTitle("Monitor").setChoiceValues(AVAILABLE_MONITORS);
// Hide the raw form responses.
for (const sheet of ss.getSheets()) {
if (sheet.getFormUrl() === ss.getFormUrl()) {
sheet.hideSheet();
}
}
// Start workflow on each form submit
ScriptApp.newTrigger("onFormSubmit_").forForm(form).onFormSubmit().create();
// Archive completed items every 5m.
ScriptApp.newTrigger("processCompletedItems_")
.timeBased()
.everyMinutes(5)
.create();
}
/**
* Cleans up the project (stop triggers, form submission, etc.)
*/
function cleanup_() {
const formUrl = SpreadsheetApp.getActiveSpreadsheet().getFormUrl();
if (!formUrl) {
return;
}
for (const trigger of ScriptApp.getProjectTriggers()) {
ScriptApp.deleteTrigger(trigger);
}
FormApp.openByUrl(formUrl).deleteAllResponses().setAcceptingResponses(false);
}
/**
* Handles new form submissions to trigger the workflow.
*
* @param {Object} event - Form submit event
*/
function onFormSubmit_(event) {
const response = mapResponse_(event.response);
sendNewEquipmentRequestEmail_(response);
const equipmentDetails = Utilities.formatString(
"%s\n%s\n%s",
response.Laptop,
response.Desktop,
response.Monitor,
);
const row = [
"New",
"",
response["Due date"],
response["Employee name"],
response["Desk location"],
equipmentDetails,
response.email,
];
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Pending requests");
sheet.appendRow(row);
}
/**
* Sweeps completed and cancelled requests, notifying the requestors and archiving them
* to the completed sheet.
*
* @param {Object} event
*/
function processCompletedItems_() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const pending = ss.getSheetByName("Pending requests");
const completed = ss.getSheetByName("Completed requests");
const rows = pending.getDataRange().getValues();
for (let i = rows.length; i >= 2; i--) {
const row = rows[i - 1];
const status = row[0];
if (status === "Completed" || status === "Cancelled") {
pending.deleteRow(i);
completed.appendRow(row);
console.log(`Deleted row: ${i}`);
sendEquipmentRequestCompletedEmail_({
"Employee name": row[3],
"Desk location": row[4],
email: row[6],
});
}
}
}
/**
* Sends an email notification that a new equipment request has been submitted.
*
* @param {Object} request - Request details
*/
function sendNewEquipmentRequestEmail_(request) {
const template = HtmlService.createTemplateFromFile(
"new-equipment-request.html",
);
template.request = request;
template.sheetUrl = SpreadsheetApp.getActiveSpreadsheet().getUrl();
const msg = template.evaluate();
MailApp.sendEmail({
to: REQUEST_NOTIFICATION_EMAIL,
subject: "New equipment request",
htmlBody: msg.getContent(),
});
}
/**
* Sends an email notifying the requestor that the request is complete.
*
* @param {Object} request - Request details
*/
function sendEquipmentRequestCompletedEmail_(request) {
const template = HtmlService.createTemplateFromFile("request-complete.html");
template.request = request;
const msg = template.evaluate();
MailApp.sendEmail({
to: request.email,
subject: "Equipment request completed",
htmlBody: msg.getContent(),
});
}
/**
* Converts a form response to an object keyed by the item titles. Allows easier
* access to response values.
*
* @param {FormResponse} response
* @return {Object} Form values keyed by question title
*/
function mapResponse_(response) {
const initialValue = {
email: response.getRespondentEmail(),
timestamp: response.getTimestamp(),
};
return response.getItemResponses().reduce((obj, itemResponse) => {
const key = itemResponse.getItem().getTitle();
obj[key] = itemResponse.getResponse();
return obj;
}, initialValue);
}