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
| const SHEET_ID = '你的試算表ID'; // 記得改成你的ID
const CONFIG_SHEET = '設定';
// 自動偵測消費和收入的科目範圍
function getCategoryRanges() {
const ss = SpreadsheetApp.openById(SHEET_ID);
const sheet = ss.getSheetByName(CONFIG_SHEET);
const firstRow = sheet.getRange('1:1').getValues()[0];
const ranges = {};
let currentType = null;
let startCol = null;
firstRow.forEach((cell, index) => {
const col = index + 1;
// 找到標記
if (cell === '[消費]') {
currentType = '消費';
startCol = col + 1; // 科目從下一欄開始
} else if (cell === '[收入]') {
// 儲存消費範圍
if (currentType === '消費' && startCol) {
const endCol = col - 1;
ranges['消費'] = sheet.getRange(1, startCol, 1, endCol - startCol + 1);
}
currentType = '收入';
startCol = col + 1;
}
});
// 儲存收入範圍(到最後)
if (currentType === '收入' && startCol) {
const lastCol = firstRow.length;
// 找到收入的最後一個有值的欄位
let endCol = startCol;
for (let i = startCol; i <= lastCol; i++) {
if (firstRow[i - 1]) endCol = i;
}
ranges['收入'] = sheet.getRange(1, startCol, 1, endCol - startCol + 1);
}
return ranges;
}
function doGet(e) {
const action = e.parameter.action;
let result;
if (action === 'getConfig') {
result = getConfig();
} else {
result = ContentService.createTextOutput('{}');
}
return result.setMimeType(ContentService.MimeType.JSON);
}
function doPost(e) {
try {
const params = JSON.parse(e.postData.contents);
const action = params.action;
if (action === 'addEntry') return addEntry(params);
return ContentService.createTextOutput(JSON.stringify({ success: false, error: 'unknown action', action: action }))
.setMimeType(ContentService.MimeType.JSON);
} catch(err) {
return ContentService.createTextOutput(JSON.stringify({ success: false, error: err.toString() }))
.setMimeType(ContentService.MimeType.JSON);
}
}
function getConfig() {
const ss = SpreadsheetApp.openById(SHEET_ID);
const sheet = ss.getSheetByName(CONFIG_SHEET);
const data = sheet.getDataRange().getValues();
const headers = data[0];
const config = {
帳戶: [],
類型: [],
消費科目: [], // 陣列
收入科目: [], // 陣列
次科目: {}
};
headers.forEach((header, colIndex) => {
if (!header) return;
// 跳過標記欄位
if (header === '[消費]' || header === '[收入]') return;
const values = [];
for (let row = 1; row < data.length; row++) {
if (data[row][colIndex]) values.push(data[row][colIndex]);
}
if (header === '帳戶') {
config.帳戶 = values;
} else if (header === '類型') {
config.類型 = values;
} else {
// 判斷是消費還是收入科目
let categoryType = '消費';
for (let i = colIndex - 1; i >= 0; i--) {
if (headers[i] === '[收入]') {
categoryType = '收入';
break;
} else if (headers[i] === '[消費]') {
categoryType = '消費';
break;
}
}
// 加入陣列(保持順序)
if (categoryType === '消費') {
config.消費科目.push(header);
} else {
config.收入科目.push(header);
}
// 儲存次科目
config.次科目[header] = values;
}
});
return ContentService.createTextOutput(JSON.stringify(config))
.setMimeType(ContentService.MimeType.JSON);
}
function addEntry(data) {
const ss = SpreadsheetApp.openById(SHEET_ID);
// 從日期取年份
let year;
if (data.date) {
const dateStr = String(data.date);
if (dateStr.includes('-')) {
year = dateStr.split('-')[0];
} else if (dateStr.includes('/')) {
year = dateStr.split('/')[0];
} else {
year = new Date().getFullYear().toString();
}
} else {
year = new Date().getFullYear().toString();
}
let sheet = ss.getSheetByName(year);
if (!sheet) {
sheet = ss.insertSheet(year);
sheet.appendRow(['日期', '類型', '科目', '次科目', '帳戶', '金額', '摘要']);
}
sheet.appendRow([
data.date,
data.type,
data.category,
data.subcategory,
data.account,
data.amount,
data.note
]);
const lastRow = sheet.getLastRow();
// 先為新增的這一行設定驗證
updateTypeValidation(sheet, lastRow);
updateCategoryValidation(sheet, lastRow);
updateSubcategoryValidation(sheet, lastRow);
updateAccountValidation(sheet, lastRow);
// 再排序
if (lastRow > 2) {
sheet.getRange(2, 1, lastRow - 1, 7).sort({ column: 1, ascending: true });
}
return ContentService.createTextOutput(JSON.stringify({ success: true }))
.setMimeType(ContentService.MimeType.JSON);
}
// === 連動下拉選單功能 ===
// 當編輯儲存格時觸發
function onEdit(e) {
const sheet = e.source.getActiveSheet();
const range = e.range;
// 跳過設定分頁和統計分頁
if (sheet.getName() === CONFIG_SHEET || sheet.getName() === '統計') return;
const col = range.getColumn();
const row = range.getRow();
// 處理類型欄(B 欄)的變更 → 更新科目
if (col === 2) {
updateCategoryValidation(sheet, row);
updateSubcategoryValidation(sheet, row);
}
// 處理科目欄(C 欄)的變更 → 更新次科目
if (col === 3) {
updateSubcategoryValidation(sheet, row);
}
}
// 設定類型的驗證
function updateTypeValidation(sheet, row) {
const typeCell = sheet.getRange(row, 2); // B 欄:類型
try {
const ss = SpreadsheetApp.openById(SHEET_ID);
const configSheet = ss.getSheetByName(CONFIG_SHEET);
const range = configSheet.getRange('A2:A3'); // 類型範圍
const rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(range, true)
.setAllowInvalid(false)
.build();
typeCell.setDataValidation(rule);
} catch (err) {
Logger.log('updateTypeValidation error: ' + err);
}
}
// 根據類型更新科目的驗證
function updateCategoryValidation(sheet, row) {
const typeCell = sheet.getRange(row, 2); // B 欄:類型
const categoryCell = sheet.getRange(row, 3); // C 欄:科目
const type = typeCell.getValue();
const currentCategory = categoryCell.getValue();
// 如果類型欄是空的,清除科目驗證和內容
if (!type) {
categoryCell.clearDataValidations();
categoryCell.clearContent();
return;
}
try {
const ranges = getCategoryRanges();
const range = ranges[type];
if (!range) {
categoryCell.clearDataValidations();
categoryCell.clearContent();
return;
}
// 取得有效的科目清單
const validCategories = range.getValues()[0].filter(v => v !== '');
// 如果當前科目不在新範圍內,清除內容
if (currentCategory && !validCategories.includes(currentCategory)) {
categoryCell.clearContent();
}
// 設定新的驗證
const rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(range, true)
.setAllowInvalid(false)
.build();
categoryCell.setDataValidation(rule);
} catch (err) {
Logger.log('updateCategoryValidation error: ' + err);
}
}
// 根據科目更新次科目的驗證
function updateSubcategoryValidation(sheet, row) {
const categoryCell = sheet.getRange(row, 3); // C 欄:科目
const subcategoryCell = sheet.getRange(row, 4); // D 欄:次科目
const category = categoryCell.getValue();
const currentSubcategory = subcategoryCell.getValue();
// 如果科目欄是空的,清除次科目驗證和內容
if (!category) {
subcategoryCell.clearDataValidations();
subcategoryCell.clearContent();
return;
}
// 嘗試從命名範圍取得次科目清單
try {
const ss = SpreadsheetApp.openById(SHEET_ID);
const namedRange = ss.getNamedRanges().find(nr => nr.getName() === category);
if (namedRange) {
const range = namedRange.getRange();
const validValues = range.getValues().flat().filter(v => v !== '');
// 如果次科目不在新範圍內,清除內容
if (currentSubcategory && !validValues.includes(currentSubcategory)) {
subcategoryCell.clearContent();
}
// 設定新的驗證
const rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(range, true)
.setAllowInvalid(false)
.build();
subcategoryCell.setDataValidation(rule);
} else {
// 找不到對應的命名範圍,清除驗證和內容
subcategoryCell.clearDataValidations();
subcategoryCell.clearContent();
}
} catch (err) {
Logger.log('updateSubcategoryValidation error: ' + err);
}
}
// 設定帳戶的驗證
function updateAccountValidation(sheet, row) {
const accountCell = sheet.getRange(row, 5); // E 欄:帳戶
try {
const ss = SpreadsheetApp.openById(SHEET_ID);
const configSheet = ss.getSheetByName(CONFIG_SHEET);
const range = configSheet.getRange('B2:B6'); // 帳戶範圍
const rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(range, true)
.setAllowInvalid(false)
.build();
accountCell.setDataValidation(rule);
} catch (err) {
Logger.log('updateAccountValidation error: ' + err);
}
}
// 手動執行:為整個工作表設定所有驗證(批次版,更快)
function setupAllValidations() {
const ss = SpreadsheetApp.openById(SHEET_ID);
const sheets = ss.getSheets();
const categoryRanges = getCategoryRanges();
const configSheet = ss.getSheetByName(CONFIG_SHEET);
sheets.forEach(sheet => {
// 跳過設定分頁和統計分頁
if (sheet.getName() === CONFIG_SHEET || sheet.getName() === '統計') return;
const lastRow = sheet.getLastRow();
if (lastRow < 2) return; // 只有標題列
Logger.log(`處理分頁: ${sheet.getName()}, ${lastRow - 1} 筆資料`);
// === 批次設定類型驗證 ===
const typeRange = configSheet.getRange('A2:A3');
const typeRule = SpreadsheetApp.newDataValidation()
.requireValueInRange(typeRange, true)
.setAllowInvalid(false)
.build();
for (let row = 2; row <= lastRow; row++) {
sheet.getRange(row, 2).setDataValidation(typeRule);
}
// === 批次設定科目驗證 ===
// 先清除 C 欄所有驗證
sheet.getRange(2, 3, lastRow - 1, 1).clearDataValidations();
// 取得所有類型值
const types = sheet.getRange(2, 2, lastRow - 1, 1).getValues().flat();
// 按類型分組
const typeGroups = { '消費': [], '收入': [] };
types.forEach((type, index) => {
const row = index + 2;
if (typeGroups[type]) {
typeGroups[type].push(row);
}
});
// 為每個類型批次設定科目驗證
Object.keys(typeGroups).forEach(type => {
const rows = typeGroups[type];
if (rows.length === 0) return;
const range = categoryRanges[type];
if (!range) return;
const rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(range, true)
.setAllowInvalid(false)
.build();
// 批次設定這個類型的所有行
rows.forEach(row => {
sheet.getRange(row, 3).setDataValidation(rule);
});
});
// === 批次設定次科目驗證 ===
// 先清除 D 欄所有驗證
sheet.getRange(2, 4, lastRow - 1, 1).clearDataValidations();
// 取得所有科目值
const categories = sheet.getRange(2, 3, lastRow - 1, 1).getValues().flat();
// 按科目分組
const categoryGroups = {};
categories.forEach((cat, index) => {
const row = index + 2;
if (!cat) return;
if (!categoryGroups[cat]) categoryGroups[cat] = [];
categoryGroups[cat].push(row);
});
// 為每個科目批次設定次科目驗證
Object.keys(categoryGroups).forEach(category => {
const rows = categoryGroups[category];
const namedRange = ss.getNamedRanges().find(nr => nr.getName() === category);
if (namedRange) {
const range = namedRange.getRange();
const rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(range, true)
.setAllowInvalid(false)
.build();
// 批次設定這個科目的所有行
rows.forEach(row => {
sheet.getRange(row, 4).setDataValidation(rule);
});
}
});
// === 批次設定帳戶驗證 ===
const accountRange = configSheet.getRange('B2:B6');
const accountRule = SpreadsheetApp.newDataValidation()
.requireValueInRange(accountRange, true)
.setAllowInvalid(false)
.build();
for (let row = 2; row <= lastRow; row++) {
sheet.getRange(row, 5).setDataValidation(accountRule);
}
});
Logger.log('所有驗證設定完成!');
}
|