deepak191z commited on
Commit
455c04c
·
verified ·
1 Parent(s): adf2bbe

Create script.j

Browse files
Files changed (1) hide show
  1. script.j +281 -0
script.j ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generate Google Apps Script
2
+ function generateScript(columns) {
3
+ return `
4
+ function doGet(e) {
5
+ try {
6
+ const action = e.parameter.action;
7
+ const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
8
+
9
+ switch (action) {
10
+ case 'search':
11
+ return handleSearchGet(sheet, e.parameter.q);
12
+ case 'fetch':
13
+ const startRow = e.parameter.startRow ? parseInt(e.parameter.startRow) : null;
14
+ const endRow = e.parameter.endRow ? parseInt(e.parameter.endRow) : null;
15
+ return handleFetchGet(sheet, startRow, endRow);
16
+ default:
17
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid action.' })).setMimeType(ContentService.MimeType.JSON);
18
+ }
19
+ } catch (error) {
20
+ Logger.log(error);
21
+ return ContentService.createTextOutput(JSON.stringify({ error: error.message })).setMimeType(ContentService.MimeType.JSON);
22
+ }
23
+ }
24
+
25
+ function doPost(e) {
26
+ try {
27
+ if (e.postData.type !== 'application/json') {
28
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid content type. Only JSON is accepted.' })).setMimeType(ContentService.MimeType.JSON);
29
+ }
30
+
31
+ const data = JSON.parse(e.postData.contents);
32
+ const action = data.action;
33
+ const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
34
+
35
+ switch (action) {
36
+ case 'append':
37
+ return handleAppend(sheet, data.rows);
38
+ case 'search':
39
+ return handleSearch(sheet, data.q);
40
+ case 'update':
41
+ return handleUpdate(sheet, data.row, ${columns.map(col => `data.${col}`).join(', ')});
42
+ case 'delete':
43
+ return handleDelete(sheet, data.row);
44
+ case 'fetch':
45
+ return handleFetch(sheet, data.row, data.endRow);
46
+ default:
47
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid action.' })).setMimeType(ContentService.MimeType.JSON);
48
+ }
49
+ } catch (error) {
50
+ Logger.log(error);
51
+ return ContentService.createTextOutput(JSON.stringify({ error: error.message })).setMimeType(ContentService.MimeType.JSON);
52
+ }
53
+ }
54
+
55
+ function handleAppend(sheet, rows) {
56
+ if (!Array.isArray(rows) || rows.length === 0) {
57
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid rows data.' })).setMimeType(ContentService.MimeType.JSON);
58
+ }
59
+
60
+ const values = rows.map(row => [${columns.map(col => `row.${col}`).join(', ')}]);
61
+ sheet.getRange(sheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
62
+
63
+ return ContentService.createTextOutput(JSON.stringify({ success: true, rowsAdded: rows.length })).setMimeType(ContentService.MimeType.JSON);
64
+ }
65
+
66
+ function handleSearch(sheet, query) {
67
+ if (!query) {
68
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Search query is required.' })).setMimeType(ContentService.MimeType.JSON);
69
+ }
70
+
71
+ const data = sheet.getDataRange().getValues();
72
+ const results = data.filter(row => ${columns.map((col, i) => `row[${i}].toLowerCase().includes(query.toLowerCase())`).join(' || ')});
73
+
74
+ return ContentService.createTextOutput(JSON.stringify(results)).setMimeType(ContentService.MimeType.JSON);
75
+ }
76
+
77
+ function handleSearchGet(sheet, query) {
78
+ if (!query) {
79
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Search query is required.' })).setMimeType(ContentService.MimeType.JSON);
80
+ }
81
+
82
+ const data = sheet.getDataRange().getValues();
83
+ const results = data.filter(row => ${columns.map((col, i) => `row[${i}].toLowerCase().includes(query.toLowerCase())`).join(' || ')});
84
+
85
+ return ContentService.createTextOutput(JSON.stringify(results)).setMimeType(ContentService.MimeType.JSON);
86
+ }
87
+
88
+ function handleUpdate(sheet, rowIndex, ${columns.join(', ')}) {
89
+ if (!rowIndex || ${columns.map(col => `!${col}`).join(' || ')}) {
90
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid update data.' })).setMimeType(ContentService.MimeType.JSON);
91
+ }
92
+
93
+ const row = rowIndex + 1;
94
+ if (row > sheet.getLastRow()) {
95
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Row index out of range.' })).setMimeType(ContentService.MimeType.JSON);
96
+ }
97
+
98
+ ${columns.map((col, i) => ` sheet.getRange(row, ${i + 1}).setValue(${col});`).join('\n')}
99
+
100
+ return ContentService.createTextOutput(JSON.stringify({ success: true })).setMimeType(ContentService.MimeType.JSON);
101
+ }
102
+
103
+ function handleDelete(sheet, rowIndex) {
104
+ if (!rowIndex) {
105
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Row index is required.' })).setMimeType(ContentService.MimeType.JSON);
106
+ }
107
+
108
+ const row = rowIndex + 1;
109
+ if (row > sheet.getLastRow()) {
110
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Row index out of range.' })).setMimeType(ContentService.MimeType.JSON);
111
+ }
112
+
113
+ sheet.deleteRow(row);
114
+ return ContentService.createTextOutput(JSON.stringify({ success: true })).setMimeType(ContentService.MimeType.JSON);
115
+ }
116
+
117
+ function handleFetch(sheet, startRow, endRow) {
118
+ const lastRow = sheet.getLastRow();
119
+ startRow = startRow ? startRow + 1 : 1;
120
+ endRow = endRow ? endRow + 1 : lastRow;
121
+
122
+ if (startRow > lastRow || endRow > lastRow || startRow > endRow) {
123
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid row range.' })).setMimeType(ContentService.MimeType.JSON);
124
+ }
125
+
126
+ const data = sheet.getRange(startRow, 1, endRow - startRow + 1, ${columns.length}).getValues();
127
+ return ContentService.createTextOutput(JSON.stringify(data)).setMimeType(ContentService.MimeType.JSON);
128
+ }
129
+
130
+ function handleFetchGet(sheet, startRow, endRow) {
131
+ const lastRow = sheet.getLastRow();
132
+ startRow = startRow ? startRow + 1 : 1;
133
+ endRow = endRow ? endRow + 1 : lastRow;
134
+
135
+ if (startRow > lastRow || endRow > lastRow || startRow > endRow) {
136
+ return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid row range.' })).setMimeType(ContentService.MimeType.JSON);
137
+ }
138
+
139
+ const data = sheet.getRange(startRow, 1, endRow - startRow + 1, ${columns.length}).getValues();
140
+ return ContentService.createTextOutput(JSON.stringify(data)).setMimeType(ContentService.MimeType.JSON);
141
+ }`.trim();
142
+ }
143
+
144
+ // Generate cURL examples as an object
145
+ function generateCurlExamples(columns) {
146
+ const sampleValues = columns.map((col, i) => [col, `Sample ${col} ${i + 1}`]);
147
+ return {
148
+ appendSingle: `
149
+ curl -X POST "https://script.google.com/macros/s/YOUR_SCRIPT_ID/exec" \\
150
+ -H "Content-Type: application/json" \\
151
+ -d '{
152
+ "action": "append",
153
+ "rows": [{
154
+ ${sampleValues.map(([col, val]) => `"${col}": "${val}"`).join(',\n ')}
155
+ }]
156
+ }'`.trim(),
157
+ appendMultiple: `
158
+ curl -X POST "https://script.google.com/macros/s/YOUR_SCRIPT_ID/exec" \\
159
+ -H "Content-Type: application/json" \\
160
+ -d '{
161
+ "action": "append",
162
+ "rows": [
163
+ { ${sampleValues.map(([col, val]) => `"${col}": "${val}"`).join(', ')} },
164
+ { ${sampleValues.map(([col, val]) => `"${col}": "Another ${val}"`).join(', ')} }
165
+ ]
166
+ }'`.trim(),
167
+ fetchAll: `
168
+ curl "https://script.google.com/macros/s/YOUR_WEB_APP_ID/exec?action=fetch"`.trim(),
169
+ fetchRange: `
170
+ curl "https://script.google.com/macros/s/YOUR_WEB_APP_ID/exec?action=fetch&startRow=50&endRow=100"`.trim(),
171
+ search: `
172
+ curl "https://script.google.com/macros/s/YOUR_WEB_APP_ID/exec?action=search&q=sample"`.trim(),
173
+ update: `
174
+ curl -X POST "https://script.google.com/macros/s/YOUR_SCRIPT_ID/exec" \\
175
+ -H "Content-Type: application/json" \\
176
+ -d '{
177
+ "action": "update",
178
+ "row": 50,
179
+ ${sampleValues.map(([col, val]) => `"${col}": "Updated ${val}"`).join(',\n ')}
180
+ }'`.trim(),
181
+ delete: `
182
+ curl -X POST "https://script.google.com/macros/s/YOUR_SCRIPT_ID/exec" \\
183
+ -H "Content-Type: application/json" \\
184
+ -d '{
185
+ "action": "delete",
186
+ "row": 100
187
+ }'`.trim()
188
+ };
189
+ }
190
+
191
+ // Update previews
192
+ function updatePreviews() {
193
+ const columns = Array.from(document.querySelectorAll('.column-input'))
194
+ .map(input => input.value.trim())
195
+ .filter(value => value !== '');
196
+ document.getElementById('codePreview').textContent = generateScript(columns);
197
+ const curlExamples = generateCurlExamples(columns);
198
+ const activeButton = document.querySelector('.curl-button.active');
199
+ const exampleKey = activeButton ? activeButton.getAttribute('onclick').match(/'([^']+)'/)[1] : 'appendSingle';
200
+ document.getElementById('curlExamples').textContent = curlExamples[exampleKey];
201
+ }
202
+
203
+ // Add new column
204
+ function addColumn() {
205
+ const container = document.getElementById('columnInputs');
206
+ const div = document.createElement('div');
207
+ div.innerHTML = `
208
+ <div class="flex space-x-2">
209
+ <input type="text" class="column-input flex-1 px-3 py-2 border rounded-md" placeholder="Column name">
210
+ <button onclick="removeColumn(this)" class="bg-red-500 text-white px-2 py-1 rounded hover:bg-red-600">X</button>
211
+ </div>
212
+ `;
213
+ container.appendChild(div);
214
+ updatePreviews();
215
+ }
216
+
217
+ // Remove column
218
+ function removeColumn(button) {
219
+ button.parentElement.parentElement.remove();
220
+ updatePreviews();
221
+ }
222
+
223
+ // Tab switching
224
+ function showTab(tabId) {
225
+ document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
226
+ document.getElementById(tabId).classList.add('active');
227
+ document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('border-blue-500'));
228
+ event.target.classList.add('border-blue-500');
229
+ }
230
+
231
+ // Show specific cURL example
232
+ function showCurlExample(exampleKey) {
233
+ const columns = Array.from(document.querySelectorAll('.column-input'))
234
+ .map(input => input.value.trim())
235
+ .filter(value => value !== '');
236
+ const curlExamples = generateCurlExamples(columns);
237
+ document.getElementById('curlExamples').textContent = curlExamples[exampleKey];
238
+ document.querySelectorAll('.curl-button').forEach(btn => btn.classList.remove('active'));
239
+ event.target.classList.add('active');
240
+ }
241
+
242
+ // Copy code to clipboard
243
+ function copyCode() {
244
+ const code = document.getElementById('codePreview').textContent;
245
+ if (navigator.clipboard && navigator.clipboard.writeText) {
246
+ navigator.clipboard.writeText(code).then(() => {
247
+ alert('Code copied to clipboard!');
248
+ }).catch(err => {
249
+ console.error('Failed to copy: ', err);
250
+ fallbackCopy(code);
251
+ });
252
+ } else {
253
+ fallbackCopy(code);
254
+ }
255
+ }
256
+
257
+ // Fallback for older browsers or restricted environments
258
+ function fallbackCopy(text) {
259
+ const textArea = document.createElement('textarea');
260
+ textArea.value = text;
261
+ document.body.appendChild(textArea);
262
+ textArea.select();
263
+ try {
264
+ document.execCommand('copy');
265
+ alert('Code copied to clipboard!');
266
+ } catch (err) {
267
+ alert('Failed to copy code. Please copy it manually.');
268
+ }
269
+ document.body.removeChild(textArea);
270
+ }
271
+
272
+ // Initialize
273
+ document.addEventListener('DOMContentLoaded', () => {
274
+ updatePreviews();
275
+ document.getElementById('columnInputs').addEventListener('input', updatePreviews);
276
+ // Set default active cURL button
277
+ const firstCurlButton = document.querySelector('.curl-button');
278
+ if (firstCurlButton) {
279
+ firstCurlButton.classList.add('active');
280
+ }
281
+ });