ichieh commited on
Commit
3adb25c
·
1 Parent(s): 813fe6a

Fix time format parsing and update Google Apps Script

Browse files
Files changed (2) hide show
  1. app.py +53 -33
  2. sync_settings.gs +87 -10
app.py CHANGED
@@ -300,46 +300,66 @@ def backup_settings():
300
  @admin_required
301
  def restore_settings():
302
  try:
303
- # 從 Sheets 恢復設定
304
- settings = sync_settings_to_sheets('loadSettings', {})
305
- if settings:
306
- # 清除現有的桌子
307
- Table.query.delete()
308
-
309
- # 重新創建桌子
310
- for i in range(int(settings['totalTables'])):
311
- table = Table(
312
- name=f'第{i+1}桌',
313
- capacity=int(settings['seatsPerTable'])
314
- )
315
- db.session.add(table)
316
-
317
- db.session.commit()
318
 
319
- # 從 Sheets 恢復參與者資料
320
- result = sync_settings_to_sheets('restoreParticipants', {})
321
- if result and 'participants' in result:
322
- # 清除現有的參與者
323
- Participant.query.delete()
324
 
325
- # 恢復參與者資料
326
- for p_data in result['participants']:
327
- participant = Participant(
328
- nickname=p_data['nickname'],
329
- email=p_data['email'],
330
- fb_link=p_data['fb_link'],
331
- introduction=p_data['introduction'],
332
- table_id=p_data['table_id'],
333
- seat_number=p_data['seat_number'],
334
- created_at=datetime.strptime(p_data['created_at'], '%Y-%m-%d %H:%M:%S')
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  )
336
- db.session.add(participant)
 
 
 
 
 
 
 
 
 
337
 
338
- db.session.commit()
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
- return jsonify({'message': '恢復成功'})
341
  except Exception as e:
342
  db.session.rollback()
 
343
  return jsonify({'error': str(e)}), 500
344
 
345
  @app.route('/api/admin/participants', methods=['GET'])
 
300
  @admin_required
301
  def restore_settings():
302
  try:
303
+ # 從 Google Apps Script 獲取數據
304
+ response = requests.get(SETTINGS_SCRIPT_URL)
305
+ data = response.json()
 
 
 
 
 
 
 
 
 
 
 
 
306
 
307
+ if not data.get('success'):
308
+ return jsonify({'error': data.get('error', '從 Google Sheets 恢復資料失敗')}), 400
 
 
 
309
 
310
+ # 清空現有資料
311
+ Participant.query.delete()
312
+ Table.query.delete()
313
+
314
+ # 恢復桌次設定
315
+ tables = {} # 用於儲存 table_id 映射
316
+ for table_data in data['tables']:
317
+ table = Table(
318
+ name=table_data['name'],
319
+ capacity=table_data['capacity']
320
+ )
321
+ db.session.add(table)
322
+ db.session.flush() # 獲取新的 table.id
323
+ tables[table_data['id']] = table.id
324
+
325
+ # 恢復參與者資料
326
+ for participant_data in data['participants']:
327
+ # 解析時間
328
+ try:
329
+ # 處理 ISO 格式的時間字串
330
+ created_at = datetime.strptime(
331
+ participant_data['created_at'].split('.')[0],
332
+ '%Y-%m-%dT%H:%M:%S'
333
  )
334
+ except ValueError:
335
+ try:
336
+ # 如果上面失敗,嘗試處理原來的格式
337
+ created_at = datetime.strptime(
338
+ participant_data['created_at'],
339
+ '%Y-%m-%d %H:%M:%S'
340
+ )
341
+ except ValueError:
342
+ # 如果都失敗,使用當前時間
343
+ created_at = datetime.utcnow()
344
 
345
+ participant = Participant(
346
+ nickname=participant_data['nickname'],
347
+ email=participant_data['email'],
348
+ fb_link=participant_data.get('fb_link'),
349
+ introduction=participant_data.get('introduction'),
350
+ table_id=tables.get(participant_data['table_id']),
351
+ seat_number=participant_data.get('seat_number'),
352
+ is_table_leader=participant_data.get('is_table_leader', False),
353
+ created_at=created_at
354
+ )
355
+ db.session.add(participant)
356
+
357
+ db.session.commit()
358
+ return jsonify({'message': '資料已成功恢復'})
359
 
 
360
  except Exception as e:
361
  db.session.rollback()
362
+ print('Error restoring data:', str(e)) # 添加錯誤日誌
363
  return jsonify({'error': str(e)}), 500
364
 
365
  @app.route('/api/admin/participants', methods=['GET'])
sync_settings.gs CHANGED
@@ -1,22 +1,55 @@
1
  function doPost(e) {
2
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
3
- var settingsSheet = sheet.getSheetByName('Settings') || sheet.insertSheet('Settings');
4
- var participantsSheet = sheet.getSheetByName('Participants') || sheet.insertSheet('Participants');
5
-
6
  var data = JSON.parse(e.postData.contents);
7
  var action = data.action;
8
 
9
  if (action === 'saveSettings') {
10
- // 保存桌次設定
11
  settingsSheet.clear();
 
 
12
  settingsSheet.getRange('A1:B1').setValues([['總桌數', '每桌人數']]);
13
  settingsSheet.getRange('A2:B2').setValues([[data.totalTables, data.seatsPerTable]]);
14
- return ContentService.createTextOutput(JSON.stringify({success: true}))
15
- .setMimeType(ContentService.MimeType.JSON);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  }
17
 
18
- if (action === 'loadSettings') {
19
  // 讀取桌次設定
 
20
  var settings = settingsSheet.getRange('A2:B2').getValues()[0];
21
  return ContentService.createTextOutput(JSON.stringify({
22
  totalTables: settings[0],
@@ -24,8 +57,9 @@ function doPost(e) {
24
  })).setMimeType(ContentService.MimeType.JSON);
25
  }
26
 
27
- if (action === 'backupParticipants') {
28
  // 備份參與者資料
 
29
  participantsSheet.clear();
30
  participantsSheet.getRange('A1:H1').setValues([['ID', '暱稱', 'Email', 'FB連結', '自我介紹', '桌次', '座位號碼', '報名時間']]);
31
 
@@ -50,8 +84,9 @@ function doPost(e) {
50
  .setMimeType(ContentService.MimeType.JSON);
51
  }
52
 
53
- if (action === 'restoreParticipants') {
54
  // 讀取備份的參與者資料
 
55
  var range = participantsSheet.getDataRange();
56
  var values = range.getValues();
57
  var participants = [];
@@ -80,5 +115,47 @@ function doPost(e) {
80
  }
81
 
82
  function doGet(e) {
83
- return doPost(e);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  }
 
1
  function doPost(e) {
2
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
 
 
 
3
  var data = JSON.parse(e.postData.contents);
4
  var action = data.action;
5
 
6
  if (action === 'saveSettings') {
7
+ var settingsSheet = sheet.getSheetByName('Settings') || sheet.insertSheet('Settings');
8
  settingsSheet.clear();
9
+
10
+ // 儲存桌次設定
11
  settingsSheet.getRange('A1:B1').setValues([['總桌數', '每桌人數']]);
12
  settingsSheet.getRange('A2:B2').setValues([[data.totalTables, data.seatsPerTable]]);
13
+
14
+ return ContentService.createTextOutput(JSON.stringify({
15
+ success: true,
16
+ message: '設定已儲存'
17
+ })).setMimeType(ContentService.MimeType.JSON);
18
+ }
19
+
20
+ else if (action === 'saveParticipant') {
21
+ var participantsSheet = sheet.getSheetByName('Participants') || sheet.insertSheet('Participants');
22
+
23
+ // 如果是第一次儲存,建立標題列
24
+ if (participantsSheet.getLastRow() === 0) {
25
+ participantsSheet.getRange('A1:I1').setValues([[
26
+ '暱稱', 'Email', 'FB連結', '自我介紹', '桌次', '座位號', '是否為桌長', '報名時間', 'ID'
27
+ ]]);
28
+ }
29
+
30
+ // 儲存參與者資料
31
+ var participant = data.participant;
32
+ participantsSheet.appendRow([
33
+ participant.nickname,
34
+ participant.email,
35
+ participant.fb_link || '',
36
+ participant.introduction || '',
37
+ participant.table_id,
38
+ participant.seat_number,
39
+ participant.is_table_leader || false,
40
+ participant.created_at,
41
+ participant.id
42
+ ]);
43
+
44
+ return ContentService.createTextOutput(JSON.stringify({
45
+ success: true,
46
+ message: '參與者資料已儲存'
47
+ })).setMimeType(ContentService.MimeType.JSON);
48
  }
49
 
50
+ else if (action === 'loadSettings') {
51
  // 讀取桌次設定
52
+ var settingsSheet = sheet.getSheetByName('Settings');
53
  var settings = settingsSheet.getRange('A2:B2').getValues()[0];
54
  return ContentService.createTextOutput(JSON.stringify({
55
  totalTables: settings[0],
 
57
  })).setMimeType(ContentService.MimeType.JSON);
58
  }
59
 
60
+ else if (action === 'backupParticipants') {
61
  // 備份參與者資料
62
+ var participantsSheet = sheet.getSheetByName('Participants') || sheet.insertSheet('Participants');
63
  participantsSheet.clear();
64
  participantsSheet.getRange('A1:H1').setValues([['ID', '暱稱', 'Email', 'FB連結', '自我介紹', '桌次', '座位號碼', '報名時間']]);
65
 
 
84
  .setMimeType(ContentService.MimeType.JSON);
85
  }
86
 
87
+ else if (action === 'restoreParticipants') {
88
  // 讀取備份的參與者資料
89
+ var participantsSheet = sheet.getSheetByName('Participants');
90
  var range = participantsSheet.getDataRange();
91
  var values = range.getValues();
92
  var participants = [];
 
115
  }
116
 
117
  function doGet(e) {
118
+ var sheet = SpreadsheetApp.getActiveSpreadsheet();
119
+
120
+ // 讀取桌次設定
121
+ var settingsSheet = sheet.getSheetByName('Settings');
122
+ var tables = [];
123
+ if (settingsSheet) {
124
+ var settingsData = settingsSheet.getDataRange().getValues();
125
+ // 跳過標題列
126
+ for (var i = 1; i < settingsData.length; i++) {
127
+ tables.push({
128
+ id: i,
129
+ name: '第' + i + '桌',
130
+ capacity: settingsData[i][1] // 每桌人數
131
+ });
132
+ }
133
+ }
134
+
135
+ // 讀取參與者資料
136
+ var participantsSheet = sheet.getSheetByName('Participants');
137
+ var participants = [];
138
+ if (participantsSheet) {
139
+ var participantsData = participantsSheet.getDataRange().getValues();
140
+ // 跳過標題列
141
+ for (var i = 1; i < participantsData.length; i++) {
142
+ participants.push({
143
+ nickname: participantsData[i][0],
144
+ email: participantsData[i][1],
145
+ fb_link: participantsData[i][2],
146
+ introduction: participantsData[i][3],
147
+ table_id: participantsData[i][4],
148
+ seat_number: participantsData[i][5],
149
+ is_table_leader: participantsData[i][6],
150
+ created_at: participantsData[i][7],
151
+ id: participantsData[i][8]
152
+ });
153
+ }
154
+ }
155
+
156
+ return ContentService.createTextOutput(JSON.stringify({
157
+ success: true,
158
+ tables: tables,
159
+ participants: participants
160
+ })).setMimeType(ContentService.MimeType.JSON);
161
  }