ichieh commited on
Commit
e876179
·
1 Parent(s): 8261b7f

更改儲存邏輯,以Spreadsheet 為主

Browse files
Files changed (2) hide show
  1. app.py +102 -113
  2. sync_settings.gs +95 -71
app.py CHANGED
@@ -24,20 +24,20 @@ app.config['SETTINGS_SCRIPT_URL'] = SETTINGS_SCRIPT_URL
24
  if os.environ.get('SPACE_ID'): # 在 Hugging Face Spaces 環境中
25
  # 確保資料目錄存在
26
  os.makedirs('/data', exist_ok=True)
27
-
28
- # 如果是第一次運行,將現有資料庫複製到持久化存儲
29
- if not os.path.exists('/data/event.db') and os.path.exists('instance/event.db'):
30
- print("將現有資料庫複製到持久化存儲...")
31
- shutil.copy2('instance/event.db', '/data/event.db')
32
- print("資料庫複製完成")
33
-
34
  db_path = '/data/event.db'
 
 
 
 
 
 
 
35
  else: # 在本地開發環境中
36
  # 確保 instance 目錄存在
37
  os.makedirs(app.instance_path, exist_ok=True)
38
  db_path = os.path.join(app.instance_path, 'event.db')
39
 
40
- print(f"Using database path: {db_path}")
41
 
42
  # 設置資料庫
43
  app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
@@ -138,61 +138,63 @@ with app.app_context():
138
  db.session.execute('SELECT 1')
139
  print("資料庫初始化成功")
140
 
141
- # 只在完全沒有桌子和參與者時才從 Google Sheets 恢復資料
142
- if Table.query.count() == 0 and Participant.query.count() == 0:
143
- print("沒有任何資料,嘗試從 Google Sheets 恢復資料...")
144
- try:
145
- response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
146
- print(f"Google Sheets 回應狀態碼: {response.status_code}")
147
- data = response.json()
148
- print(f"Google Sheets 回應內容: {data}")
 
 
 
149
 
150
- if data.get('success'):
151
- # 首先恢復設定
152
- settings = data.get('settings', {})
153
- total_tables = settings.get('total_tables', 10)
154
- seats_per_table = settings.get('seats_per_table', 10)
155
- print(f"從 Google Sheets 恢復設定:總桌數={total_tables}, 每桌人數={seats_per_table}")
156
-
157
- # 創建桌子
158
- for i in range(1, total_tables + 1):
159
- table = Table(
160
- name=f'第{i}桌',
161
- capacity=seats_per_table
162
- )
163
- db.session.add(table)
164
- db.session.commit()
165
- print("桌次設定恢復完成")
166
-
167
- # 恢復參與者資料
168
- participants_data = data.get('participants', [])
169
- print(f"從 Google Sheets 找到 {len(participants_data)} 個參與者")
170
-
171
- for participant_data in participants_data:
172
- created_at_str = participant_data['created_at'].replace('T', ' ').replace('.000Z', '')
173
- created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
174
-
175
- participant = Participant(
176
- nickname=participant_data['nickname'],
177
- email=participant_data['email'],
178
- fb_link=participant_data.get('fb_link', ''),
179
- introduction=participant_data.get('introduction', ''),
180
- table_id=participant_data['table_id'],
181
- seat_number=participant_data['seat_number'],
182
- is_table_leader=participant_data.get('is_table_leader', False),
183
- created_at=created_at,
184
- has_paid=participant_data.get('has_paid', False),
185
- note=participant_data.get('note', '')
186
- )
187
- db.session.add(participant)
188
- print(f"已添加參與者: {participant.nickname}")
189
 
190
- db.session.commit()
191
- print("參與者資料恢復完成")
192
- except Exception as e:
193
- print(f"從 Google Sheets 恢復資料時出錯: {str(e)}")
194
- else:
195
- print(f"資料庫中已有資料:{Table.query.count()} 張桌子,{Participant.query.count()} 位參與者")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
  except Exception as e:
198
  print(f"初始化資料庫時出錯: {str(e)}")
@@ -245,67 +247,54 @@ def admin_login_api():
245
  return jsonify({'success': True, 'message': 'Login successful'}), 200
246
  return jsonify({'success': False, 'error': 'Invalid password'}), 401
247
 
248
- @app.route('/api/admin/settings', methods=['GET', 'POST'])
249
  @admin_required
250
  def update_settings():
251
- if request.method == 'GET':
252
- # 獲取目前設定
253
- total_tables = Table.query.count()
254
- first_table = Table.query.first()
255
- seats_per_table = first_table.capacity if first_table else 8
256
- return jsonify({
257
- 'total_tables': total_tables,
258
- 'seats_per_table': seats_per_table
259
- })
260
- else:
261
- try:
262
- data = request.get_json()
263
- total_tables = int(data.get('total_tables', 0))
264
- seats_per_table = int(data.get('seats_per_table', 0))
265
 
266
- if total_tables <= 0 or seats_per_table <= 0:
267
- return jsonify({'error': '桌數和座位數必須大於 0'}), 400
 
 
 
268
 
269
- # 清除現有的桌子
270
- Table.query.delete()
271
 
272
- # 創建新的桌子
273
- for i in range(total_tables):
274
- table = Table(name=f'第 {i+1} 桌', capacity=seats_per_table)
275
- db.session.add(table)
276
 
277
- db.session.commit()
278
-
279
- # 同步設定到 Google Sheets
280
- settings_data = {
281
- 'action': 'updateSettings',
282
- 'settings': {
283
- 'total_tables': total_tables,
284
- 'seats_per_table': seats_per_table
285
- }
286
- }
 
287
 
288
- print(f"Sending settings to Google Sheets: {settings_data}")
289
-
290
- try:
291
- response = requests.post(
292
- app.config['SETTINGS_SCRIPT_URL'],
293
- json=settings_data,
294
- timeout=10
295
- )
296
- print(f"Response from Google Sheets: {response.text}")
297
-
298
- if not response.ok:
299
- print(f"Failed to sync settings to Google Sheets. Status: {response.status_code}")
300
- app.logger.error(f"Failed to sync settings to Google Sheets: {response.text}")
301
- except Exception as e:
302
- print(f"Error syncing settings to Google Sheets: {str(e)}")
303
- app.logger.error(f"Error syncing settings to Google Sheets: {str(e)}")
304
 
 
305
  return jsonify({'message': '設定已更新'})
306
- except Exception as e:
307
- db.session.rollback()
308
- return jsonify({'error': str(e)}), 500
 
 
 
 
309
 
310
  @app.route('/api/admin/settings/backup', methods=['POST'])
311
  @admin_required
 
24
  if os.environ.get('SPACE_ID'): # 在 Hugging Face Spaces 環境中
25
  # 確保資料目錄存在
26
  os.makedirs('/data', exist_ok=True)
 
 
 
 
 
 
 
27
  db_path = '/data/event.db'
28
+
29
+ # 檢查資料庫文件是否存在
30
+ if not os.path.exists(db_path):
31
+ print(f"資料庫文件不存在:{db_path}")
32
+ # 如果資料庫不存在,將創建一個新的
33
+ open(db_path, 'a').close()
34
+ print("創建了新的資料庫文件")
35
  else: # 在本地開發環境中
36
  # 確保 instance 目錄存在
37
  os.makedirs(app.instance_path, exist_ok=True)
38
  db_path = os.path.join(app.instance_path, 'event.db')
39
 
40
+ print(f"使用資料庫路徑: {db_path}")
41
 
42
  # 設置資料庫
43
  app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
 
138
  db.session.execute('SELECT 1')
139
  print("資料庫初始化成功")
140
 
141
+ # 每次啟動時都從 Google Sheets 同步資料
142
+ print("從 Google Sheets 同步資料...")
143
+ try:
144
+ response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
145
+ print(f"Google Sheets 回應狀態碼: {response.status_code}")
146
+ data = response.json()
147
+
148
+ if data.get('success'):
149
+ # 清空現有資料
150
+ Participant.query.delete()
151
+ Table.query.delete()
152
 
153
+ # 恢復設定和創建桌子
154
+ settings = data.get('settings', {})
155
+ total_tables = settings.get('total_tables', 10)
156
+ seats_per_table = settings.get('seats_per_table', 10)
157
+ print(f"從 Google Sheets 讀取設定:總桌數={total_tables}, 每桌人數={seats_per_table}")
158
+
159
+ # 創建桌子
160
+ for i in range(1, total_tables + 1):
161
+ table = Table(
162
+ name=f'第{i}桌',
163
+ capacity=seats_per_table
164
+ )
165
+ db.session.add(table)
166
+ db.session.commit()
167
+ print("桌次設定更新完成")
168
+
169
+ # 恢復參與者資料
170
+ participants_data = data.get('participants', [])
171
+ print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料")
172
+
173
+ for participant_data in participants_data:
174
+ created_at_str = participant_data['created_at'].replace('T', ' ').replace('.000Z', '')
175
+ created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
+ participant = Participant(
178
+ nickname=participant_data['nickname'],
179
+ email=participant_data['email'],
180
+ fb_link=participant_data.get('fb_link', ''),
181
+ introduction=participant_data.get('introduction', ''),
182
+ table_id=participant_data['table_id'],
183
+ seat_number=participant_data['seat_number'],
184
+ is_table_leader=participant_data.get('is_table_leader', False),
185
+ created_at=created_at,
186
+ has_paid=participant_data.get('has_paid', False),
187
+ note=participant_data.get('note', '')
188
+ )
189
+ db.session.add(participant)
190
+ print(f"已更新參與者: {participant.nickname}")
191
+
192
+ db.session.commit()
193
+ print("參與者資料更新完成")
194
+ else:
195
+ print(f"從 Google Sheets 同步資料失敗: {data.get('error', '未知錯誤')}")
196
+ except Exception as e:
197
+ print(f"同步資料時出錯: {str(e)}")
198
 
199
  except Exception as e:
200
  print(f"初始化資料庫時出錯: {str(e)}")
 
247
  return jsonify({'success': True, 'message': 'Login successful'}), 200
248
  return jsonify({'success': False, 'error': 'Invalid password'}), 401
249
 
250
+ @app.route('/api/admin/settings/update', methods=['POST'])
251
  @admin_required
252
  def update_settings():
253
+ try:
254
+ data = request.get_json()
255
+ action = data.get('action')
256
+
257
+ if action == 'update_tables':
258
+ total_tables = int(data.get('total_tables', 10))
259
+ seats_per_table = int(data.get('seats_per_table', 10))
 
 
 
 
 
 
 
260
 
261
+ # 同步到 Google Sheets
262
+ sync_result = sync_settings_to_sheets('update_tables', {
263
+ 'total_tables': total_tables,
264
+ 'seats_per_table': seats_per_table
265
+ })
266
 
267
+ if not sync_result.get('success', False):
268
+ return jsonify({'error': '同步到 Google Sheets 失敗'}), 500
269
 
270
+ # 更新本地資料庫
271
+ current_tables = Table.query.count()
 
 
272
 
273
+ if total_tables > current_tables:
274
+ # 添加新桌子
275
+ for i in range(current_tables + 1, total_tables + 1):
276
+ table = Table(name=f'第{i}桌', capacity=seats_per_table)
277
+ db.session.add(table)
278
+ elif total_tables < current_tables:
279
+ # 刪除多餘的桌子(確保沒有參與者)
280
+ for i in range(total_tables + 1, current_tables + 1):
281
+ table = Table.query.filter_by(name=f'第{i}桌').first()
282
+ if table and len(table.participants) == 0:
283
+ db.session.delete(table)
284
 
285
+ # 更新所有桌子的容量
286
+ for table in Table.query.all():
287
+ table.capacity = seats_per_table
 
 
 
 
 
 
 
 
 
 
 
 
 
288
 
289
+ db.session.commit()
290
  return jsonify({'message': '設定已更新'})
291
+
292
+ else:
293
+ return jsonify({'error': '無效的操作'}), 400
294
+
295
+ except Exception as e:
296
+ db.session.rollback()
297
+ return jsonify({'error': str(e)}), 500
298
 
299
  @app.route('/api/admin/settings/backup', methods=['POST'])
300
  @admin_required
sync_settings.gs CHANGED
@@ -35,34 +35,31 @@ function doGet() {
35
  ]);
36
  }
37
 
38
- if (!participantsSheet) {
39
- return ContentService.createTextOutput(JSON.stringify({
40
- success: false,
41
- error: 'Participants sheet not found',
42
- settings: settings
43
- })).setMimeType(ContentService.MimeType.JSON);
44
- }
45
-
46
- var data = participantsSheet.getDataRange().getValues();
47
- var headers = data[0];
48
  var participants = [];
49
-
50
- for (var i = 1; i < data.length; i++) {
51
- var row = data[i];
52
- var participant = {
53
- id: row[0],
54
- nickname: row[1],
55
- email: row[2],
56
- fb_link: row[3],
57
- introduction: row[4],
58
- table_id: row[5],
59
- seat_number: row[6],
60
- is_table_leader: row[7],
61
- created_at: row[8],
62
- has_paid: row[9],
63
- note: row[10]
64
- };
65
- participants.push(participant);
 
 
 
 
 
 
66
  }
67
 
68
  return ContentService.createTextOutput(JSON.stringify({
@@ -80,59 +77,86 @@ function doPost(e) {
80
  Logger.log("Received action: " + action);
81
  Logger.log("Received data: " + JSON.stringify(data));
82
 
83
- if (action === 'backupParticipants') {
84
- // 備份參與者資料
85
- var participantsSheet = sheet.getSheetByName('Participants') || sheet.insertSheet('Participants');
86
- participantsSheet.clear();
87
- participantsSheet.getRange('A1:K1').setValues([[
88
- 'ID', '暱稱', 'Email', 'FB連結', '自我介紹', '桌次', '座位號', '是否為桌長', '報名時間', '付款狀態', '備註'
89
- ]]);
90
-
91
- var participants = data.participants;
92
- if (participants && participants.length > 0) {
93
- var values = participants.map(function(p) {
94
- return [
95
- p.id,
96
- p.nickname,
97
- p.email,
98
- p.fb_link || '',
99
- p.introduction || '',
100
- p.table_id,
101
- p.seat_number,
102
- p.is_table_leader,
103
- p.created_at,
104
- p.has_paid,
105
- p.note || ''
106
- ];
107
- });
108
-
109
- participantsSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
110
  }
111
 
112
  return ContentService.createTextOutput(JSON.stringify({
113
- success: true,
114
- message: 'Participants data backed up successfully'
115
  })).setMimeType(ContentService.MimeType.JSON);
116
- } else if (action === 'updateSettings') {
117
- // 更新設定
118
- var settingsSheet = sheet.getSheetByName('Settings') || sheet.insertSheet('Settings');
119
- settingsSheet.clear();
120
- settingsSheet.getRange('A1:B1').setValues([['設定項目', '值']]);
121
-
122
- var settings = data.settings;
123
- settingsSheet.getRange('A2:B3').setValues([
124
- ['總桌數', settings.total_tables],
125
- ['每桌人數', settings.seats_per_table]
126
- ]);
127
 
 
 
128
  return ContentService.createTextOutput(JSON.stringify({
129
- success: true,
130
- message: 'Settings updated successfully'
131
  })).setMimeType(ContentService.MimeType.JSON);
132
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  return ContentService.createTextOutput(JSON.stringify({
135
- success: false,
136
- error: 'Unknown action'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  })).setMimeType(ContentService.MimeType.JSON);
138
  }
 
35
  ]);
36
  }
37
 
38
+ // 獲取參與者資料
 
 
 
 
 
 
 
 
 
39
  var participants = [];
40
+ if (participantsSheet) {
41
+ var data = participantsSheet.getDataRange().getValues();
42
+ var headers = data[0];
43
+
44
+ for (var i = 1; i < data.length; i++) {
45
+ var row = data[i];
46
+ if (row[0]) { // 只處理有 ID 的行
47
+ var participant = {
48
+ id: row[0],
49
+ nickname: row[1],
50
+ email: row[2],
51
+ fb_link: row[3] || '',
52
+ introduction: row[4] || '',
53
+ table_id: parseInt(row[5]) || 0,
54
+ seat_number: parseInt(row[6]) || 0,
55
+ is_table_leader: Boolean(row[7]),
56
+ created_at: row[8],
57
+ has_paid: Boolean(row[9]),
58
+ note: row[10] || ''
59
+ };
60
+ participants.push(participant);
61
+ }
62
+ }
63
  }
64
 
65
  return ContentService.createTextOutput(JSON.stringify({
 
77
  Logger.log("Received action: " + action);
78
  Logger.log("Received data: " + JSON.stringify(data));
79
 
80
+ try {
81
+ if (action === 'backupParticipants') {
82
+ return backupParticipants(sheet, data.participants);
83
+ } else if (action === 'update_tables') {
84
+ return updateSettings(sheet, data);
85
+ } else if (action === 'updateSettings') {
86
+ return updateSettings(sheet, data.settings);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  }
88
 
89
  return ContentService.createTextOutput(JSON.stringify({
90
+ success: false,
91
+ error: 'Unknown action: ' + action
92
  })).setMimeType(ContentService.MimeType.JSON);
 
 
 
 
 
 
 
 
 
 
 
93
 
94
+ } catch (error) {
95
+ Logger.log("Error in doPost: " + error.toString());
96
  return ContentService.createTextOutput(JSON.stringify({
97
+ success: false,
98
+ error: error.toString()
99
  })).setMimeType(ContentService.MimeType.JSON);
100
  }
101
+ }
102
+
103
+ function backupParticipants(sheet, participants) {
104
+ var participantsSheet = sheet.getSheetByName('Participants') || sheet.insertSheet('Participants');
105
+ participantsSheet.clear();
106
+
107
+ // 設置標題行
108
+ participantsSheet.getRange('A1:K1').setValues([[
109
+ 'ID', '暱稱', 'Email', 'FB連結', '自我介紹', '桌次', '座位號', '是否為桌長', '報名時間', '付款狀態', '備註'
110
+ ]]);
111
+
112
+ if (participants && participants.length > 0) {
113
+ var values = participants.map(function(p) {
114
+ return [
115
+ p.id,
116
+ p.nickname,
117
+ p.email,
118
+ p.fb_link || '',
119
+ p.introduction || '',
120
+ p.table_id,
121
+ p.seat_number,
122
+ p.is_table_leader,
123
+ p.created_at,
124
+ p.has_paid,
125
+ p.note || ''
126
+ ];
127
+ });
128
+
129
+ participantsSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
130
+ }
131
 
132
  return ContentService.createTextOutput(JSON.stringify({
133
+ success: true,
134
+ message: 'Participants data backed up successfully'
135
+ })).setMimeType(ContentService.MimeType.JSON);
136
+ }
137
+
138
+ function updateSettings(sheet, settings) {
139
+ var settingsSheet = sheet.getSheetByName('Settings') || sheet.insertSheet('Settings');
140
+ settingsSheet.clear();
141
+
142
+ // 設置標題行
143
+ settingsSheet.getRange('A1:B1').setValues([['設定項目', '值']]);
144
+
145
+ // 更新設定值
146
+ var total_tables = settings.total_tables || 10;
147
+ var seats_per_table = settings.seats_per_table || 10;
148
+
149
+ settingsSheet.getRange('A2:B3').setValues([
150
+ ['總桌數', total_tables],
151
+ ['每桌人數', seats_per_table]
152
+ ]);
153
+
154
+ return ContentService.createTextOutput(JSON.stringify({
155
+ success: true,
156
+ message: 'Settings updated successfully',
157
+ settings: {
158
+ total_tables: total_tables,
159
+ seats_per_table: seats_per_table
160
+ }
161
  })).setMimeType(ContentService.MimeType.JSON);
162
  }