ichieh commited on
Commit
3deafeb
·
1 Parent(s): 7c0402b

修正報名者狀態同步

Browse files
Files changed (3) hide show
  1. .history/app_20250118100840.py +953 -0
  2. app.py +31 -20
  3. sync_settings.gs +7 -7
.history/app_20250118100840.py ADDED
@@ -0,0 +1,953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify, session, redirect, url_for, current_app
2
+ from flask_sqlalchemy import SQLAlchemy
3
+ from datetime import datetime, timedelta
4
+ import os
5
+ import time
6
+ from functools import wraps
7
+ import requests
8
+ import shutil
9
+
10
+ # 添加新的環境變數
11
+ SETTINGS_SCRIPT_URL = os.environ.get('SETTINGS_SCRIPT_URL', '')
12
+ ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin')
13
+
14
+ app = Flask(__name__, instance_relative_config=True)
15
+
16
+ # 設置 session secret key
17
+ app.secret_key = os.urandom(24)
18
+
19
+ # 設置管理者密碼和 Google Apps Script URL
20
+ app.config['ADMIN_PASSWORD'] = ADMIN_PASSWORD
21
+ app.config['SETTINGS_SCRIPT_URL'] = SETTINGS_SCRIPT_URL
22
+
23
+ # 設置資料庫路徑 - 使用持久化存儲
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}'
44
+ app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
45
+
46
+ db = SQLAlchemy(app)
47
+
48
+ class Table(db.Model):
49
+ id = db.Column(db.Integer, primary_key=True)
50
+ name = db.Column(db.String(100)) # 新增桌次名稱欄位
51
+ capacity = db.Column(db.Integer, nullable=False)
52
+ participants = db.relationship('Participant', backref='table', lazy=True)
53
+
54
+ def to_dict(self):
55
+ return {
56
+ 'id': self.id,
57
+ 'name': self.name or '', # 確保 name 不會是 None
58
+ 'capacity': self.capacity,
59
+ 'participants': [{
60
+ 'id': p.id,
61
+ 'nickname': p.nickname,
62
+ 'fb_link': p.fb_link,
63
+ 'introduction': p.introduction,
64
+ 'is_table_leader': p.is_table_leader,
65
+ 'created_at': p.created_at,
66
+ 'has_paid': p.has_paid,
67
+ 'note': p.note
68
+ } for p in sorted(self.participants, key=lambda x: (not x.is_table_leader, x.created_at))]
69
+ }
70
+
71
+ class Participant(db.Model):
72
+ id = db.Column(db.Integer, primary_key=True)
73
+ nickname = db.Column(db.String(100), nullable=False)
74
+ email = db.Column(db.String(120), nullable=False)
75
+ fb_link = db.Column(db.String(200))
76
+ introduction = db.Column(db.Text)
77
+ table_id = db.Column(db.Integer, db.ForeignKey('table.id'))
78
+ seat_number = db.Column(db.Integer)
79
+ is_table_leader = db.Column(db.Boolean, default=False)
80
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
81
+ has_paid = db.Column(db.Boolean, default=False)
82
+ note = db.Column(db.Text)
83
+
84
+ def to_dict(self):
85
+ return {
86
+ 'id': self.id,
87
+ 'nickname': self.nickname,
88
+ 'email': self.email,
89
+ 'fb_link': self.fb_link,
90
+ 'introduction': self.introduction,
91
+ 'table_id': self.table_id,
92
+ 'seat_number': self.seat_number,
93
+ 'is_table_leader': self.is_table_leader,
94
+ 'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
95
+ 'has_paid': self.has_paid,
96
+ 'note': self.note
97
+ }
98
+
99
+ # 初始化資料庫和創建預設桌子
100
+ def init_db():
101
+ with app.app_context():
102
+ try:
103
+ # 只創建不存在的表格
104
+ db.create_all()
105
+
106
+ # 從 Google Sheets 獲取設定
107
+ print("正在從 Google Sheets 獲取設定...")
108
+ try:
109
+ if not app.config.get('SETTINGS_SCRIPT_URL'):
110
+ print("未設定 SETTINGS_SCRIPT_URL,使用預設值")
111
+ raise Exception("未設定 SETTINGS_SCRIPT_URL")
112
+
113
+ response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
114
+ if response.status_code != 200:
115
+ print(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}")
116
+ raise Exception(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}")
117
+
118
+ try:
119
+ data = response.json()
120
+ except ValueError as e:
121
+ print("JSON 解析錯誤:", str(e))
122
+ print("原始回應內容:", response.text)
123
+ raise
124
+
125
+ if not data.get('success'):
126
+ error_msg = data.get('error', '從 Google Sheets 獲取資料失敗')
127
+ print("Google Sheets 返回錯誤:", error_msg)
128
+ raise Exception(error_msg)
129
+
130
+ # 獲取設定
131
+ settings = data.get('settings', {})
132
+ total_tables = settings.get('total_tables', 10)
133
+ seats_per_table = settings.get('seats_per_table', 10)
134
+
135
+ print(f"從 Google Sheets 獲取到的設定:")
136
+ print(f"- 總桌數: {total_tables}")
137
+ print(f"- 每桌人數: {seats_per_table}")
138
+
139
+ # 清空現有的桌次和參與者資料
140
+ print("清空現有資料...")
141
+ Participant.query.delete()
142
+ Table.query.delete()
143
+
144
+ # 創建桌次
145
+ tables_data = data.get('tables', [])
146
+ print(f"從 Google Sheets 讀取 {len(tables_data)} 張桌子")
147
+
148
+ for i in range(1, total_tables + 1):
149
+ # 從 tables_data 中找到對應的桌次資料
150
+ table_data = next((t for t in tables_data if t['id'] == i), None)
151
+ table_name = table_data['name'].strip() if table_data and table_data.get('name') else f'第{i}桌'
152
+
153
+ table = Table(
154
+ id=i,
155
+ name=table_name,
156
+ capacity=seats_per_table
157
+ )
158
+ db.session.add(table)
159
+ print(f"創建第 {i} 桌,名稱為: {table_name}")
160
+
161
+ # 創建參與者
162
+ participants_data = data.get('participants', [])
163
+ print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者")
164
+
165
+ for p_data in participants_data:
166
+ try:
167
+ # 處理 ISO 格式的時間
168
+ created_at_str = p_data['created_at'].replace('T', ' ').replace('.000Z', '')
169
+ created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
170
+
171
+ participant = Participant(
172
+ id=int(p_data['id']),
173
+ nickname=p_data['nickname'],
174
+ email=p_data['email'],
175
+ fb_link=p_data.get('fb_link', ''),
176
+ introduction=p_data.get('introduction', ''),
177
+ table_id=int(p_data['table_id']),
178
+ seat_number=int(p_data['seat_number']),
179
+ is_table_leader=bool(p_data.get('is_table_leader', False)),
180
+ created_at=created_at,
181
+ has_paid=bool(p_data.get('has_paid', False)),
182
+ note=p_data.get('note', '')
183
+ )
184
+ db.session.add(participant)
185
+ print(f"創建參與者: {participant.nickname}")
186
+ except Exception as e:
187
+ print(f"處理參與者資料時出錯: {str(e)}")
188
+ print(f"問題資料: {p_data}")
189
+ continue
190
+
191
+ db.session.commit()
192
+ print("資料庫初始化完成")
193
+
194
+ except Exception as e:
195
+ print(f"從 Google Sheets 獲取設定時出錯: {str(e)}")
196
+ print("使用預設值")
197
+
198
+ # 如果沒有任何桌次,創建預設桌次
199
+ if Table.query.count() == 0:
200
+ for i in range(1, 11): # 預設 10 張桌子
201
+ table = Table(id=i, name=f'第{i}桌', capacity=10) # 預設每桌 10 人
202
+ db.session.add(table)
203
+ db.session.commit()
204
+ print("已創建預設桌次")
205
+
206
+ except Exception as e:
207
+ print(f"初始化資料庫時出錯: {str(e)}")
208
+ db.session.rollback()
209
+ raise
210
+
211
+ # 在應用啟動時初始化資料庫
212
+ with app.app_context():
213
+ try:
214
+ # 創建資料庫表格(如果不存在)
215
+ db.create_all()
216
+ print("資料庫表格創建成功")
217
+
218
+ # 檢查資料庫連接
219
+ db.session.execute('SELECT 1')
220
+ print("資料庫初始化成功")
221
+
222
+ # 從 Google Sheets 同步資料
223
+ print("從 Google Sheets 同步資料...")
224
+ try:
225
+ response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
226
+ print(f"Google Sheets 回應狀態碼: {response.status_code}")
227
+ print(f"Google Sheets 回應內容: {response.text}")
228
+
229
+ data = response.json()
230
+ if not data.get('success'):
231
+ raise Exception(f"同步失敗: {data.get('error', '未知錯誤')}")
232
+
233
+ # 清空現有資料
234
+ Participant.query.delete()
235
+ Table.query.delete()
236
+ db.session.commit()
237
+
238
+ # 從 Google Sheets 讀取設定
239
+ settings = data.get('settings', {})
240
+ if not settings:
241
+ raise Exception("無法從 Google Sheets 讀取設定")
242
+
243
+ total_tables = int(settings.get('total_tables', 10))
244
+ seats_per_table = int(settings.get('seats_per_table', 10))
245
+ print(f"從 Google Sheets 讀取設定:總桌數={total_tables}, 每桌人數={seats_per_table}")
246
+
247
+ # 創建桌子
248
+ for i in range(1, total_tables + 1):
249
+ table = Table(
250
+ name=f'第{i}桌',
251
+ capacity=seats_per_table
252
+ )
253
+ db.session.add(table)
254
+ db.session.commit()
255
+ print("桌次設定更新完成")
256
+
257
+ # 恢復參與者資料
258
+ participants_data = data.get('participants', [])
259
+ print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料")
260
+
261
+ for participant_data in participants_data:
262
+ created_at_str = participant_data['created_at'].replace('T', ' ').replace('.000Z', '')
263
+ created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
264
+
265
+ participant = Participant(
266
+ nickname=participant_data['nickname'],
267
+ email=participant_data['email'],
268
+ fb_link=participant_data.get('fb_link', ''),
269
+ introduction=participant_data.get('introduction', ''),
270
+ table_id=participant_data['table_id'],
271
+ seat_number=participant_data['seat_number'],
272
+ is_table_leader=participant_data.get('is_table_leader', False),
273
+ created_at=created_at,
274
+ has_paid=participant_data.get('has_paid', False),
275
+ note=participant_data.get('note', '')
276
+ )
277
+ db.session.add(participant)
278
+ print(f"已更新參與者: {participant.nickname}")
279
+
280
+ db.session.commit()
281
+ print("參與者資料更新完成")
282
+ except Exception as e:
283
+ print(f"同步資料時出錯: {str(e)}")
284
+
285
+ except Exception as e:
286
+ print(f"初始化資料庫時出錯: {str(e)}")
287
+
288
+ # 管理者認證裝飾器
289
+ def admin_required(f):
290
+ @wraps(f)
291
+ def decorated_function(*args, **kwargs):
292
+ if not session.get('admin_logged_in'):
293
+ return redirect(url_for('admin_login'))
294
+ return f(*args, **kwargs)
295
+ return decorated_function
296
+
297
+ # 添加新的環境變數
298
+ SETTINGS_SCRIPT_URL = os.environ.get('SETTINGS_SCRIPT_URL', '')
299
+
300
+ def sync_settings_to_sheets(action, data):
301
+ """同步設定到 Google Sheets"""
302
+ if not app.config['SETTINGS_SCRIPT_URL']:
303
+ print("未設定 SETTINGS_SCRIPT_URL")
304
+ return {'success': False, 'error': '未設定 Google Sheets URL'}
305
+
306
+ try:
307
+ print(f"正在同步到 Google Sheets: action={action}, data={data}")
308
+ response = requests.post(app.config['SETTINGS_SCRIPT_URL'], json={
309
+ 'action': action,
310
+ **data
311
+ })
312
+ print(f"Google Sheets 回應狀態碼: {response.status_code}")
313
+ print(f"Google Sheets 回應內容: {response.text}")
314
+
315
+ if response.status_code != 200:
316
+ return {'success': False, 'error': f'Google Sheets 回應錯誤: {response.status_code}'}
317
+
318
+ try:
319
+ result = response.json()
320
+ return result
321
+ except ValueError as e:
322
+ print(f"JSON 解析錯誤: {str(e)}")
323
+ return {'success': False, 'error': '無效的 JSON 回應'}
324
+
325
+ except Exception as e:
326
+ print(f"同步到 Google Sheets 時出錯: {str(e)}")
327
+ return {'success': False, 'error': str(e)}
328
+
329
+ def _backup_data_internal():
330
+ """內部函數:同步參與者資料到 Google Sheets"""
331
+ try:
332
+ all_participants = Participant.query.all()
333
+ participants_data = []
334
+
335
+ for p in all_participants:
336
+ local_time = p.created_at + timedelta(hours=8) # 轉換為台灣時間
337
+ participants_data.append({
338
+ 'id': p.id,
339
+ 'nickname': p.nickname,
340
+ 'email': p.email,
341
+ 'fb_link': p.fb_link,
342
+ 'introduction': p.introduction,
343
+ 'table_id': p.table_id,
344
+ 'seat_number': p.seat_number,
345
+ 'is_table_leader': p.is_table_leader,
346
+ 'created_at': local_time.strftime('%Y-%m-%d %H:%M:%S'),
347
+ 'has_paid': p.has_paid,
348
+ 'note': p.note or ''
349
+ })
350
+
351
+ # 同步到 Google Sheets
352
+ response = requests.post(SETTINGS_SCRIPT_URL, json={
353
+ 'action': 'backupParticipants', # 修正 action 名稱
354
+ 'participants': participants_data # 修正資料格式
355
+ })
356
+
357
+ if response.status_code != 200:
358
+ raise Exception(f"同步到 Google Sheets 失敗: {response.text}")
359
+
360
+ return True
361
+ except Exception as e:
362
+ print(f"備份資料時出錯: {str(e)}")
363
+ raise e
364
+
365
+ @app.route('/api/admin/backup', methods=['POST'])
366
+ @admin_required
367
+ def backup_data():
368
+ """API 路由:備份參與者資料(需要管理員權限)"""
369
+ try:
370
+ _backup_data_internal()
371
+ return jsonify({'message': '備份成功'})
372
+ except Exception as e:
373
+ return jsonify({'error': str(e)}), 500
374
+
375
+ @app.route('/')
376
+ def index():
377
+ return render_template('index.html')
378
+
379
+ @app.route('/admin/login')
380
+ def admin_login():
381
+ return render_template('admin_login.html')
382
+
383
+ @app.route('/admin')
384
+ @admin_required
385
+ def admin():
386
+ return render_template('admin.html')
387
+
388
+ @app.route('/api/admin/login', methods=['POST'])
389
+ def admin_login_api():
390
+ data = request.json
391
+ if data.get('password') == app.config['ADMIN_PASSWORD']:
392
+ session['admin_logged_in'] = True
393
+ return jsonify({'success': True, 'message': 'Login successful'}), 200
394
+ return jsonify({'success': False, 'error': 'Invalid password'}), 401
395
+
396
+ @app.route('/api/admin/settings/update', methods=['POST'])
397
+ @admin_required
398
+ def update_settings():
399
+ try:
400
+ data = request.get_json()
401
+ action = data.get('action')
402
+
403
+ if action == 'update_tables':
404
+ total_tables = int(data.get('total_tables', 10))
405
+ seats_per_table = int(data.get('seats_per_table', 10))
406
+
407
+ # 更新 Google Sheets
408
+ sync_settings_to_sheets('updateSettings', {
409
+ 'total_tables': total_tables,
410
+ 'seats_per_table': seats_per_table
411
+ })
412
+
413
+ # 更新資料庫中的桌次
414
+ current_tables = Table.query.order_by(Table.id).all()
415
+ current_count = len(current_tables)
416
+
417
+ if total_tables > current_count:
418
+ # 需要添加新桌次
419
+ for i in range(current_count + 1, total_tables + 1):
420
+ new_table = Table(id=i, capacity=seats_per_table)
421
+ db.session.add(new_table)
422
+ elif total_tables < current_count:
423
+ # 需要刪除多餘的桌次
424
+ # 檢查要刪除的桌次是否有參與者
425
+ for table in current_tables[total_tables:]:
426
+ if len(table.participants) > 0: # 只刪除沒有參與者的桌次
427
+ return jsonify({
428
+ 'error': f'無法刪除第 {table.id} 桌,因為還有參與者在該桌'
429
+ }), 400
430
+ db.session.delete(table)
431
+
432
+ # 更新所有桌次的容量
433
+ for table in Table.query.all():
434
+ table.capacity = seats_per_table
435
+
436
+ db.session.commit()
437
+
438
+ return jsonify({
439
+ 'message': '設定已更新',
440
+ 'settings': {
441
+ 'total_tables': total_tables,
442
+ 'seats_per_table': seats_per_table
443
+ }
444
+ })
445
+
446
+ elif action == 'update_table_name':
447
+ table_id = data.get('table_id')
448
+ name = data.get('name', '')
449
+
450
+ table = Table.query.get(table_id)
451
+ if not table:
452
+ return jsonify({'error': '找不到該桌次'}), 404
453
+
454
+ table.name = name
455
+ db.session.commit()
456
+
457
+ # 同步到 Google Sheets
458
+ sync_settings_to_sheets('update_table_name', {
459
+ 'table_id': table_id,
460
+ 'name': name
461
+ })
462
+
463
+ return jsonify({
464
+ 'message': '桌次名稱已更新',
465
+ 'table': {
466
+ 'id': table.id,
467
+ 'name': table.name
468
+ }
469
+ })
470
+
471
+ return jsonify({'error': '未知的操作'}), 400
472
+
473
+ except Exception as e:
474
+ print(f"更新設定時出錯: {str(e)}")
475
+ db.session.rollback()
476
+ return jsonify({'error': str(e)}), 500
477
+
478
+ @app.route('/api/admin/settings/backup', methods=['POST'])
479
+ @admin_required
480
+ def backup_settings():
481
+ try:
482
+ # 獲取當前所有桌子設定
483
+ tables = Table.query.all()
484
+ total_tables = len(tables)
485
+ seats_per_table = tables[0].capacity if tables else 0
486
+
487
+ # 同步設定到 Sheets
488
+ sync_settings_to_sheets('saveSettings', {
489
+ 'totalTables': total_tables,
490
+ 'seatsPerTable': seats_per_table
491
+ })
492
+
493
+ # 備份參與者資料
494
+ participants = Participant.query.all()
495
+ sync_settings_to_sheets('backupParticipants', {
496
+ 'participants': [{
497
+ 'id': p.id,
498
+ 'nickname': p.nickname,
499
+ 'email': p.email,
500
+ 'fb_link': p.fb_link,
501
+ 'introduction': p.introduction,
502
+ 'table_id': p.table_id,
503
+ 'seat_number': p.seat_number,
504
+ 'is_table_leader': p.is_table_leader,
505
+ 'created_at': p.created_at.strftime('%Y-%m-%d %H:%M:%S'),
506
+ 'has_paid': p.has_paid,
507
+ 'note': p.note
508
+ } for p in participants]
509
+ })
510
+
511
+ return jsonify({'message': '備份成功'})
512
+ except Exception as e:
513
+ return jsonify({'error': str(e)}), 500
514
+
515
+ @app.route('/api/admin/settings/restore', methods=['POST'])
516
+ @admin_required
517
+ def restore_data():
518
+ try:
519
+ # 從 Google Apps Script 獲取數據
520
+ print("正在從 Google Sheets 同步資料...")
521
+ response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
522
+ print("Google Sheets 回應狀態碼:", response.status_code)
523
+
524
+ try:
525
+ data = response.json()
526
+ except ValueError as e:
527
+ print("JSON 解析錯誤:", str(e))
528
+ print("原始回應內容:", response.text)
529
+ return jsonify({'error': '從 Google Sheets 獲取資料失敗:無效的 JSON 格式'}), 500
530
+
531
+ if not data.get('success'):
532
+ error_msg = data.get('error', '從 Google Sheets 恢復資料失敗')
533
+ print("Google Sheets 返回錯誤:", error_msg)
534
+ return jsonify({'error': error_msg}), 400
535
+
536
+ # 更新桌次設定
537
+ settings = data.get('settings', {})
538
+ print(f"從 Google Sheets 讀取設定:總桌數={settings.get('total_tables')}, 每桌人數={settings.get('seats_per_table')}")
539
+
540
+ # 更新桌次名稱
541
+ tables_data = data.get('tables', [])
542
+ for table_data in tables_data:
543
+ table = Table.query.get(table_data.get('id'))
544
+ if table and 'name' in table_data:
545
+ table.name = table_data['name']
546
+ db.session.commit()
547
+ print("桌次設定更新完成")
548
+
549
+ # 清空現有的參與者資料
550
+ Participant.query.delete()
551
+
552
+ # 恢復參與者資料
553
+ participants_data = data.get('participants', [])
554
+ print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料")
555
+
556
+ for participant_data in participants_data:
557
+ # 處理 ISO 格式的時間
558
+ created_at_str = participant_data['created_at'].replace('T', ' ').replace('.000Z', '')
559
+ created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
560
+
561
+ try:
562
+ participant = Participant(
563
+ nickname=participant_data['nickname'],
564
+ email=participant_data['email'],
565
+ fb_link=participant_data.get('fb_link', ''),
566
+ introduction=participant_data.get('introduction', ''),
567
+ table_id=int(participant_data['table_id']),
568
+ seat_number=int(participant_data['seat_number']),
569
+ is_table_leader=bool(participant_data.get('is_table_leader', False)),
570
+ created_at=created_at,
571
+ has_paid=bool(participant_data.get('has_paid', False)),
572
+ note=participant_data.get('note', '')
573
+ )
574
+ db.session.add(participant)
575
+ print(f"已更新參與者: {participant.nickname}")
576
+ except (KeyError, ValueError) as e:
577
+ print(f"處理參與者資料時出錯: {str(e)}")
578
+ print(f"問題資料: {participant_data}")
579
+ continue
580
+
581
+ db.session.commit()
582
+ print("參與者資料更新完成")
583
+ return jsonify({'message': '資料已成功恢復'})
584
+
585
+ except Exception as e:
586
+ db.session.rollback()
587
+ print('恢復資料時出錯:', str(e))
588
+ return jsonify({'error': str(e)}), 500
589
+
590
+ @app.route('/api/admin/settings', methods=['GET'])
591
+ @admin_required
592
+ def get_settings():
593
+ try:
594
+ # 從 Google Sheets 獲取最新設定
595
+ response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
596
+ if response.status_code == 200:
597
+ data = response.json()
598
+ if data.get('success'):
599
+ settings = data.get('settings', {})
600
+ return jsonify({
601
+ 'total_tables': settings.get('total_tables', 10),
602
+ 'seats_per_table': settings.get('seats_per_table', 10)
603
+ })
604
+
605
+ # 如果無法從 Google Sheets 獲取,使用資料庫中的設定
606
+ total_tables = Table.query.count()
607
+ first_table = Table.query.first()
608
+ seats_per_table = first_table.capacity if first_table else 10
609
+
610
+ return jsonify({
611
+ 'total_tables': total_tables,
612
+ 'seats_per_table': seats_per_table
613
+ })
614
+ except Exception as e:
615
+ print(f"獲取設定時出錯: {str(e)}")
616
+ return jsonify({'error': str(e)}), 500
617
+
618
+ @app.route('/api/admin/participants', methods=['GET'])
619
+ @admin_required
620
+ def get_all_participants():
621
+ try:
622
+ participants = Participant.query.all()
623
+ tables = Table.query.all()
624
+ return jsonify({
625
+ 'participants': [{
626
+ 'id': p.id,
627
+ 'nickname': p.nickname,
628
+ 'email': p.email,
629
+ 'fb_link': p.fb_link,
630
+ 'introduction': p.introduction,
631
+ 'table_id': p.table_id,
632
+ 'seat_number': p.seat_number,
633
+ 'is_table_leader': p.is_table_leader,
634
+ 'created_at': p.created_at.strftime('%Y-%m-%d %H:%M:%S'),
635
+ 'has_paid': p.has_paid,
636
+ 'note': p.note
637
+ } for p in participants],
638
+ 'tables': [{
639
+ 'id': t.id,
640
+ 'name': t.name,
641
+ 'capacity': t.capacity,
642
+ 'current_seats': len(Participant.query.filter_by(table_id=t.id).all())
643
+ } for t in tables]
644
+ })
645
+ except Exception as e:
646
+ return jsonify({'error': str(e)}), 500
647
+
648
+ @app.route('/api/admin/participant/<int:participant_id>/move', methods=['POST'])
649
+ @admin_required
650
+ def move_participant(participant_id):
651
+ try:
652
+ data = request.get_json()
653
+ new_table_id = data.get('new_table_id')
654
+
655
+ if not new_table_id:
656
+ return jsonify({'error': '請提供新的桌號'}), 400
657
+
658
+ participant = Participant.query.get(participant_id)
659
+ if not participant:
660
+ return jsonify({'error': '找不到該參與者'}), 404
661
+
662
+ new_table = Table.query.get(new_table_id)
663
+ if not new_table:
664
+ return jsonify({'error': '找不到該桌子'}), 404
665
+
666
+ # 檢查新桌子是否已滿
667
+ current_seats = len(Participant.query.filter_by(table_id=new_table_id).all())
668
+ if current_seats >= new_table.capacity:
669
+ return jsonify({'error': '該桌已滿'}), 400
670
+
671
+ # 更新座位號碼
672
+ participant.table_id = new_table_id
673
+ participant.seat_number = current_seats + 1
674
+
675
+ db.session.commit()
676
+
677
+ # 同步到 Google Sheets
678
+ try:
679
+ _backup_data_internal() # 使用內部函數而不是 API 路由
680
+ print("成功備份參與者資料到 Google Sheets")
681
+ except Exception as e:
682
+ print(f"同步到 Google Sheets 時出錯: {str(e)}")
683
+ # 不中斷操作,只記錄錯誤
684
+
685
+ return jsonify({
686
+ 'message': '成功移動座位',
687
+ 'participant': {
688
+ 'id': participant.id,
689
+ 'nickname': participant.nickname,
690
+ 'table_id': participant.table_id,
691
+ 'seat_number': participant.seat_number
692
+ }
693
+ })
694
+ except Exception as e:
695
+ db.session.rollback()
696
+ return jsonify({'error': str(e)}), 500
697
+
698
+ @app.route('/api/admin/participants/<int:participant_id>', methods=['DELETE'])
699
+ @admin_required
700
+ def delete_participant(participant_id):
701
+ try:
702
+ participant = Participant.query.get(participant_id)
703
+ if participant:
704
+ db.session.delete(participant)
705
+ db.session.commit()
706
+
707
+ # 同步到 Google Sheets
708
+ try:
709
+ _backup_data_internal() # 使用內部函數而不是 API 路由
710
+ print("成功備份參與者資料到 Google Sheets")
711
+ except Exception as e:
712
+ print(f"同步到 Google Sheets 時出錯: {str(e)}")
713
+ # 不中斷操作,只記錄錯誤
714
+
715
+ return jsonify({'message': 'Participant deleted successfully'})
716
+ return jsonify({'error': 'Participant not found'}), 404
717
+ except Exception as e:
718
+ db.session.rollback()
719
+ return jsonify({'error': str(e)}), 400
720
+
721
+ @app.route('/api/tables', methods=['GET'])
722
+ def get_tables():
723
+ try:
724
+ print("正在獲取桌次資料...")
725
+
726
+ # 如果是從管理後台呼叫,先從 Google Sheets 同步資料
727
+ if request.referrer and '/admin' in request.referrer:
728
+ print("從管理後台呼叫,同步 Google Sheets 資料...")
729
+ try:
730
+ response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
731
+ if response.status_code == 200:
732
+ data = response.json()
733
+ if data.get('success'):
734
+ # 更新桌次名稱
735
+ tables_data = data.get('tables', [])
736
+ table_names = {table['id']: table['name'] for table in tables_data}
737
+ for table in Table.query.all():
738
+ if table.id in table_names:
739
+ table.name = table_names[table.id]
740
+
741
+ # 更新參與者資料
742
+ participants_data = data.get('participants', [])
743
+ for p_data in participants_data:
744
+ participant = Participant.query.get(p_data['id'])
745
+ if participant:
746
+ participant.nickname = p_data['nickname']
747
+ participant.email = p_data['email']
748
+ participant.fb_link = p_data.get('fb_link', '')
749
+ participant.introduction = p_data.get('introduction', '')
750
+ participant.table_id = int(p_data['table_id'])
751
+ participant.seat_number = int(p_data['seat_number'])
752
+ participant.is_table_leader = bool(p_data.get('is_table_leader', False))
753
+ participant.has_paid = bool(p_data.get('has_paid', False))
754
+ participant.note = p_data.get('note', '')
755
+
756
+ db.session.commit()
757
+ print("資料已從 Google Sheets 更新")
758
+ else:
759
+ print("從 Google Sheets 獲取資料失敗")
760
+ else:
761
+ print(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}")
762
+ except Exception as e:
763
+ print(f"同步 Google Sheets 資料時出錯: {str(e)}")
764
+
765
+ # 從資料庫獲取桌次資料
766
+ tables = Table.query.order_by(Table.id).all()
767
+ print(f"找到 {len(tables)} 張桌子")
768
+
769
+ # 轉換成 JSON 格式
770
+ result = {
771
+ 'tables': [table.to_dict() for table in tables]
772
+ }
773
+
774
+ print("桌次資料獲取成功")
775
+ return jsonify(result)
776
+
777
+ except Exception as e:
778
+ print(f"獲取桌次資料時出錯: {str(e)}")
779
+ return jsonify({'error': str(e)}), 500
780
+
781
+ @app.route('/api/register', methods=['POST'])
782
+ def register():
783
+ try:
784
+ data = request.get_json()
785
+
786
+ # 驗證必填欄位
787
+ if not all(key in data for key in ['nickname', 'email', 'table_id']):
788
+ return jsonify({'error': '缺少必要欄位'}), 400
789
+
790
+ # 檢查桌子是否存在且有空位
791
+ table = Table.query.get(data['table_id'])
792
+ if not table:
793
+ return jsonify({'error': '找不到該桌子'}), 404
794
+
795
+ current_seats = len(Participant.query.filter_by(table_id=data['table_id']).all())
796
+ if current_seats >= table.capacity:
797
+ return jsonify({'error': '該桌已滿'}), 400
798
+
799
+ # 創建新參與者
800
+ participant = Participant(
801
+ nickname=data['nickname'],
802
+ email=data['email'],
803
+ fb_link=data.get('fb_link', ''),
804
+ introduction=data.get('introduction', ''),
805
+ table_id=data['table_id'],
806
+ seat_number=current_seats + 1
807
+ )
808
+
809
+ db.session.add(participant)
810
+ db.session.commit()
811
+
812
+ # 同步到 Google Sheets
813
+ try:
814
+ _backup_data_internal() # 使用內部函數而不是 API 路由
815
+ print("成功備份參與者資料到 Google Sheets")
816
+ except Exception as e:
817
+ print(f"同步到 Google Sheets 時出錯: {str(e)}")
818
+ # 不中斷操作,只記錄錯誤
819
+
820
+ return jsonify({
821
+ 'message': '報名成功',
822
+ 'participant': {
823
+ 'id': participant.id,
824
+ 'nickname': participant.nickname,
825
+ 'table_id': participant.table_id,
826
+ 'seat_number': participant.seat_number
827
+ }
828
+ })
829
+
830
+ except Exception as e:
831
+ return jsonify({'error': str(e)}), 500
832
+
833
+ @app.route('/api/participants/export', methods=['GET'])
834
+ def export_participants():
835
+ try:
836
+ participants = Participant.query.all()
837
+ export_data = []
838
+
839
+ for participant in participants:
840
+ local_time = participant.created_at + timedelta(hours=8) # 轉換為台灣時間
841
+ export_data.append({
842
+ 'nickname': participant.nickname,
843
+ 'email': participant.email,
844
+ 'fb_link': participant.fb_link,
845
+ 'introduction': participant.introduction,
846
+ 'table_id': participant.table_id,
847
+ 'seat_number': participant.seat_number,
848
+ 'is_table_leader': '是' if participant.is_table_leader else '否',
849
+ 'registration_time': local_time.strftime('%Y-%m-%d %H:%M:%S'),
850
+ 'has_paid': '是' if participant.has_paid else '否',
851
+ 'note': participant.note or ''
852
+ })
853
+
854
+ return jsonify(export_data)
855
+ except Exception as e:
856
+ return jsonify({'error': str(e)}), 500
857
+
858
+ @app.route('/api/admin/participant/<int:participant_id>/toggle-leader', methods=['POST'])
859
+ @admin_required
860
+ def toggle_leader(participant_id):
861
+ try:
862
+ participant = Participant.query.get(participant_id)
863
+ if not participant:
864
+ return jsonify({'error': '找不到該參與者'}), 404
865
+
866
+ # 如果要設為桌長,先確認該桌是否已有桌長
867
+ if not participant.is_table_leader:
868
+ existing_leader = Participant.query.filter_by(
869
+ table_id=participant.table_id,
870
+ is_table_leader=True
871
+ ).first()
872
+
873
+ if existing_leader:
874
+ return jsonify({
875
+ 'error': f'該桌已有桌長:{existing_leader.nickname}'
876
+ }), 400
877
+
878
+ # 切換桌長狀態
879
+ participant.is_table_leader = not participant.is_table_leader
880
+ db.session.commit()
881
+
882
+ # 同步到 Google Sheets
883
+ try:
884
+ _backup_data_internal() # 使用內部函數而不是 API 路由
885
+ except Exception as e:
886
+ print(f"同步到 Google Sheets 時出錯: {str(e)}")
887
+ # 不中斷操作,只記錄錯誤
888
+
889
+ return jsonify({
890
+ 'message': f'已{participant.is_table_leader and "設為" or "取消"}桌長',
891
+ 'participant': participant.to_dict()
892
+ })
893
+ except Exception as e:
894
+ print("更新桌長狀態時出錯:", str(e))
895
+ return jsonify({'error': str(e)}), 500
896
+
897
+ @app.route('/api/admin/participant/<int:participant_id>/payment', methods=['POST'])
898
+ @admin_required
899
+ def toggle_payment(participant_id):
900
+ try:
901
+ participant = Participant.query.get(participant_id)
902
+ if not participant:
903
+ return jsonify({'error': '找不到該參與者'}), 404
904
+
905
+ participant.has_paid = not participant.has_paid
906
+ db.session.commit()
907
+
908
+ # 同步到 Google Sheets
909
+ try:
910
+ _backup_data_internal() # 使用內部函數而不是 API 路由
911
+ except Exception as e:
912
+ print(f"同步到 Google Sheets 時出錯: {str(e)}")
913
+ # 不中斷操作,只記錄錯誤
914
+
915
+ return jsonify({
916
+ 'message': f'已更新付款狀態為{"已" if participant.has_paid else "未"}付款',
917
+ 'participant': participant.to_dict()
918
+ })
919
+ except Exception as e:
920
+ print("更新付款狀態時出錯:", str(e))
921
+ return jsonify({'error': str(e)}), 500
922
+
923
+ @app.route('/api/admin/participant/<int:participant_id>/note', methods=['POST'])
924
+ @admin_required
925
+ def update_participant_note(participant_id):
926
+ try:
927
+ data = request.get_json()
928
+ note = data.get('note', '')
929
+
930
+ participant = Participant.query.get(participant_id)
931
+ if not participant:
932
+ return jsonify({'error': '找不到該參與者'}), 404
933
+
934
+ participant.note = note
935
+ db.session.commit()
936
+
937
+ # 同步到 Google Sheets
938
+ try:
939
+ _backup_data_internal() # 使用內部函數而不是 API 路由
940
+ except Exception as e:
941
+ print(f"同步到 Google Sheets 時出錯: {str(e)}")
942
+ # 不中斷操作,只記錄錯誤
943
+
944
+ return jsonify({
945
+ 'message': '備註已更新',
946
+ 'participant': participant.to_dict()
947
+ })
948
+ except Exception as e:
949
+ print("更新備註時出錯:", str(e))
950
+ return jsonify({'error': str(e)}), 500
951
+
952
+ if __name__ == '__main__':
953
+ app.run(host='0.0.0.0', port=7860)
app.py CHANGED
@@ -342,16 +342,16 @@ def _backup_data_internal():
342
  'introduction': p.introduction,
343
  'table_id': p.table_id,
344
  'seat_number': p.seat_number,
345
- 'is_table_leader': '是' if p.is_table_leader else '否', # 轉換為中文
346
  'created_at': local_time.strftime('%Y-%m-%d %H:%M:%S'),
347
- 'has_paid': '是' if p.has_paid else '否', # 轉換為中文
348
  'note': p.note or ''
349
  })
350
 
351
  # 同步到 Google Sheets
352
  response = requests.post(SETTINGS_SCRIPT_URL, json={
353
- 'action': 'backupParticipants',
354
- 'participants': participants_data
355
  })
356
 
357
  if response.status_code != 200:
@@ -517,11 +517,9 @@ def backup_settings():
517
  def restore_data():
518
  try:
519
  # 從 Google Apps Script 獲取數據
520
- print("正在從 Google Apps Script 獲取數據...")
521
  response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
522
- print("Response status code:", response.status_code)
523
- print("Response headers:", response.headers)
524
- print("Response content:", response.text)
525
 
526
  try:
527
  data = response.json()
@@ -532,15 +530,28 @@ def restore_data():
532
 
533
  if not data.get('success'):
534
  error_msg = data.get('error', '從 Google Sheets 恢復資料失敗')
535
- print("Google Apps Script 返回錯誤:", error_msg)
536
  return jsonify({'error': error_msg}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
537
 
538
  # 清空現有的參與者資料
539
  Participant.query.delete()
540
 
541
  # 恢復參與者資料
542
  participants_data = data.get('participants', [])
543
- print(f"找到 {len(participants_data)} 個參與者資料")
544
 
545
  for participant_data in participants_data:
546
  # 處理 ISO 格式的時間
@@ -555,20 +566,20 @@ def restore_data():
555
  introduction=participant_data.get('introduction', ''),
556
  table_id=int(participant_data['table_id']),
557
  seat_number=int(participant_data['seat_number']),
558
- is_table_leader=participant_data.get('is_table_leader') == '是', # 從中文轉換
559
  created_at=created_at,
560
- has_paid=participant_data.get('has_paid') == '是', # 從中文轉換
561
  note=participant_data.get('note', '')
562
  )
563
  db.session.add(participant)
564
- print(f"已添加參與者: {participant.nickname}")
565
  except (KeyError, ValueError) as e:
566
  print(f"處理參與者資料時出錯: {str(e)}")
567
  print(f"問題資料: {participant_data}")
568
  continue
569
 
570
  db.session.commit()
571
- print("資料恢復完成")
572
  return jsonify({'message': '資料已成功恢復'})
573
 
574
  except Exception as e:
@@ -665,7 +676,7 @@ def move_participant(participant_id):
665
 
666
  # 同步到 Google Sheets
667
  try:
668
- _backup_data_internal() # 使用內部函數而不是 API 路由
669
  print("成功備份參與者資料到 Google Sheets")
670
  except Exception as e:
671
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
@@ -695,7 +706,7 @@ def delete_participant(participant_id):
695
 
696
  # 同步到 Google Sheets
697
  try:
698
- _backup_data_internal() # 使用內部函數而不是 API 路由
699
  print("成功備份參與者資料到 Google Sheets")
700
  except Exception as e:
701
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
@@ -800,7 +811,7 @@ def register():
800
 
801
  # 同步到 Google Sheets
802
  try:
803
- _backup_data_internal() # 使用內部函數而不是 API 路由
804
  print("成功備份參與者資料到 Google Sheets")
805
  except Exception as e:
806
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
@@ -870,7 +881,7 @@ def toggle_leader(participant_id):
870
 
871
  # 同步到 Google Sheets
872
  try:
873
- _backup_data_internal() # 使用內部函數而不是 API 路由
874
  except Exception as e:
875
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
876
  # 不中斷操作,只記錄錯誤
@@ -896,7 +907,7 @@ def toggle_payment(participant_id):
896
 
897
  # 同步到 Google Sheets
898
  try:
899
- _backup_data_internal() # 使用內部函數而不是 API 路由
900
  except Exception as e:
901
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
902
  # 不中斷操作,只記錄錯誤
@@ -925,7 +936,7 @@ def update_participant_note(participant_id):
925
 
926
  # 同步到 Google Sheets
927
  try:
928
- _backup_data_internal() # 使用內部函數而不是 API 路由
929
  except Exception as e:
930
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
931
  # 不中斷操作,只記錄錯誤
 
342
  'introduction': p.introduction,
343
  'table_id': p.table_id,
344
  'seat_number': p.seat_number,
345
+ 'is_table_leader': p.is_table_leader,
346
  'created_at': local_time.strftime('%Y-%m-%d %H:%M:%S'),
347
+ 'has_paid': p.has_paid,
348
  'note': p.note or ''
349
  })
350
 
351
  # 同步到 Google Sheets
352
  response = requests.post(SETTINGS_SCRIPT_URL, json={
353
+ 'action': 'backupParticipants',
354
+ 'participants': participants_data
355
  })
356
 
357
  if response.status_code != 200:
 
517
  def restore_data():
518
  try:
519
  # 從 Google Apps Script 獲取數據
520
+ print("正在從 Google Sheets 同步資料...")
521
  response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
522
+ print("Google Sheets 回應狀態碼:", response.status_code)
 
 
523
 
524
  try:
525
  data = response.json()
 
530
 
531
  if not data.get('success'):
532
  error_msg = data.get('error', '從 Google Sheets 恢復資料失敗')
533
+ print("Google Sheets 返回錯誤:", error_msg)
534
  return jsonify({'error': error_msg}), 400
535
+
536
+ # 更新桌次設定
537
+ settings = data.get('settings', {})
538
+ print(f"從 Google Sheets 讀取設定:總桌數={settings.get('total_tables')}, 每桌人數={settings.get('seats_per_table')}")
539
+
540
+ # 更新桌次名稱
541
+ tables_data = data.get('tables', [])
542
+ for table_data in tables_data:
543
+ table = Table.query.get(table_data.get('id'))
544
+ if table and 'name' in table_data:
545
+ table.name = table_data['name']
546
+ db.session.commit()
547
+ print("桌次設定更新完成")
548
 
549
  # 清空現有的參與者資料
550
  Participant.query.delete()
551
 
552
  # 恢復參與者資料
553
  participants_data = data.get('participants', [])
554
+ print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料")
555
 
556
  for participant_data in participants_data:
557
  # 處理 ISO 格式的時間
 
566
  introduction=participant_data.get('introduction', ''),
567
  table_id=int(participant_data['table_id']),
568
  seat_number=int(participant_data['seat_number']),
569
+ is_table_leader=participant_data.get('is_table_leader') == True or participant_data.get('is_table_leader') == 'TRUE',
570
  created_at=created_at,
571
+ has_paid=participant_data.get('has_paid') == True or participant_data.get('has_paid') == 'TRUE',
572
  note=participant_data.get('note', '')
573
  )
574
  db.session.add(participant)
575
+ print(f"已更新參與者: {participant.nickname}")
576
  except (KeyError, ValueError) as e:
577
  print(f"處理參與者資料時出錯: {str(e)}")
578
  print(f"問題資料: {participant_data}")
579
  continue
580
 
581
  db.session.commit()
582
+ print("參與者資料更新完成")
583
  return jsonify({'message': '資料已成功恢復'})
584
 
585
  except Exception as e:
 
676
 
677
  # 同步到 Google Sheets
678
  try:
679
+ _backup_data_internal()
680
  print("成功備份參與者資料到 Google Sheets")
681
  except Exception as e:
682
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
 
706
 
707
  # 同步到 Google Sheets
708
  try:
709
+ _backup_data_internal()
710
  print("成功備份參與者資料到 Google Sheets")
711
  except Exception as e:
712
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
 
811
 
812
  # 同步到 Google Sheets
813
  try:
814
+ _backup_data_internal()
815
  print("成功備份參與者資料到 Google Sheets")
816
  except Exception as e:
817
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
 
881
 
882
  # 同步到 Google Sheets
883
  try:
884
+ _backup_data_internal()
885
  except Exception as e:
886
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
887
  # 不中斷操作,只記錄錯誤
 
907
 
908
  # 同步到 Google Sheets
909
  try:
910
+ _backup_data_internal()
911
  except Exception as e:
912
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
913
  # 不中斷操作,只記錄錯誤
 
936
 
937
  # 同步到 Google Sheets
938
  try:
939
+ _backup_data_internal()
940
  except Exception as e:
941
  print(f"同步到 Google Sheets 時出錯: {str(e)}")
942
  # 不中斷操作,只記錄錯誤
sync_settings.gs CHANGED
@@ -81,9 +81,9 @@ function doGet() {
81
  introduction: row[4] || '',
82
  table_id: parseInt(row[5]) || 0,
83
  seat_number: parseInt(row[6]) || 0,
84
- is_table_leader: Boolean(row[7]),
85
  created_at: row[8],
86
- has_paid: Boolean(row[9]),
87
  note: row[10] || ''
88
  };
89
  participants.push(participant);
@@ -207,11 +207,11 @@ function backupParticipants(sheet, participants) {
207
  p.email,
208
  p.fb_link || '',
209
  p.introduction || '',
210
- p.table_id,
211
- p.seat_number,
212
- p.is_table_leader ? '是' : '否',
213
- p.created_at,
214
- p.has_paid ? '是' : '否',
215
  p.note || ''
216
  ];
217
  });
 
81
  introduction: row[4] || '',
82
  table_id: parseInt(row[5]) || 0,
83
  seat_number: parseInt(row[6]) || 0,
84
+ is_table_leader: row[7] === true || row[7] === 'TRUE', // 使用 TRUE/FALSE
85
  created_at: row[8],
86
+ has_paid: row[9] === true || row[9] === 'TRUE', // 使用 TRUE/FALSE
87
  note: row[10] || ''
88
  };
89
  participants.push(participant);
 
207
  p.email,
208
  p.fb_link || '',
209
  p.introduction || '',
210
+ p.table_id || 0,
211
+ p.seat_number || 0,
212
+ p.is_table_leader ? 'TRUE' : 'FALSE', // 使用 TRUE/FALSE
213
+ p.created_at || '',
214
+ p.has_paid ? 'TRUE' : 'FALSE', // 使用 TRUE/FALSE
215
  p.note || ''
216
  ];
217
  });