ichieh commited on
Commit
71e734b
·
1 Parent(s): dc8d1ea

修改桌次名稱同步

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