from flask import Flask, render_template, request, jsonify, session, redirect, url_for, current_app from flask_sqlalchemy import SQLAlchemy from datetime import datetime, timedelta import os import time from functools import wraps import requests import shutil # 添加新的環境變數 SETTINGS_SCRIPT_URL = os.environ.get('SETTINGS_SCRIPT_URL', '') ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin') app = Flask(__name__, instance_relative_config=True) # 設置 session secret key app.secret_key = os.urandom(24) # 設置管理者密碼和 Google Apps Script URL app.config['ADMIN_PASSWORD'] = ADMIN_PASSWORD app.config['SETTINGS_SCRIPT_URL'] = SETTINGS_SCRIPT_URL # 設置資料庫路徑 - 使用持久化存儲 if os.environ.get('SPACE_ID'): # 在 Hugging Face Spaces 環境中 # 確保資料目錄存在 os.makedirs('/data', exist_ok=True) db_path = '/data/event.db' # 檢查資料庫文件是否存在 if not os.path.exists(db_path): print(f"資料庫文件不存在:{db_path}") # 如果資料庫不存在,將創建一個新的 open(db_path, 'a').close() print("創建了新的資料庫文件") else: # 在本地開發環境中 # 確保 instance 目錄存在 os.makedirs(app.instance_path, exist_ok=True) db_path = os.path.join(app.instance_path, 'event.db') print(f"使用資料庫路徑: {db_path}") # 設置資料庫 app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class Table(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) # 新增桌次名稱欄位 capacity = db.Column(db.Integer, nullable=False) participants = db.relationship('Participant', backref='table', lazy=True) def to_dict(self): return { 'id': self.id, 'name': self.name or '', # 確保 name 不會是 None 'capacity': self.capacity, 'participants': [{ 'id': p.id, 'nickname': p.nickname, 'fb_link': p.fb_link, 'introduction': p.introduction, 'is_table_leader': p.is_table_leader, 'created_at': p.created_at, 'has_paid': p.has_paid, 'note': p.note } for p in sorted(self.participants, key=lambda x: (not x.is_table_leader, x.created_at))] } class Participant(db.Model): id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(100), nullable=False) email = db.Column(db.String(120), nullable=False) fb_link = db.Column(db.String(200)) introduction = db.Column(db.Text) table_id = db.Column(db.Integer, db.ForeignKey('table.id')) seat_number = db.Column(db.Integer) is_table_leader = db.Column(db.Boolean, default=False) created_at = db.Column(db.DateTime, default=datetime.utcnow) has_paid = db.Column(db.Boolean, default=False) note = db.Column(db.Text) def to_dict(self): return { 'id': self.id, 'nickname': self.nickname, 'email': self.email, 'fb_link': self.fb_link, 'introduction': self.introduction, 'table_id': self.table_id, 'seat_number': self.seat_number, 'is_table_leader': self.is_table_leader, 'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'), 'has_paid': self.has_paid, 'note': self.note } # 初始化資料庫和創建預設桌子 def init_db(): with app.app_context(): try: # 只創建不存在的表格 db.create_all() # 從 Google Sheets 獲取設定 print("正在從 Google Sheets 獲取設定...") try: if not app.config.get('SETTINGS_SCRIPT_URL'): print("未設定 SETTINGS_SCRIPT_URL,使用預設值") raise Exception("未設定 SETTINGS_SCRIPT_URL") response = requests.get(app.config['SETTINGS_SCRIPT_URL']) if response.status_code != 200: print(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}") raise Exception(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}") try: data = response.json() except ValueError as e: print("JSON 解析錯誤:", str(e)) print("原始回應內容:", response.text) raise if not data.get('success'): error_msg = data.get('error', '從 Google Sheets 獲取資料失敗') print("Google Sheets 返回錯誤:", error_msg) raise Exception(error_msg) # 獲取設定 settings = data.get('settings', {}) total_tables = settings.get('total_tables', 10) seats_per_table = settings.get('seats_per_table', 10) print(f"從 Google Sheets 獲取到的設定:") print(f"- 總桌數: {total_tables}") print(f"- 每桌人數: {seats_per_table}") # 清空現有的桌次和參與者資料 print("清空現有資料...") Participant.query.delete() Table.query.delete() # 創建桌次 tables_data = data.get('tables', []) print(f"從 Google Sheets 讀取 {len(tables_data)} 張桌子") for i in range(1, total_tables + 1): # 從 tables_data 中找到對應的桌次資料 table_data = next((t for t in tables_data if t['id'] == i), None) table_name = table_data['name'].strip() if table_data and table_data.get('name') else f'第{i}桌' table = Table( id=i, name=table_name, capacity=seats_per_table ) db.session.add(table) print(f"創建第 {i} 桌,名稱為: {table_name}") # 創建參與者 participants_data = data.get('participants', []) print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者") for p_data in participants_data: try: # 處理 ISO 格式的時間 created_at_str = p_data['created_at'].replace('T', ' ').replace('.000Z', '') created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S') participant = Participant( id=int(p_data['id']), nickname=p_data['nickname'], email=p_data['email'], fb_link=p_data.get('fb_link', ''), introduction=p_data.get('introduction', ''), table_id=int(p_data['table_id']), seat_number=int(p_data['seat_number']), is_table_leader=bool(p_data.get('is_table_leader', False)), created_at=created_at, has_paid=bool(p_data.get('has_paid', False)), note=p_data.get('note', '') ) db.session.add(participant) print(f"創建參與者: {participant.nickname}") except Exception as e: print(f"處理參與者資料時出錯: {str(e)}") print(f"問題資料: {p_data}") continue db.session.commit() print("資料庫初始化完成") except Exception as e: print(f"從 Google Sheets 獲取設定時出錯: {str(e)}") print("使用預設值") # 如果沒有任何桌次,創建預設桌次 if Table.query.count() == 0: for i in range(1, 11): # 預設 10 張桌子 table = Table(id=i, name=f'第{i}桌', capacity=10) # 預設每桌 10 人 db.session.add(table) db.session.commit() print("已創建預設桌次") except Exception as e: print(f"初始化資料庫時出錯: {str(e)}") db.session.rollback() raise # 在應用啟動時初始化資料庫 with app.app_context(): try: # 創建資料庫表格(如果不存在) db.create_all() print("資料庫表格創建成功") # 檢查資料庫連接 db.session.execute('SELECT 1') print("資料庫初始化成功") # 從 Google Sheets 同步資料 print("從 Google Sheets 同步資料...") try: response = requests.get(app.config['SETTINGS_SCRIPT_URL']) print(f"Google Sheets 回應狀態碼: {response.status_code}") print(f"Google Sheets 回應內容: {response.text}") data = response.json() if not data.get('success'): raise Exception(f"同步失敗: {data.get('error', '未知錯誤')}") # 清空現有資料 Participant.query.delete() Table.query.delete() db.session.commit() # 從 Google Sheets 讀取設定 settings = data.get('settings', {}) if not settings: raise Exception("無法從 Google Sheets 讀取設定") total_tables = int(settings.get('total_tables', 10)) seats_per_table = int(settings.get('seats_per_table', 10)) print(f"從 Google Sheets 讀取設定:總桌數={total_tables}, 每桌人數={seats_per_table}") # 創建桌子 for i in range(1, total_tables + 1): table = Table( name=f'第{i}桌', capacity=seats_per_table ) db.session.add(table) db.session.commit() print("桌次設定更新完成") # 恢復參與者資料 participants_data = data.get('participants', []) print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料") for participant_data in participants_data: created_at_str = participant_data['created_at'].replace('T', ' ').replace('.000Z', '') created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S') participant = Participant( nickname=participant_data['nickname'], email=participant_data['email'], fb_link=participant_data.get('fb_link', ''), introduction=participant_data.get('introduction', ''), table_id=participant_data['table_id'], seat_number=participant_data['seat_number'], is_table_leader=participant_data.get('is_table_leader', False), created_at=created_at, has_paid=participant_data.get('has_paid', False), note=participant_data.get('note', '') ) db.session.add(participant) print(f"已更新參與者: {participant.nickname}") db.session.commit() print("參與者資料更新完成") except Exception as e: print(f"同步資料時出錯: {str(e)}") except Exception as e: print(f"初始化資料庫時出錯: {str(e)}") # 管理者認證裝飾器 def admin_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not session.get('admin_logged_in'): return redirect(url_for('admin_login')) return f(*args, **kwargs) return decorated_function # 添加新的環境變數 SETTINGS_SCRIPT_URL = os.environ.get('SETTINGS_SCRIPT_URL', '') def sync_settings_to_sheets(action, data): """同步設定到 Google Sheets""" if not app.config['SETTINGS_SCRIPT_URL']: print("未設定 SETTINGS_SCRIPT_URL") return {'success': False, 'error': '未設定 Google Sheets URL'} try: print(f"正在同步到 Google Sheets: action={action}, data={data}") response = requests.post(app.config['SETTINGS_SCRIPT_URL'], json={ 'action': action, **data }) print(f"Google Sheets 回應狀態碼: {response.status_code}") print(f"Google Sheets 回應內容: {response.text}") if response.status_code != 200: return {'success': False, 'error': f'Google Sheets 回應錯誤: {response.status_code}'} try: result = response.json() return result except ValueError as e: print(f"JSON 解析錯誤: {str(e)}") return {'success': False, 'error': '無效的 JSON 回應'} except Exception as e: print(f"同步到 Google Sheets 時出錯: {str(e)}") return {'success': False, 'error': str(e)} def _backup_data_internal(): """內部函數:同步參與者資料到 Google Sheets""" try: all_participants = Participant.query.all() participants_data = [] for p in all_participants: local_time = p.created_at + timedelta(hours=8) # 轉換為台灣時間 participants_data.append({ 'id': p.id, 'nickname': p.nickname, 'email': p.email, 'fb_link': p.fb_link, 'introduction': p.introduction, 'table_id': p.table_id, 'seat_number': p.seat_number, 'is_table_leader': p.is_table_leader, 'created_at': local_time.strftime('%Y-%m-%d %H:%M:%S'), 'has_paid': p.has_paid, 'note': p.note or '' }) # 同步到 Google Sheets response = requests.post(SETTINGS_SCRIPT_URL, json={ 'action': 'backupParticipants', 'participants': participants_data }) if response.status_code != 200: raise Exception(f"同步到 Google Sheets 失敗: {response.text}") return True except Exception as e: print(f"備份資料時出錯: {str(e)}") raise e @app.route('/api/admin/backup', methods=['POST']) @admin_required def backup_data(): """API 路由:備份參與者資料(需要管理員權限)""" try: _backup_data_internal() return jsonify({'message': '備份成功'}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/') def index(): return render_template('index.html') @app.route('/admin/login') def admin_login(): return render_template('admin_login.html') @app.route('/admin') @admin_required def admin(): return render_template('admin.html') @app.route('/api/admin/login', methods=['POST']) def admin_login_api(): data = request.json if data.get('password') == app.config['ADMIN_PASSWORD']: session['admin_logged_in'] = True return jsonify({'success': True, 'message': 'Login successful'}), 200 return jsonify({'success': False, 'error': 'Invalid password'}), 401 @app.route('/api/admin/settings/update', methods=['POST']) @admin_required def update_settings(): try: data = request.get_json() action = data.get('action') if action == 'update_tables': total_tables = int(data.get('total_tables', 10)) seats_per_table = int(data.get('seats_per_table', 10)) # 更新 Google Sheets sync_settings_to_sheets('updateSettings', { 'total_tables': total_tables, 'seats_per_table': seats_per_table }) # 更新資料庫中的桌次 current_tables = Table.query.order_by(Table.id).all() current_count = len(current_tables) if total_tables > current_count: # 需要添加新桌次 for i in range(current_count + 1, total_tables + 1): new_table = Table(id=i, capacity=seats_per_table) db.session.add(new_table) elif total_tables < current_count: # 需要刪除多餘的桌次 # 檢查要刪除的桌次是否有參與者 for table in current_tables[total_tables:]: if len(table.participants) > 0: # 只刪除沒有參與者的桌次 return jsonify({ 'error': f'無法刪除第 {table.id} 桌,因為還有參與者在該桌' }), 400 db.session.delete(table) # 更新所有桌次的容量 for table in Table.query.all(): table.capacity = seats_per_table db.session.commit() return jsonify({ 'message': '設定已更新', 'settings': { 'total_tables': total_tables, 'seats_per_table': seats_per_table } }) elif action == 'update_table_name': table_id = data.get('table_id') name = data.get('name', '') table = Table.query.get(table_id) if not table: return jsonify({'error': '找不到該桌次'}), 404 table.name = name db.session.commit() # 同步到 Google Sheets sync_settings_to_sheets('update_table_name', { 'table_id': table_id, 'name': name }) return jsonify({ 'message': '桌次名稱已更新', 'table': { 'id': table.id, 'name': table.name } }) return jsonify({'error': '未知的操作'}), 400 except Exception as e: print(f"更新設定時出錯: {str(e)}") db.session.rollback() return jsonify({'error': str(e)}), 500 @app.route('/api/admin/settings/backup', methods=['POST']) @admin_required def backup_settings(): try: # 獲取當前所有桌子設定 tables = Table.query.all() total_tables = len(tables) seats_per_table = tables[0].capacity if tables else 0 # 同步設定到 Sheets sync_settings_to_sheets('saveSettings', { 'totalTables': total_tables, 'seatsPerTable': seats_per_table }) # 備份參與者資料 participants = Participant.query.all() sync_settings_to_sheets('backupParticipants', { 'participants': [{ 'id': p.id, 'nickname': p.nickname, 'email': p.email, 'fb_link': p.fb_link, 'introduction': p.introduction, 'table_id': p.table_id, 'seat_number': p.seat_number, 'is_table_leader': p.is_table_leader, 'created_at': p.created_at.strftime('%Y-%m-%d %H:%M:%S'), 'has_paid': p.has_paid, 'note': p.note } for p in participants] }) return jsonify({'message': '備份成功'}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/admin/settings/restore', methods=['POST']) @admin_required def restore_data(): try: # 從 Google Apps Script 獲取數據 print("正在從 Google Sheets 同步資料...") response = requests.get(app.config['SETTINGS_SCRIPT_URL']) print("Google Sheets 回應狀態碼:", response.status_code) try: data = response.json() except ValueError as e: print("JSON 解析錯誤:", str(e)) print("原始回應內容:", response.text) return jsonify({'error': '從 Google Sheets 獲取資料失敗:無效的 JSON 格式'}), 500 if not data.get('success'): error_msg = data.get('error', '從 Google Sheets 恢復資料失敗') print("Google Sheets 返回錯誤:", error_msg) return jsonify({'error': error_msg}), 400 # 更新桌次設定 settings = data.get('settings', {}) print(f"從 Google Sheets 讀取設定:總桌數={settings.get('total_tables')}, 每桌人數={settings.get('seats_per_table')}") # 更新桌次名稱 tables_data = data.get('tables', []) for table_data in tables_data: table = Table.query.get(table_data.get('id')) if table and 'name' in table_data: table.name = table_data['name'] db.session.commit() print("桌次設定更新完成") # 清空現有的參與者資料 Participant.query.delete() # 恢復參與者資料 participants_data = data.get('participants', []) print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料") for participant_data in participants_data: # 處理 ISO 格式的時間 created_at_str = participant_data['created_at'].replace('T', ' ').replace('.000Z', '') created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S') try: participant = Participant( nickname=participant_data['nickname'], email=participant_data['email'], fb_link=participant_data.get('fb_link', ''), introduction=participant_data.get('introduction', ''), table_id=int(participant_data['table_id']), seat_number=int(participant_data['seat_number']), is_table_leader=participant_data.get('is_table_leader') == True or participant_data.get('is_table_leader') == 'TRUE', created_at=created_at, has_paid=participant_data.get('has_paid') == True or participant_data.get('has_paid') == 'TRUE', note=participant_data.get('note', '') ) db.session.add(participant) print(f"已更新參與者: {participant.nickname}") except (KeyError, ValueError) as e: print(f"處理參與者資料時出錯: {str(e)}") print(f"問題資料: {participant_data}") continue db.session.commit() print("參與者資料更新完成") return jsonify({'message': '資料已成功恢復'}) except Exception as e: db.session.rollback() print('恢復資料時出錯:', str(e)) return jsonify({'error': str(e)}), 500 @app.route('/api/admin/settings', methods=['GET']) @admin_required def get_settings(): try: # 從 Google Sheets 獲取最新設定 response = requests.get(app.config['SETTINGS_SCRIPT_URL']) if response.status_code == 200: data = response.json() if data.get('success'): settings = data.get('settings', {}) return jsonify({ 'total_tables': settings.get('total_tables', 10), 'seats_per_table': settings.get('seats_per_table', 10) }) # 如果無法從 Google Sheets 獲取,使用資料庫中的設定 total_tables = Table.query.count() first_table = Table.query.first() seats_per_table = first_table.capacity if first_table else 10 return jsonify({ 'total_tables': total_tables, 'seats_per_table': seats_per_table }) except Exception as e: print(f"獲取設定時出錯: {str(e)}") return jsonify({'error': str(e)}), 500 @app.route('/api/admin/participants', methods=['GET']) @admin_required def get_all_participants(): try: participants = Participant.query.all() tables = Table.query.all() return jsonify({ 'participants': [{ 'id': p.id, 'nickname': p.nickname, 'email': p.email, 'fb_link': p.fb_link, 'introduction': p.introduction, 'table_id': p.table_id, 'seat_number': p.seat_number, 'is_table_leader': p.is_table_leader, 'created_at': p.created_at.strftime('%Y-%m-%d %H:%M:%S'), 'has_paid': p.has_paid, 'note': p.note } for p in participants], 'tables': [{ 'id': t.id, 'name': t.name, 'capacity': t.capacity, 'current_seats': len(Participant.query.filter_by(table_id=t.id).all()) } for t in tables] }) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/admin/participant//move', methods=['POST']) @admin_required def move_participant(participant_id): try: data = request.get_json() new_table_id = data.get('new_table_id') if not new_table_id: return jsonify({'error': '請提供新的桌號'}), 400 participant = Participant.query.get(participant_id) if not participant: return jsonify({'error': '找不到該參與者'}), 404 new_table = Table.query.get(new_table_id) if not new_table: return jsonify({'error': '找不到該桌子'}), 404 # 檢查新桌子是否已滿 current_seats = len(Participant.query.filter_by(table_id=new_table_id).all()) if current_seats >= new_table.capacity: return jsonify({'error': '該桌已滿'}), 400 # 更新座位號碼 participant.table_id = new_table_id participant.seat_number = current_seats + 1 db.session.commit() # 同步到 Google Sheets try: _backup_data_internal() print("成功備份參與者資料到 Google Sheets") except Exception as e: print(f"同步到 Google Sheets 時出錯: {str(e)}") # 不中斷操作,只記錄錯誤 return jsonify({ 'message': '成功移動座位', 'participant': { 'id': participant.id, 'nickname': participant.nickname, 'table_id': participant.table_id, 'seat_number': participant.seat_number } }) except Exception as e: db.session.rollback() return jsonify({'error': str(e)}), 500 @app.route('/api/admin/participants/', methods=['DELETE']) @admin_required def delete_participant(participant_id): try: participant = Participant.query.get(participant_id) if participant: db.session.delete(participant) db.session.commit() # 同步到 Google Sheets try: _backup_data_internal() print("成功備份參與者資料到 Google Sheets") except Exception as e: print(f"同步到 Google Sheets 時出錯: {str(e)}") # 不中斷操作,只記錄錯誤 return jsonify({'message': 'Participant deleted successfully'}) return jsonify({'error': 'Participant not found'}), 404 except Exception as e: db.session.rollback() return jsonify({'error': str(e)}), 400 @app.route('/api/tables', methods=['GET']) def get_tables(): try: print("正在獲取桌次資料...") # 如果是從管理後台呼叫,先從 Google Sheets 同步資料 if request.referrer and '/admin' in request.referrer: print("從管理後台呼叫,同步 Google Sheets 資料...") try: response = requests.get(app.config['SETTINGS_SCRIPT_URL']) if response.status_code == 200: data = response.json() if data.get('success'): # 更新桌次名稱 tables_data = data.get('tables', []) table_names = {table['id']: table['name'] for table in tables_data} for table in Table.query.all(): if table.id in table_names: table.name = table_names[table.id] # 更新參與者資料 participants_data = data.get('participants', []) for p_data in participants_data: participant = Participant.query.get(p_data['id']) if participant: participant.nickname = p_data['nickname'] participant.email = p_data['email'] participant.fb_link = p_data.get('fb_link', '') participant.introduction = p_data.get('introduction', '') participant.table_id = int(p_data['table_id']) participant.seat_number = int(p_data['seat_number']) participant.is_table_leader = bool(p_data.get('is_table_leader', False)) participant.has_paid = bool(p_data.get('has_paid', False)) participant.note = p_data.get('note', '') db.session.commit() print("資料已從 Google Sheets 更新") else: print("從 Google Sheets 獲取資料失敗") else: print(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}") except Exception as e: print(f"同步 Google Sheets 資料時出錯: {str(e)}") # 從資料庫獲取桌次資料 tables = Table.query.order_by(Table.id).all() print(f"找到 {len(tables)} 張桌子") # 轉換成 JSON 格式 result = { 'tables': [table.to_dict() for table in tables] } print("桌次資料獲取成功") return jsonify(result) except Exception as e: print(f"獲取桌次資料時出錯: {str(e)}") return jsonify({'error': str(e)}), 500 @app.route('/api/register', methods=['POST']) def register(): try: data = request.get_json() # 驗證必填欄位 if not all(key in data for key in ['nickname', 'email', 'table_id']): return jsonify({'error': '缺少必要欄位'}), 400 # 檢查桌子是否存在且有空位 table = Table.query.get(data['table_id']) if not table: return jsonify({'error': '找不到該桌子'}), 404 current_seats = len(Participant.query.filter_by(table_id=data['table_id']).all()) if current_seats >= table.capacity: return jsonify({'error': '該桌已滿'}), 400 # 創建新參與者 participant = Participant( nickname=data['nickname'], email=data['email'], fb_link=data.get('fb_link', ''), introduction=data.get('introduction', ''), table_id=data['table_id'], seat_number=current_seats + 1 ) db.session.add(participant) db.session.commit() # 同步到 Google Sheets try: _backup_data_internal() print("成功備份參與者資料到 Google Sheets") except Exception as e: print(f"同步到 Google Sheets 時出錯: {str(e)}") # 不中斷操作,只記錄錯誤 return jsonify({ 'message': '報名成功', 'participant': { 'id': participant.id, 'nickname': participant.nickname, 'table_id': participant.table_id, 'seat_number': participant.seat_number } }) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/participants/export', methods=['GET']) def export_participants(): try: participants = Participant.query.all() export_data = [] for participant in participants: local_time = participant.created_at + timedelta(hours=8) # 轉換為台灣時間 export_data.append({ 'nickname': participant.nickname, 'email': participant.email, 'fb_link': participant.fb_link, 'introduction': participant.introduction, 'table_id': participant.table_id, 'seat_number': participant.seat_number, 'is_table_leader': '是' if participant.is_table_leader else '否', 'registration_time': local_time.strftime('%Y-%m-%d %H:%M:%S'), 'has_paid': '是' if participant.has_paid else '否', 'note': participant.note or '' }) return jsonify(export_data) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/admin/participant//toggle-leader', methods=['POST']) @admin_required def toggle_leader(participant_id): try: participant = Participant.query.get(participant_id) if not participant: return jsonify({'error': '找不到該參與者'}), 404 # 如果要設為桌長,先確認該桌是否已有桌長 if not participant.is_table_leader: existing_leader = Participant.query.filter_by( table_id=participant.table_id, is_table_leader=True ).first() if existing_leader: return jsonify({ 'error': f'該桌已有桌長:{existing_leader.nickname}' }), 400 # 切換桌長狀態 participant.is_table_leader = not participant.is_table_leader db.session.commit() # 同步到 Google Sheets try: _backup_data_internal() except Exception as e: print(f"同步到 Google Sheets 時出錯: {str(e)}") # 不中斷操作,只記錄錯誤 return jsonify({ 'message': f'已{participant.is_table_leader and "設為" or "取消"}桌長', 'participant': participant.to_dict() }) except Exception as e: print("更新桌長狀態時出錯:", str(e)) return jsonify({'error': str(e)}), 500 @app.route('/api/admin/participant//payment', methods=['POST']) @admin_required def toggle_payment(participant_id): try: participant = Participant.query.get(participant_id) if not participant: return jsonify({'error': '找不到該參與者'}), 404 participant.has_paid = not participant.has_paid db.session.commit() # 同步到 Google Sheets try: _backup_data_internal() except Exception as e: print(f"同步到 Google Sheets 時出錯: {str(e)}") # 不中斷操作,只記錄錯誤 return jsonify({ 'message': f'已更新付款狀態為{"已" if participant.has_paid else "未"}付款', 'participant': participant.to_dict() }) except Exception as e: print("更新付款狀態時出錯:", str(e)) return jsonify({'error': str(e)}), 500 @app.route('/api/admin/participant//note', methods=['POST']) @admin_required def update_participant_note(participant_id): try: data = request.get_json() note = data.get('note', '') participant = Participant.query.get(participant_id) if not participant: return jsonify({'error': '找不到該參與者'}), 404 participant.note = note db.session.commit() # 同步到 Google Sheets try: _backup_data_internal() except Exception as e: print(f"同步到 Google Sheets 時出錯: {str(e)}") # 不中斷操作,只記錄錯誤 return jsonify({ 'message': '備註已更新', 'participant': participant.to_dict() }) except Exception as e: print("更新備註時出錯:", str(e)) return jsonify({'error': str(e)}), 500 if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)