ichieh commited on
Commit
dc8d1ea
·
1 Parent(s): 984680d

修改桌次名稱同步

Browse files
Files changed (2) hide show
  1. app.py +19 -8
  2. sync_settings.gs +134 -106
app.py CHANGED
@@ -436,11 +436,9 @@ def backup_settings():
436
  def restore_data():
437
  try:
438
  # 從 Google Apps Script 獲取數據
439
- print("正在從 Google Apps Script 獲取數據...")
440
  response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
441
- print("Response status code:", response.status_code)
442
- print("Response headers:", response.headers)
443
- print("Response content:", response.text)
444
 
445
  try:
446
  data = response.json()
@@ -451,15 +449,28 @@ def restore_data():
451
 
452
  if not data.get('success'):
453
  error_msg = data.get('error', '從 Google Sheets 恢復資料失敗')
454
- print("Google Apps Script 返回錯誤:", error_msg)
455
  return jsonify({'error': error_msg}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
456
 
457
  # 清空現有的參與者資料
458
  Participant.query.delete()
459
 
460
  # 恢復參與者資料
461
  participants_data = data.get('participants', [])
462
- print(f"找到 {len(participants_data)} 個參與者資料")
463
 
464
  for participant_data in participants_data:
465
  # 處理 ISO 格式的時間
@@ -480,14 +491,14 @@ def restore_data():
480
  note=participant_data.get('note', '')
481
  )
482
  db.session.add(participant)
483
- print(f"已添加參與者: {participant.nickname}")
484
  except (KeyError, ValueError) as e:
485
  print(f"處理參與者資料時出錯: {str(e)}")
486
  print(f"問題資料: {participant_data}")
487
  continue
488
 
489
  db.session.commit()
490
- print("資料恢復完成")
491
  return jsonify({'message': '資料已成功恢復'})
492
 
493
  except Exception as e:
 
436
  def restore_data():
437
  try:
438
  # 從 Google Apps Script 獲取數據
439
+ print("正在從 Google Sheets 同步資料...")
440
  response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
441
+ print("Google Sheets 回應狀態碼:", response.status_code)
 
 
442
 
443
  try:
444
  data = response.json()
 
449
 
450
  if not data.get('success'):
451
  error_msg = data.get('error', '從 Google Sheets 恢復資料失敗')
452
+ print("Google Sheets 返回錯誤:", error_msg)
453
  return jsonify({'error': error_msg}), 400
454
+
455
+ # 更新桌次設定
456
+ settings = data.get('settings', {})
457
+ print(f"從 Google Sheets 讀取設定:總桌數={settings.get('total_tables')}, 每桌人數={settings.get('seats_per_table')}")
458
+
459
+ # 更新桌次名稱
460
+ tables_data = data.get('tables', [])
461
+ for table_data in tables_data:
462
+ table = Table.query.get(table_data.get('id'))
463
+ if table and 'name' in table_data:
464
+ table.name = table_data['name']
465
+ db.session.commit()
466
+ print("桌次設定更新完成")
467
 
468
  # 清空現有的參與者資料
469
  Participant.query.delete()
470
 
471
  # 恢復參與者資料
472
  participants_data = data.get('participants', [])
473
+ print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料")
474
 
475
  for participant_data in participants_data:
476
  # 處理 ISO 格式的時間
 
491
  note=participant_data.get('note', '')
492
  )
493
  db.session.add(participant)
494
+ print(f"已更新參與者: {participant.nickname}")
495
  except (KeyError, ValueError) as e:
496
  print(f"處理參與者資料時出錯: {str(e)}")
497
  print(f"問題資料: {participant_data}")
498
  continue
499
 
500
  db.session.commit()
501
+ print("參與者資料更新完成")
502
  return jsonify({'message': '資料已成功恢復'})
503
 
504
  except Exception as e:
sync_settings.gs CHANGED
@@ -2,6 +2,7 @@ function doGet() {
2
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
3
  var participantsSheet = sheet.getSheetByName('Participants');
4
  var settingsSheet = sheet.getSheetByName('Settings');
 
5
 
6
  // 獲取設定
7
  var settings = {
@@ -25,6 +26,24 @@ function doGet() {
25
  }
26
  }
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  // 獲取參與者資料
29
  var participants = [];
30
  if (participantsSheet) {
@@ -55,7 +74,8 @@ function doGet() {
55
  return ContentService.createTextOutput(JSON.stringify({
56
  success: true,
57
  participants: participants,
58
- settings: settings
 
59
  })).setMimeType(ContentService.MimeType.JSON);
60
  }
61
 
@@ -87,28 +107,35 @@ function doPost(e) {
87
 
88
  // 更新桌次名稱
89
  var tablesSheet = sheet.getSheetByName('Tables');
 
 
 
 
 
 
90
  var tableRow = findTableRow(tableId, tablesSheet);
91
- if (tableRow > 0) {
92
- tablesSheet.getRange(tableRow, 2).setValue(name); // 假設名稱在第二列
93
- return ContentService.createTextOutput(JSON.stringify({
94
- success: true,
95
- message: '桌次名稱已更新'
96
- })).setMimeType(ContentService.MimeType.JSON);
97
  } else {
98
- return ContentService.createTextOutput(JSON.stringify({
99
- success: false,
100
- error: '找不到指定的桌次'
101
- })).setMimeType(ContentService.MimeType.JSON);
102
  }
 
 
 
 
 
103
  }
104
 
105
  return ContentService.createTextOutput(JSON.stringify({
106
  success: false,
107
- error: 'Unknown action: ' + action
108
  })).setMimeType(ContentService.MimeType.JSON);
109
 
110
  } catch (error) {
111
- Logger.log("Error in doPost: " + error.toString());
112
  return ContentService.createTextOutput(JSON.stringify({
113
  success: false,
114
  error: error.toString()
@@ -119,119 +146,120 @@ function doPost(e) {
119
  // 尋找桌次在表格中的行數
120
  function findTableRow(tableId, sheet) {
121
  var data = sheet.getDataRange().getValues();
122
- for (var i = 0; i < data.length; i++) {
123
- if (data[i][0] == tableId) { // 假設 ID 在第一列
124
- return i + 1; // 轉換為 1-based 索引
125
  }
126
  }
127
- return -1;
128
  }
129
 
130
  function backupParticipants(sheet, participants) {
131
- if (!participants) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  return ContentService.createTextOutput(JSON.stringify({
133
  success: false,
134
- error: 'No participants data provided'
135
  })).setMimeType(ContentService.MimeType.JSON);
136
  }
137
-
138
- var participantsSheet = sheet.getSheetByName('Participants') || sheet.insertSheet('Participants');
139
- participantsSheet.clear();
140
-
141
- // 設置標題行
142
- participantsSheet.getRange('A1:K1').setValues([[
143
- 'ID', '暱稱', 'Email', 'FB連結', '自我介紹', '桌次', '座位號', '是否為桌長', '報名時間', '付款狀態', '備註'
144
- ]]);
145
-
146
- if (participants.length > 0) {
147
- var values = participants.map(function(p) {
148
- return [
149
- p.id || '',
150
- p.nickname || '',
151
- p.email || '',
152
- p.fb_link || '',
153
- p.introduction || '',
154
- p.table_id || 0,
155
- p.seat_number || 0,
156
- Boolean(p.is_table_leader),
157
- p.created_at || '',
158
- Boolean(p.has_paid),
159
- p.note || ''
160
- ];
161
- });
162
-
163
- participantsSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
164
- }
165
-
166
- return ContentService.createTextOutput(JSON.stringify({
167
- success: true,
168
- message: 'Participants data backed up successfully'
169
- })).setMimeType(ContentService.MimeType.JSON);
170
  }
171
 
172
  function updateSettings(sheet, settings) {
173
- if (!settings || (typeof settings.total_tables === 'undefined' && typeof settings.seats_per_table === 'undefined')) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  return ContentService.createTextOutput(JSON.stringify({
175
  success: false,
176
- error: 'Invalid settings data'
177
  })).setMimeType(ContentService.MimeType.JSON);
178
  }
 
179
 
180
- var settingsSheet = sheet.getSheetByName('Settings') || sheet.insertSheet('Settings');
181
- settingsSheet.clear();
182
-
183
- // 設置標題行
184
- settingsSheet.getRange('A1:B1').setValues([['設定項目', '值']]);
185
-
186
- // 更新設定值
187
- var total_tables = parseInt(settings.total_tables) || 10;
188
- var seats_per_table = parseInt(settings.seats_per_table) || 10;
189
-
190
- settingsSheet.getRange('A2:B3').setValues([
191
- ['總桌數', total_tables],
192
- ['每桌人數', seats_per_table]
193
- ]);
194
-
195
- // 初始化或更新 Tables 工作表
196
- var tablesSheet = sheet.getSheetByName('Tables') || sheet.insertSheet('Tables');
197
-
198
- // 如果是新工作表,設置標題行
199
- if (tablesSheet.getLastRow() === 0) {
200
- tablesSheet.getRange('A1:B1').setValues([['Table ID', 'Table Name']]);
201
- }
202
-
203
- // 獲取現有的桌次資料
204
- var existingData = tablesSheet.getDataRange().getValues();
205
- var existingTables = {};
206
 
207
- // 跳過標題行,建立現有桌次的映射
208
- for (var i = 1; i < existingData.length; i++) {
209
- var tableId = existingData[i][0];
210
- var tableName = existingData[i][1];
211
- if (tableId) {
212
- existingTables[tableId] = tableName || '';
213
  }
214
  }
215
-
216
- // 準備新的桌次資料
217
- var newData = [];
218
- for (var i = 1; i <= total_tables; i++) {
219
- // 保留現有桌次的名稱,如果是新桌次則設為空字串
220
- newData.push([i, existingTables[i] || '']);
221
- }
222
-
223
- // 清除現有資料(保留標題行)
224
- if (tablesSheet.getLastRow() > 1) {
225
- tablesSheet.getRange(2, 1, tablesSheet.getLastRow() - 1, 2).clear();
226
- }
227
-
228
- // 寫入新的桌次資料
229
- if (newData.length > 0) {
230
- tablesSheet.getRange(2, 1, newData.length, 2).setValues(newData);
231
  }
232
 
233
- return ContentService.createTextOutput(JSON.stringify({
234
- success: true,
235
- message: 'Settings updated successfully'
236
- })).setMimeType(ContentService.MimeType.JSON);
237
  }
 
2
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
3
  var participantsSheet = sheet.getSheetByName('Participants');
4
  var settingsSheet = sheet.getSheetByName('Settings');
5
+ var tablesSheet = sheet.getSheetByName('Tables'); // 新增桌次表格
6
 
7
  // 獲取設定
8
  var settings = {
 
26
  }
27
  }
28
 
29
+ // 獲取桌次資料
30
+ var tables = [];
31
+ if (tablesSheet) {
32
+ var tablesData = tablesSheet.getDataRange().getValues();
33
+ var tablesHeaders = tablesData[0];
34
+
35
+ for (var i = 1; i < tablesData.length; i++) {
36
+ var row = tablesData[i];
37
+ if (row[0]) { // 只處理有 ID 的行
38
+ var table = {
39
+ id: parseInt(row[0]),
40
+ name: row[1] || ''
41
+ };
42
+ tables.push(table);
43
+ }
44
+ }
45
+ }
46
+
47
  // 獲取參與者資料
48
  var participants = [];
49
  if (participantsSheet) {
 
74
  return ContentService.createTextOutput(JSON.stringify({
75
  success: true,
76
  participants: participants,
77
+ settings: settings,
78
+ tables: tables
79
  })).setMimeType(ContentService.MimeType.JSON);
80
  }
81
 
 
107
 
108
  // 更新桌次名稱
109
  var tablesSheet = sheet.getSheetByName('Tables');
110
+ if (!tablesSheet) {
111
+ tablesSheet = sheet.insertSheet('Tables');
112
+ tablesSheet.getRange(1, 1, 1, 2).setValues([['ID', '名稱']]);
113
+ }
114
+
115
+ // 尋找或創建桌次行
116
  var tableRow = findTableRow(tableId, tablesSheet);
117
+ if (tableRow === 0) {
118
+ // 如果找不到桌次,在最後一行添加
119
+ tableRow = tablesSheet.getLastRow() + 1;
120
+ tablesSheet.getRange(tableRow, 1, 1, 2).setValues([[tableId, name]]);
 
 
121
  } else {
122
+ // 更新現有桌次名稱
123
+ tablesSheet.getRange(tableRow, 2).setValue(name);
 
 
124
  }
125
+
126
+ return ContentService.createTextOutput(JSON.stringify({
127
+ success: true,
128
+ message: '桌次名稱已更新'
129
+ })).setMimeType(ContentService.MimeType.JSON);
130
  }
131
 
132
  return ContentService.createTextOutput(JSON.stringify({
133
  success: false,
134
+ error: 'Unknown action'
135
  })).setMimeType(ContentService.MimeType.JSON);
136
 
137
  } catch (error) {
138
+ Logger.log("Error: " + error.toString());
139
  return ContentService.createTextOutput(JSON.stringify({
140
  success: false,
141
  error: error.toString()
 
146
  // 尋找桌次在表格中的行數
147
  function findTableRow(tableId, sheet) {
148
  var data = sheet.getDataRange().getValues();
149
+ for (var i = 1; i < data.length; i++) {
150
+ if (data[i][0] == tableId) {
151
+ return i + 1; // 加 1 是因為 getValues() 從 0 開始,但 sheet 從 1 開始
152
  }
153
  }
154
+ return 0; // 沒找到
155
  }
156
 
157
  function backupParticipants(sheet, participants) {
158
+ try {
159
+ var participantsSheet = sheet.getSheetByName('Participants');
160
+ if (!participantsSheet) {
161
+ participantsSheet = sheet.insertSheet('Participants');
162
+ }
163
+
164
+ // 設置表頭
165
+ var headers = [
166
+ 'ID', '暱稱', 'Email', 'FB連結', '自我介紹',
167
+ '桌次', '座位號', '是否桌長', '報名時間', '是否付款', '備註'
168
+ ];
169
+ participantsSheet.getRange(1, 1, 1, headers.length).setValues([headers]);
170
+
171
+ // 清空舊資料(保留表頭)
172
+ var lastRow = participantsSheet.getLastRow();
173
+ if (lastRow > 1) {
174
+ participantsSheet.getRange(2, 1, lastRow - 1, headers.length).clear();
175
+ }
176
+
177
+ // 寫入新資料
178
+ if (participants && participants.length > 0) {
179
+ var values = participants.map(function(p) {
180
+ return [
181
+ p.id,
182
+ p.nickname,
183
+ p.email,
184
+ p.fb_link || '',
185
+ p.introduction || '',
186
+ p.table_id,
187
+ p.seat_number,
188
+ p.is_table_leader ? '是' : '否',
189
+ p.created_at,
190
+ p.has_paid ? '是' : '否',
191
+ p.note || ''
192
+ ];
193
+ });
194
+
195
+ participantsSheet.getRange(2, 1, values.length, headers.length).setValues(values);
196
+ }
197
+
198
+ return ContentService.createTextOutput(JSON.stringify({
199
+ success: true,
200
+ message: '參與者資料已更新'
201
+ })).setMimeType(ContentService.MimeType.JSON);
202
+
203
+ } catch (error) {
204
+ Logger.log("Error in backupParticipants: " + error.toString());
205
  return ContentService.createTextOutput(JSON.stringify({
206
  success: false,
207
+ error: error.toString()
208
  })).setMimeType(ContentService.MimeType.JSON);
209
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  }
211
 
212
  function updateSettings(sheet, settings) {
213
+ try {
214
+ var settingsSheet = sheet.getSheetByName('Settings');
215
+ if (!settingsSheet) {
216
+ settingsSheet = sheet.insertSheet('Settings');
217
+ settingsSheet.getRange(1, 1, 1, 2).setValues([['設定項目', '值']]);
218
+ }
219
+
220
+ // 更新總桌數
221
+ if (settings.totalTables || settings.total_tables) {
222
+ var totalTables = settings.totalTables || settings.total_tables;
223
+ updateSettingValue(settingsSheet, '總桌數', totalTables);
224
+ }
225
+
226
+ // 更新每桌人數
227
+ if (settings.seatsPerTable || settings.seats_per_table) {
228
+ var seatsPerTable = settings.seatsPerTable || settings.seats_per_table;
229
+ updateSettingValue(settingsSheet, '每桌人數', seatsPerTable);
230
+ }
231
+
232
+ return ContentService.createTextOutput(JSON.stringify({
233
+ success: true,
234
+ message: '設定已更新'
235
+ })).setMimeType(ContentService.MimeType.JSON);
236
+
237
+ } catch (error) {
238
+ Logger.log("Error in updateSettings: " + error.toString());
239
  return ContentService.createTextOutput(JSON.stringify({
240
  success: false,
241
+ error: error.toString()
242
  })).setMimeType(ContentService.MimeType.JSON);
243
  }
244
+ }
245
 
246
+ function updateSettingValue(sheet, key, value) {
247
+ var data = sheet.getDataRange().getValues();
248
+ var rowIndex = -1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
+ // 尋找設定項目
251
+ for (var i = 1; i < data.length; i++) {
252
+ if (data[i][0] === key) {
253
+ rowIndex = i + 1;
254
+ break;
 
255
  }
256
  }
257
+
258
+ // 如果找不到,就新增一行
259
+ if (rowIndex === -1) {
260
+ rowIndex = sheet.getLastRow() + 1;
 
 
 
 
 
 
 
 
 
 
 
 
261
  }
262
 
263
+ // 更新值
264
+ sheet.getRange(rowIndex, 1, 1, 2).setValues([[key, value]]);
 
 
265
  }