-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
239 lines (200 loc) · 5.73 KB
/
Copy pathCode.gs
File metadata and controls
239 lines (200 loc) · 5.73 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
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
// Configuration
const CONFIG = {
SPREADSHEET_ID: '1LE9j22gEmi5oLNH7EawEA1DMn9T7C6fuoj6Uyir3YUQ',
FORM_ID: '1tqBYTZ73YK9pQPVttVcJUwB2nHMtOlssrmSKCdMRNU',
AUTHORIZED_USERS: [
'ucmerced@saseconnect.org',
'addisonxchen@gmail.com'
]
};
/**
* Main function triggered when form is submitted
*/
function onFormSubmit(e) {
if (!e || !e.response) {
Logger.log('Error: Invalid event object');
return;
}
try {
const formResponse = e.response;
const itemResponses = formResponse.getItemResponses();
// Extract form data
const formData = extractFormData(itemResponses);
if (!formData.fileId) {
Logger.log('No file uploaded in form submission');
return;
}
// Process the uploaded file
processUploadedFile(formData);
Logger.log('Form submission processed successfully');
} catch (error) {
Logger.log('Error processing form submission: ' + error.toString());
}
}
/**
* Extract form data from responses
*/
function extractFormData(itemResponses) {
const data = {
fileId: null,
email: null
};
for (const item of itemResponses) {
const title = item.getItem().getTitle();
const response = item.getResponse();
if (title === 'Upload your photo') {
data.fileId = response;
} else if (title === 'Email') {
data.email = response;
}
}
return data;
}
/**
* Process the uploaded file
*/
function processUploadedFile(formData) {
const file = DriveApp.getFileById(formData.fileId);
// Share with authorized users
shareFileWithUsers(file, CONFIG.AUTHORIZED_USERS);
// Share with form respondent if email was provided
if (formData.email) {
file.addViewer(formData.email);
}
// Store the file URL in spreadsheet
storeFileUrlInSpreadsheet(file.getUrl());
}
/**
* Share file with list of users
*/
function shareFileWithUsers(file, users) {
users.forEach(email => {
try {
file.addViewer(email);
} catch (error) {
Logger.log(`Error sharing file with ${email}: ${error.toString()}`);
}
});
}
/**
* Store file URL in spreadsheet
*/
function storeFileUrlInSpreadsheet(fileUrl) {
const ss = SpreadsheetApp.openById(CONFIG.SPREADSHEET_ID);
const sheet = ss.getSheetByName('Form Responses 1');
const lastRow = sheet.getLastRow();
// Find or create Photo URL column
const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
let photoUrlColumnIndex = headers.indexOf('Photo URL') + 1;
if (photoUrlColumnIndex === 0) {
photoUrlColumnIndex = sheet.getLastColumn() + 1;
sheet.getRange(1, photoUrlColumnIndex).setValue('Photo URL');
}
// Store URL in the last row
sheet.getRange(lastRow, photoUrlColumnIndex).setValue(fileUrl);
}
/**
* Handle HTTP GET requests to serve the data
*/
function doGet(e) {
const output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.JSON);
try {
const profiles = getAllProfiles();
output.setContent(JSON.stringify(profiles));
} catch (error) {
Logger.log('Error in doGet: ' + error.toString());
output.setContent(JSON.stringify({
error: true,
message: error.toString()
}));
}
return output;
}
/**
* Handle OPTIONS requests for CORS preflight
*/
function doOptions(e) {
return ContentService.createTextOutput()
.setMimeType(ContentService.MimeType.TEXT);
}
/**
* Get all profiles from the spreadsheet
*/
function getAllProfiles() {
const ss = SpreadsheetApp.openById(CONFIG.SPREADSHEET_ID);
const sheet = ss.getSheetByName('Form Responses 1');
if (!sheet) {
throw new Error("Sheet 'Form Responses 1' not found");
}
const data = sheet.getDataRange().getValues();
if (data.length <= 1) return [];
const headers = data[0];
const photoUrlIndex = headers.indexOf('Photo URL');
return data.slice(1).map((row, index) => {
const profile = {
ID: `chair-${index + 1}`,
Timestamp: new Date().toISOString()
};
headers.forEach((header, i) => {
if (header) {
const propertyName = getPropertyName(header);
profile[propertyName] = row[i] || '';
}
});
if (photoUrlIndex >= 0) {
profile['PhotoUrl'] = row[photoUrlIndex] || '';
profile['Photo URL'] = row[photoUrlIndex] || '';
}
return profile;
});
}
/**
* Map form field names to profile property names
*/
function getPropertyName(header) {
const mappings = {
'Full Name': 'Name',
'Academic Year': 'Year',
'Major': 'Major',
'Department Chair Position': 'Department',
'Leadership Quote': 'Quote',
'Areas of Expertise': 'Expertise',
'Notable Achievements': 'Achievements',
'Qualifications': 'Qualifications'
};
return mappings[header] || header;
}
/**
* Set up the form submission trigger
*/
function createFormSubmitTrigger() {
// Remove existing triggers
ScriptApp.getProjectTriggers()
.filter(trigger => trigger.getHandlerFunction() === 'onFormSubmit')
.forEach(trigger => ScriptApp.deleteTrigger(trigger));
// Create new trigger
const form = FormApp.openById(CONFIG.FORM_ID);
ScriptApp.newTrigger('onFormSubmit')
.forForm(form)
.onFormSubmit()
.create();
Logger.log('Form submit trigger created successfully');
}
/**
* Test function to verify getAllProfiles is working
*/
function testGetAllProfiles() {
try {
const profiles = getAllProfiles();
Logger.log(`Found ${profiles.length} profiles`);
if (profiles.length > 0) {
Logger.log('Sample profile:');
Logger.log(JSON.stringify(profiles[0], null, 2));
}
return 'Success! Found ' + profiles.length + ' profiles.';
} catch (error) {
Logger.log('Error in testGetAllProfiles: ' + error.toString());
return 'Error: ' + error.toString();
}
}