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

更新Readme

Browse files
.history/README_20250118170747.md ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: 蛇來蛇去座位表
3
+ emoji: 📈
4
+ colorFrom: blue
5
+ colorTo: yellow
6
+ sdk: docker
7
+ pinned: false
8
+ license: apache-2.0
9
+ app_port: 7860
10
+ persistent_dir: ["/data"]
11
+ ---
12
+
13
+ # 蛇來蛇去座位表 - 活動座位選擇系統
14
+
15
+ 這是一個專為活動設計的座位選擇系統,讓參與者可以自由選擇想要坐的桌次。系統支援多桌次管理、桌長設定、付款狀態追蹤等功能。
16
+
17
+ ## 功能特色
18
+
19
+ ### 參與者功能
20
+ - 即時查看各桌剩餘座位
21
+ - 選擇想要入座的桌次
22
+ - 填寫個人資料(暱稱、Email、FB連結、自我介紹)
23
+ - 點擊參與者名字可查看詳細資訊
24
+
25
+ ### 管理者功能
26
+ - 管理者後台密碼保護
27
+ - 查看所有參與者資訊
28
+ - 設定/取消桌長身份
29
+ - 標記付款狀態
30
+ - 新增/編輯參與者備註
31
+ - 匯出參與者資料
32
+ - 備份/還原資料庫
33
+ - 與 Google Sheets 同步
34
+
35
+ ## 技術架構
36
+
37
+ ### 前端
38
+ - HTML5/CSS3
39
+ - Bootstrap 5.1.3
40
+ - SweetAlert2 (彈窗提示)
41
+ - Bootstrap Icons
42
+
43
+ ### 後端
44
+ - Python Flask
45
+ - SQLite 資料庫
46
+ - Flask-SQLAlchemy
47
+ - Google Apps Script (資料同步)
48
+
49
+ ## 系統架構圖
50
+
51
+ ```mermaid
52
+ graph TB
53
+ subgraph Frontend
54
+ A[首頁 index.html] --> B[管理者登入 admin_login.html]
55
+ B --> C[管理面板 admin.html]
56
+ end
57
+
58
+ subgraph Backend
59
+ D[Flask App] --> E[SQLite 資料庫]
60
+ D --> F[Google Apps Script]
61
+ end
62
+
63
+ subgraph 使用者流程
64
+ G[瀏覽座位] --> H[選擇座位]
65
+ H --> I[填寫資料]
66
+ I --> J[完成報名]
67
+ end
68
+
69
+ subgraph 管理者流程
70
+ K[登入驗證] --> L[查看報名]
71
+ L --> M[管理座位]
72
+ M --> N[同步資料]
73
+ end
74
+
75
+ A --> D
76
+ C --> D
77
+ D --> F
78
+ F --> O[Google Sheets]
79
+ ```
80
+
81
+ ## 主要功能流程
82
+
83
+ 1. **一般使用者流程**
84
+ - 瀏覽活動座位表
85
+ - 選擇想要的座位
86
+ - 填寫個人資料(暱稱、Email、FB連結、自我介紹)
87
+ - 完成報名
88
+
89
+ 2. **管理者流程**
90
+ - 登入管理面板
91
+ - 查看所有報名資料
92
+ - 管理座位分配
93
+ - 與 Google Sheets 同步資料
94
+
95
+ 3. **資料同步流程**
96
+ - 後端 Flask 應用程式處理請求
97
+ - 透過 Google Apps Script 進行資料同步
98
+ - 資料存儲於 SQLite 資料庫和 Google Sheets
99
+
100
+ ## 部署資訊
101
+
102
+ 本系統部署在 Hugging Face Spaces 平台,使用持久化存儲來保存資料。
103
+
104
+ ### 環境變數設定
105
+ - `ADMIN_PASSWORD`: 管理者密碼
106
+ - `SETTINGS_SCRIPT_URL`: Google Apps Script 網址(用於同步設定)
107
+
108
+ ## 本地開發
109
+
110
+ 1. 安裝依賴:
111
+ ```bash
112
+ pip install -r requirements.txt
113
+ ```
114
+
115
+ 2. 設定環境變數:
116
+ ```bash
117
+ export ADMIN_PASSWORD=your_password
118
+ export SETTINGS_SCRIPT_URL=your_script_url
119
+ ```
120
+
121
+ 3. 啟動應用:
122
+ ```bash
123
+ python app.py
124
+ ```
125
+
126
+ 應用將在 http://localhost:7860 運行
127
+
128
+ ## 資料庫結構
129
+
130
+ ### Table 資料表
131
+ - id: 桌次 ID
132
+ - name: 桌次名稱
133
+ - capacity: 座位容量
134
+ - participants: 關聯到 Participant 資料表
135
+
136
+ ### Participant 資料表
137
+ - id: 參與者 ID
138
+ - nickname: 暱稱
139
+ - email: 電子郵件
140
+ - fb_link: Facebook 連結
141
+ - introduction: 自我介紹
142
+ - table_id: 所屬桌次
143
+ - seat_number: 座位號碼
144
+ - is_table_leader: 是否為桌長
145
+ - created_at: 建立時間
146
+ - has_paid: 付款狀態
147
+ - note: 管理者備註
148
+
149
+ ## 資料備份
150
+
151
+ 系統提供兩種備份機制:
152
+ 1. 資料庫備份:完整備份所有資料
153
+ 2. Google Sheets 同步:即時同步重要設定
154
+
155
+ ## 注意事項
156
+
157
+ 1. 請定期備份資料庫
158
+ 2. 管理者密碼請妥善保管
159
+ 3. 建議定期檢查 Google Sheets 同步狀態
160
+
161
+ ## 授權資訊
162
+
163
+ 本專案採用 MIT 授權條款。
164
+
165
+ ## 開發 Debug 記錄
166
+
167
+ ### 前端顯示
168
+
169
+ 1. **圓形桌位顯示溢出**
170
+ - 問題:參與者超過 5 人時,名字會溢出圓形區域
171
+ - 解決:改用長方形設計,並根據參與者數量自動調整大小
172
+
173
+ 2. **參與者資訊顯示優化**
174
+ - 問題:自我介紹和備註內容過長時影響版面
175
+ - 解決:實作文字截斷和彈出式詳細資訊視窗
176
+
177
+ ### Google Sheets 同步
178
+
179
+ 1. **跨域請求問題**
180
+ - 問題:無法直接從前端呼叫 Google Apps Script
181
+ - 解決:透過後端 API 轉發請求,並處理回應
182
+
183
+ ### 安全性問題
184
+
185
+ 1. **管理者密碼保護**
186
+ - 問題:需要保護管理者頁面的存取
187
+ - 解決:使用環境變數和 session 機制,實作管理者登入功能
188
+
189
+ ### 使用者體驗
190
+
191
+ 1. **座位選擇流程**
192
+ - 問題:原本點擊整個圓桌來選擇不夠直覺
193
+ - 解決:新增獨立的選擇按鈕,並提供視覺回饋
194
+
195
+ 2. **錯誤處理優化**
196
+ - 問題:系統錯誤訊息不夠友善
197
+ - 解決:使用 SweetAlert2 提供更好的錯誤提示
198
+
199
+ ---
200
+ Hosted on 🤗 Hugging Face Spaces
.history/app_20250118170635.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',
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=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:
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()
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()
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()
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()
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()
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()
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)
.history/sync_settings_20250118170635.gs ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function doGet() {
2
+ var sheet = SpreadsheetApp.getActiveSpreadsheet();
3
+ var participantsSheet = sheet.getSheetByName('Participants');
4
+ var settingsSheet = sheet.getSheetByName('Settings');
5
+ var tablesSheet = sheet.getSheetByName('Tables'); // 新增桌次表格
6
+
7
+ // 獲取設定
8
+ var settings = {
9
+ total_tables: 10, // 預設值
10
+ seats_per_table: 10 // 預設值
11
+ };
12
+
13
+ if (settingsSheet) {
14
+ var settingsRange = settingsSheet.getDataRange();
15
+ var settingsValues = settingsRange.getValues();
16
+
17
+ // 從第二行開始尋找設定值
18
+ for (var i = 1; i < settingsValues.length; i++) {
19
+ var row = settingsValues[i];
20
+ if (row[0] === '總桌數') {
21
+ settings.total_tables = parseInt(row[1]) || 10;
22
+ }
23
+ if (row[0] === '每桌人數') {
24
+ settings.seats_per_table = parseInt(row[1]) || 10;
25
+ }
26
+ }
27
+ }
28
+
29
+ // 獲取桌次資料
30
+ var tables = [];
31
+ if (tablesSheet) {
32
+ var tablesData = tablesSheet.getDataRange().getValues();
33
+ Logger.log("Tables sheet data: " + JSON.stringify(tablesData));
34
+
35
+ if (tablesData.length > 0) {
36
+ var headers = tablesData[0];
37
+ var idIndex = headers.indexOf('Table ID');
38
+ var nameIndex = headers.indexOf('Table Name');
39
+
40
+ Logger.log("Table headers found - ID index: " + idIndex + ", Name index: " + nameIndex);
41
+
42
+ if (idIndex !== -1 && nameIndex !== -1) {
43
+ for (var i = 1; i < tablesData.length; i++) {
44
+ var row = tablesData[i];
45
+ var tableId = row[idIndex];
46
+ var tableName = row[nameIndex];
47
+
48
+ if (tableId) { // 只處理有 ID 的行
49
+ tableId = parseInt(tableId);
50
+ tableName = tableName || '';
51
+
52
+ Logger.log("Found table: ID=" + tableId + ", Name=" + tableName);
53
+
54
+ tables.push({
55
+ id: tableId,
56
+ name: tableName
57
+ });
58
+ }
59
+ }
60
+ } else {
61
+ Logger.log("Error: Table ID or Table Name column not found");
62
+ }
63
+ }
64
+ }
65
+ Logger.log("Final tables data: " + JSON.stringify(tables));
66
+
67
+ // 獲取參與者資料
68
+ var participants = [];
69
+ if (participantsSheet) {
70
+ var data = participantsSheet.getDataRange().getValues();
71
+ var headers = data[0];
72
+
73
+ for (var i = 1; i < data.length; i++) {
74
+ var row = data[i];
75
+ if (row[0]) { // 只處理有 ID 的行
76
+ var participant = {
77
+ id: row[0],
78
+ nickname: row[1],
79
+ email: row[2],
80
+ fb_link: row[3] || '',
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);
90
+ }
91
+ }
92
+ }
93
+
94
+ var response = {
95
+ success: true,
96
+ participants: participants,
97
+ settings: settings,
98
+ tables: tables
99
+ };
100
+ Logger.log("Final response: " + JSON.stringify(response));
101
+
102
+ return ContentService.createTextOutput(JSON.stringify(response))
103
+ .setMimeType(ContentService.MimeType.JSON);
104
+ }
105
+
106
+ function doPost(e) {
107
+ if (!e || !e.postData || !e.postData.contents) {
108
+ return ContentService.createTextOutput(JSON.stringify({
109
+ success: false,
110
+ error: 'Invalid request format'
111
+ })).setMimeType(ContentService.MimeType.JSON);
112
+ }
113
+
114
+ var sheet = SpreadsheetApp.getActiveSpreadsheet();
115
+
116
+ try {
117
+ var data = JSON.parse(e.postData.contents);
118
+ var action = data.action;
119
+
120
+ Logger.log("Received action: " + action);
121
+ Logger.log("Received data: " + JSON.stringify(data));
122
+
123
+ if (action === 'backupParticipants') {
124
+ return backupParticipants(sheet, data.participants);
125
+ } else if (action === 'update_tables' || action === 'updateSettings') {
126
+ var settings = action === 'update_tables' ? data : data.settings;
127
+ return updateSettings(sheet, settings);
128
+ } else if (action === 'update_table_name') {
129
+ var tableId = data.table_id;
130
+ var name = data.name;
131
+
132
+ // 更新桌次名稱
133
+ var tablesSheet = sheet.getSheetByName('Tables');
134
+ if (!tablesSheet) {
135
+ tablesSheet = sheet.insertSheet('Tables');
136
+ tablesSheet.getRange(1, 1, 1, 2).setValues([['ID', '名稱']]);
137
+ }
138
+
139
+ // 尋找或創建桌次行
140
+ var tableRow = findTableRow(tableId, tablesSheet);
141
+ if (tableRow === 0) {
142
+ // 如果找不到桌次,在最後一行添加
143
+ tableRow = tablesSheet.getLastRow() + 1;
144
+ tablesSheet.getRange(tableRow, 1, 1, 2).setValues([[tableId, name]]);
145
+ } else {
146
+ // 更新現有桌次名稱
147
+ tablesSheet.getRange(tableRow, 2).setValue(name);
148
+ }
149
+
150
+ return ContentService.createTextOutput(JSON.stringify({
151
+ success: true,
152
+ message: '桌次名稱已更新'
153
+ })).setMimeType(ContentService.MimeType.JSON);
154
+ }
155
+
156
+ return ContentService.createTextOutput(JSON.stringify({
157
+ success: false,
158
+ error: 'Unknown action'
159
+ })).setMimeType(ContentService.MimeType.JSON);
160
+
161
+ } catch (error) {
162
+ Logger.log("Error: " + error.toString());
163
+ return ContentService.createTextOutput(JSON.stringify({
164
+ success: false,
165
+ error: error.toString()
166
+ })).setMimeType(ContentService.MimeType.JSON);
167
+ }
168
+ }
169
+
170
+ // 尋找桌次在表格中的行數
171
+ function findTableRow(tableId, sheet) {
172
+ var data = sheet.getDataRange().getValues();
173
+ for (var i = 1; i < data.length; i++) {
174
+ if (data[i][0] == tableId) {
175
+ return i + 1; // 加 1 是因為 getValues() 從 0 開始,但 sheet 從 1 開始
176
+ }
177
+ }
178
+ return 0; // 沒找到
179
+ }
180
+
181
+ function backupParticipants(sheet, participants) {
182
+ try {
183
+ var participantsSheet = sheet.getSheetByName('Participants');
184
+ if (!participantsSheet) {
185
+ participantsSheet = sheet.insertSheet('Participants');
186
+ }
187
+
188
+ // 設置表頭
189
+ var headers = [
190
+ 'ID', '暱稱', 'Email', 'FB連結', '自我介紹',
191
+ '桌次', '座位號', '是否桌長', '報名時間', '是否付款', '備註'
192
+ ];
193
+ participantsSheet.getRange(1, 1, 1, headers.length).setValues([headers]);
194
+
195
+ // 清空舊資料(保留表頭)
196
+ var lastRow = participantsSheet.getLastRow();
197
+ if (lastRow > 1) {
198
+ participantsSheet.getRange(2, 1, lastRow - 1, headers.length).clear();
199
+ }
200
+
201
+ // 寫入新資料
202
+ if (participants && participants.length > 0) {
203
+ var values = participants.map(function(p) {
204
+ return [
205
+ p.id,
206
+ p.nickname,
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
+ });
218
+
219
+ participantsSheet.getRange(2, 1, values.length, headers.length).setValues(values);
220
+ }
221
+
222
+ return ContentService.createTextOutput(JSON.stringify({
223
+ success: true,
224
+ message: '參與者資料已更新'
225
+ })).setMimeType(ContentService.MimeType.JSON);
226
+
227
+ } catch (error) {
228
+ Logger.log("Error in backupParticipants: " + error.toString());
229
+ return ContentService.createTextOutput(JSON.stringify({
230
+ success: false,
231
+ error: error.toString()
232
+ })).setMimeType(ContentService.MimeType.JSON);
233
+ }
234
+ }
235
+
236
+ function updateSettings(sheet, settings) {
237
+ try {
238
+ var settingsSheet = sheet.getSheetByName('Settings');
239
+ if (!settingsSheet) {
240
+ settingsSheet = sheet.insertSheet('Settings');
241
+ settingsSheet.getRange(1, 1, 1, 2).setValues([['設定項目', '值']]);
242
+ }
243
+
244
+ // 更新總桌數
245
+ if (settings.totalTables || settings.total_tables) {
246
+ var totalTables = settings.totalTables || settings.total_tables;
247
+ updateSettingValue(settingsSheet, '總桌數', totalTables);
248
+
249
+ // 同時更新 Tables 工作表
250
+ var tablesSheet = sheet.getSheetByName('Tables');
251
+ if (!tablesSheet) {
252
+ tablesSheet = sheet.insertSheet('Tables');
253
+ tablesSheet.getRange(1, 1, 1, 2).setValues([['ID', '名稱']]);
254
+ }
255
+
256
+ // 獲取當前所有桌次資料
257
+ var currentData = tablesSheet.getDataRange().getValues();
258
+ var currentTables = {};
259
+ for (var i = 1; i < currentData.length; i++) {
260
+ if (currentData[i][0]) {
261
+ currentTables[currentData[i][0]] = currentData[i][1] || '';
262
+ }
263
+ }
264
+
265
+ // 準備新的桌次資料
266
+ var newData = [['ID', '名稱']]; // 標題行
267
+ for (var i = 1; i <= totalTables; i++) {
268
+ newData.push([i, currentTables[i] || '']); // 保留現有的桌次名稱
269
+ }
270
+
271
+ // 清除現有資料並寫入新資料
272
+ tablesSheet.clear();
273
+ tablesSheet.getRange(1, 1, newData.length, 2).setValues(newData);
274
+ }
275
+
276
+ // 更新每桌人數
277
+ if (settings.seatsPerTable || settings.seats_per_table) {
278
+ var seatsPerTable = settings.seatsPerTable || settings.seats_per_table;
279
+ updateSettingValue(settingsSheet, '每桌人數', seatsPerTable);
280
+ }
281
+
282
+ return ContentService.createTextOutput(JSON.stringify({
283
+ success: true,
284
+ message: '設定已更新'
285
+ })).setMimeType(ContentService.MimeType.JSON);
286
+
287
+ } catch (error) {
288
+ Logger.log("Error in updateSettings: " + error.toString());
289
+ return ContentService.createTextOutput(JSON.stringify({
290
+ success: false,
291
+ error: error.toString()
292
+ })).setMimeType(ContentService.MimeType.JSON);
293
+ }
294
+ }
295
+
296
+ function updateSettingValue(sheet, key, value) {
297
+ var data = sheet.getDataRange().getValues();
298
+ var rowIndex = -1;
299
+
300
+ // 尋找設定項目
301
+ for (var i = 1; i < data.length; i++) {
302
+ if (data[i][0] === key) {
303
+ rowIndex = i + 1;
304
+ break;
305
+ }
306
+ }
307
+
308
+ // 如果找不到,就新增一行
309
+ if (rowIndex === -1) {
310
+ rowIndex = sheet.getLastRow() + 1;
311
+ }
312
+
313
+ // 更新值
314
+ sheet.getRange(rowIndex, 1, 1, 2).setValues([[key, value]]);
315
+ }
.history/sync_settings_20250118170656.gs ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function doGet() {
2
+ var sheet = SpreadsheetApp.getActiveSpreadsheet();
3
+ var participantsSheet = sheet.getSheetByName('Participants');
4
+ var settingsSheet = sheet.getSheetByName('Settings');
5
+ var tablesSheet = sheet.getSheetByName('Tables'); // 新增桌次表格
6
+
7
+ // 獲取設定
8
+ var settings = {
9
+ total_tables: 10, // 預設值
10
+ seats_per_table: 10 // 預設值
11
+ };
12
+
13
+ if (settingsSheet) {
14
+ var settingsRange = settingsSheet.getDataRange();
15
+ var settingsValues = settingsRange.getValues();
16
+
17
+ // 從第二行開始尋找設定值
18
+ for (var i = 1; i < settingsValues.length; i++) {
19
+ var row = settingsValues[i];
20
+ if (row[0] === '總桌數') {
21
+ settings.total_tables = parseInt(row[1]) || 10;
22
+ }
23
+ if (row[0] === '每桌人數') {
24
+ settings.seats_per_table = parseInt(row[1]) || 10;
25
+ }
26
+ }
27
+ }
28
+
29
+ // 獲取桌次資料
30
+ var tables = [];
31
+ if (tablesSheet) {
32
+ var tablesData = tablesSheet.getDataRange().getValues();
33
+ Logger.log("Tables sheet data: " + JSON.stringify(tablesData));
34
+
35
+ if (tablesData.length > 0) {
36
+ var headers = tablesData[0];
37
+ var idIndex = headers.indexOf('Table ID');
38
+ var nameIndex = headers.indexOf('Table Name');
39
+
40
+ Logger.log("Table headers found - ID index: " + idIndex + ", Name index: " + nameIndex);
41
+
42
+ if (idIndex !== -1 && nameIndex !== -1) {
43
+ for (var i = 1; i < tablesData.length; i++) {
44
+ var row = tablesData[i];
45
+ var tableId = row[idIndex];
46
+ var tableName = row[nameIndex];
47
+
48
+ if (tableId) { // 只處理有 ID 的行
49
+ tableId = parseInt(tableId);
50
+ tableName = tableName || '';
51
+
52
+ Logger.log("Found table: ID=" + tableId + ", Name=" + tableName);
53
+
54
+ tables.push({
55
+ id: tableId,
56
+ name: tableName
57
+ });
58
+ }
59
+ }
60
+ } else {
61
+ Logger.log("Error: Table ID or Table Name column not found");
62
+ }
63
+ }
64
+ }
65
+ Logger.log("Final tables data: " + JSON.stringify(tables));
66
+
67
+ // 獲取參與者資料
68
+ var participants = [];
69
+ if (participantsSheet) {
70
+ var data = participantsSheet.getDataRange().getValues();
71
+ var headers = data[0];
72
+
73
+ for (var i = 1; i < data.length; i++) {
74
+ var row = data[i];
75
+ if (row[0]) { // 只處理有 ID 的行
76
+ var participant = {
77
+ id: row[0],
78
+ nickname: row[1],
79
+ email: row[2],
80
+ fb_link: row[3] || '',
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);
90
+ }
91
+ }
92
+ }
93
+
94
+ var response = {
95
+ success: true,
96
+ participants: participants,
97
+ settings: settings,
98
+ tables: tables
99
+ };
100
+ Logger.log("Final response: " + JSON.stringify(response));
101
+
102
+ return ContentService.createTextOutput(JSON.stringify(response))
103
+ .setMimeType(ContentService.MimeType.JSON);
104
+ }
105
+
106
+ function doPost(e) {
107
+ if (!e || !e.postData || !e.postData.contents) {
108
+ return ContentService.createTextOutput(JSON.stringify({
109
+ success: false,
110
+ error: 'Invalid request format'
111
+ })).setMimeType(ContentService.MimeType.JSON);
112
+ }
113
+
114
+ var sheet = SpreadsheetApp.getActiveSpreadsheet();
115
+
116
+ try {
117
+ var data = JSON.parse(e.postData.contents);
118
+ var action = data.action;
119
+
120
+ Logger.log("Received action: " + action);
121
+ Logger.log("Received data: " + JSON.stringify(data));
122
+
123
+ if (action === 'backupParticipants') {
124
+ return backupParticipants(sheet, data.participants);
125
+ } else if (action === 'update_tables' || action === 'updateSettings') {
126
+ var settings = action === 'update_tables' ? data : data.settings;
127
+ return updateSettings(sheet, settings);
128
+ } else if (action === 'update_table_name') {
129
+ var tableId = data.table_id;
130
+ var name = data.name;
131
+
132
+ // 更新桌次名稱
133
+ var tablesSheet = sheet.getSheetByName('Tables');
134
+ if (!tablesSheet) {
135
+ tablesSheet = sheet.insertSheet('Tables');
136
+ tablesSheet.getRange(1, 1, 1, 2).setValues([['ID', '名稱']]);
137
+ }
138
+
139
+ // 尋找或創建桌次行
140
+ var tableRow = findTableRow(tableId, tablesSheet);
141
+ if (tableRow === 0) {
142
+ // 如果找不到桌次,在最後一行添加
143
+ tableRow = tablesSheet.getLastRow() + 1;
144
+ tablesSheet.getRange(tableRow, 1, 1, 2).setValues([[tableId, name]]);
145
+ } else {
146
+ // 更新現有桌次名稱
147
+ tablesSheet.getRange(tableRow, 2).setValue(name);
148
+ }
149
+
150
+ return ContentService.createTextOutput(JSON.stringify({
151
+ success: true,
152
+ message: '桌次名稱已更新'
153
+ })).setMimeType(ContentService.MimeType.JSON);
154
+ }
155
+
156
+ return ContentService.createTextOutput(JSON.stringify({
157
+ success: false,
158
+ error: 'Unknown action'
159
+ })).setMimeType(ContentService.MimeType.JSON);
160
+
161
+ } catch (error) {
162
+ Logger.log("Error: " + error.toString());
163
+ return ContentService.createTextOutput(JSON.stringify({
164
+ success: false,
165
+ error: error.toString()
166
+ })).setMimeType(ContentService.MimeType.JSON);
167
+ }
168
+ }
169
+
170
+ // 尋找桌次在表格中的行數
171
+ function findTableRow(tableId, sheet) {
172
+ var data = sheet.getDataRange().getValues();
173
+ for (var i = 1; i < data.length; i++) {
174
+ if (data[i][0] == tableId) {
175
+ return i + 1; // 加 1 是因為 getValues() 從 0 開始,但 sheet 從 1 開始
176
+ }
177
+ }
178
+ return 0; // 沒找到
179
+ }
180
+
181
+ function backupParticipants(sheet, participants) {
182
+ try {
183
+ var participantsSheet = sheet.getSheetByName('Participants');
184
+ if (!participantsSheet) {
185
+ participantsSheet = sheet.insertSheet('Participants');
186
+ }
187
+
188
+ // 設置表頭
189
+ var headers = [
190
+ 'ID', '暱稱', 'Email', 'FB連結', '自我介紹',
191
+ '桌次', '座位號', '是否桌長', '報名時間', '是否付款', '備註'
192
+ ];
193
+ participantsSheet.getRange(1, 1, 1, headers.length).setValues([headers]);
194
+
195
+ // 清空舊資料(保留表頭)
196
+ var lastRow = participantsSheet.getLastRow();
197
+ if (lastRow > 1) {
198
+ participantsSheet.getRange(2, 1, lastRow - 1, headers.length).clear();
199
+ }
200
+
201
+ // 寫入新資料
202
+ if (participants && participants.length > 0) {
203
+ var values = participants.map(function(p) {
204
+ return [
205
+ p.id,
206
+ p.nickname,
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
+ });
218
+
219
+ participantsSheet.getRange(2, 1, values.length, headers.length).setValues(values);
220
+ }
221
+
222
+ return ContentService.createTextOutput(JSON.stringify({
223
+ success: true,
224
+ message: '參與者資料已更新'
225
+ })).setMimeType(ContentService.MimeType.JSON);
226
+
227
+ } catch (error) {
228
+ Logger.log("Error in backupParticipants: " + error.toString());
229
+ return ContentService.createTextOutput(JSON.stringify({
230
+ success: false,
231
+ error: error.toString()
232
+ })).setMimeType(ContentService.MimeType.JSON);
233
+ }
234
+ }
235
+
236
+ function updateSettings(sheet, settings) {
237
+ try {
238
+ var settingsSheet = sheet.getSheetByName('Settings');
239
+ if (!settingsSheet) {
240
+ settingsSheet = sheet.insertSheet('Settings');
241
+ settingsSheet.getRange(1, 1, 1, 2).setValues([['設定項目', '值']]);
242
+ }
243
+
244
+ // 更新總桌數
245
+ if (settings.totalTables || settings.total_tables) {
246
+ var totalTables = settings.totalTables || settings.total_tables;
247
+ updateSettingValue(settingsSheet, '總桌數', totalTables);
248
+
249
+ // 同時更新 Tables 工作表
250
+ var tablesSheet = sheet.getSheetByName('Tables');
251
+ if (!tablesSheet) {
252
+ tablesSheet = sheet.insertSheet('Tables');
253
+ tablesSheet.getRange(1, 1, 1, 2).setValues([['ID', '名稱']]);
254
+ }
255
+
256
+ // 獲取當前所有桌次資料
257
+ var currentData = tablesSheet.getDataRange().getValues();
258
+ var currentTables = {};
259
+ for (var i = 1; i < currentData.length; i++) {
260
+ if (currentData[i][0]) {
261
+ currentTables[currentData[i][0]] = currentData[i][1] || '';
262
+ }
263
+ }
264
+
265
+ // 準備新的桌次資料
266
+ var newData = [['ID', '名稱']]; // 標題行
267
+ for (var i = 1; i <= totalTables; i++) {
268
+ newData.push([i, currentTables[i] || '']); // 保留現有的桌次名稱
269
+ }
270
+
271
+ // 清除現有資料並寫入新資料
272
+ tablesSheet.clear();
273
+ tablesSheet.getRange(1, 1, newData.length, 2).setValues(newData);
274
+ }
275
+
276
+ // 更新每桌人數
277
+ if (settings.seatsPerTable || settings.seats_per_table) {
278
+ var seatsPerTable = settings.seatsPerTable || settings.seats_per_table;
279
+ updateSettingValue(settingsSheet, '每桌人數', seatsPerTable);
280
+ }
281
+
282
+ return ContentService.createTextOutput(JSON.stringify({
283
+ success: true,
284
+ message: '設定已更新'
285
+ })).setMimeType(ContentService.MimeType.JSON);
286
+
287
+ } catch (error) {
288
+ Logger.log("Error in updateSettings: " + error.toString());
289
+ return ContentService.createTextOutput(JSON.stringify({
290
+ success: false,
291
+ error: error.toString()
292
+ })).setMimeType(ContentService.MimeType.JSON);
293
+ }
294
+ }
295
+
296
+ function updateSettingValue(sheet, key, value) {
297
+ var data = sheet.getDataRange().getValues();
298
+ var rowIndex = -1;
299
+
300
+ // 尋找設定項目
301
+ for (var i = 1; i < data.length; i++) {
302
+ if (data[i][0] === key) {
303
+ rowIndex = i + 1;
304
+ break;
305
+ }
306
+ }
307
+
308
+ // 如果找不到,就新增一行
309
+ if (rowIndex === -1) {
310
+ rowIndex = sheet.getLastRow() + 1;
311
+ }
312
+
313
+ // 更新值
314
+ sheet.getRange(rowIndex, 1, 1, 2).setValues([[key, value]]);
315
+ }
README.md CHANGED
@@ -10,7 +10,7 @@ app_port: 7860
10
  persistent_dir: ["/data"]
11
  ---
12
 
13
- # Event Invite - 活動座位選擇系統
14
 
15
  這是一個專為活動設計的座位選擇系統,讓參與者可以自由選擇想要坐的桌次。系統支援多桌次管理、桌長設定、付款狀態追蹤等功能。
16
 
@@ -42,42 +42,132 @@ persistent_dir: ["/data"]
42
 
43
  ### 後端
44
  - Python Flask
45
- - SQLite 資料庫
46
  - Flask-SQLAlchemy
47
- - Google Apps Script (資料同步)
48
 
49
  ## 系統架構圖
50
 
51
  ```mermaid
52
  graph TB
53
- subgraph Frontend
54
- A[首頁 index.html] --> B[管理者登入 admin_login.html]
55
- B --> C[管理面板 admin.html]
 
 
 
 
 
 
 
 
 
56
  end
57
 
58
- subgraph Backend
59
- D[Flask App] --> E[SQLite 資料庫]
60
- D --> F[Google Apps Script]
 
 
61
  end
62
 
63
- subgraph 使用者流程
64
- G[瀏覽座位] --> H[選擇座位]
65
- H --> I[填寫資料]
66
- I --> J[完成報名]
67
  end
68
 
69
- subgraph 管理者流程
70
- K[登入驗證] --> L[查看報名]
71
- L --> M[管理座位]
72
- M --> N[同步資料]
 
73
  end
74
 
75
- A --> D
76
- C --> D
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  D --> F
78
- F --> O[Google Sheets]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  ```
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  ## 主要功能流程
82
 
83
  1. **一般使用者流程**
@@ -180,6 +270,10 @@ python app.py
180
  - 問題:無法直接從前端呼叫 Google Apps Script
181
  - 解決:透過後端 API 轉發請求,並處理回應
182
 
 
 
 
 
183
  ### 安全性問題
184
 
185
  1. **管理者密碼保護**
@@ -196,5 +290,18 @@ python app.py
196
  - 問題:系統錯誤訊息不夠友善
197
  - 解決:使用 SweetAlert2 提供更好的錯誤提示
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  ---
200
  Hosted on 🤗 Hugging Face Spaces
 
10
  persistent_dir: ["/data"]
11
  ---
12
 
13
+ # 蛇來蛇去座位表 - 活動座位選擇系統
14
 
15
  這是一個專為活動設計的座位選擇系統,讓參與者可以自由選擇想要坐的桌次。系統支援多桌次管理、桌長設定、付款狀態追蹤等功能。
16
 
 
42
 
43
  ### 後端
44
  - Python Flask
45
+ - SQLite (暫存資料庫)
46
  - Flask-SQLAlchemy
47
+ - Google Apps Script (主要資料存儲)
48
 
49
  ## 系統架構圖
50
 
51
  ```mermaid
52
  graph TB
53
+ %% 定義風格
54
+ classDef page fill:#f9f,stroke:#333,stroke-width:2px
55
+ classDef backend fill:#bbf,stroke:#333,stroke-width:2px
56
+ classDef database fill:#ddb,stroke:#333,stroke-width:2px
57
+ classDef api fill:#bfb,stroke:#333,stroke-width:2px
58
+
59
+ %% 前端部分
60
+ subgraph Frontend[前端介面]
61
+ A[首頁 index.html]
62
+ B[管理者登入 admin_login.html]
63
+ C[管理面板 admin.html]
64
+ UI[UI 元件<br>Bootstrap 5.1.3<br>SweetAlert2<br>Bootstrap Icons]
65
  end
66
 
67
+ %% 後端部分
68
+ subgraph Backend[後端服務]
69
+ D[Flask App]
70
+ Routes[路由處理<br>/admin<br>/toggle_payment<br>/update_note<br>/backup<br>/restore]
71
+ Auth[認證機制]
72
  end
73
 
74
+ %% 資料存儲
75
+ subgraph Storage[資料暫存]
76
+ E[SQLite 資料庫<br>臨時資料]
77
+ Tables[資料表<br>Participant<br>Table]
78
  end
79
 
80
+ %% Google整合
81
+ subgraph Google[主要資料存儲]
82
+ F[Google Apps Script]
83
+ O[Google Sheets<br>永久資料]
84
+ Sync[資料同步<br>布林值轉換<br>錯誤處理]
85
  end
86
 
87
+ %% 使用者流程
88
+ subgraph UserFlow[使用者流程]
89
+ G[瀏覽座位]
90
+ H[選擇座位]
91
+ I[填寫資料]
92
+ J[完成報名]
93
+ end
94
+
95
+ %% 管理者流程
96
+ subgraph AdminFlow[管理者流程]
97
+ K[登入驗證]
98
+ L[查看報名]
99
+ M[管理座位/付款]
100
+ N[同步資料]
101
+ end
102
+
103
+ %% 連接關係
104
+ A --> UI
105
+ B --> UI
106
+ C --> UI
107
+ UI --> D
108
+
109
+ D --> Routes
110
+ Routes --> Auth
111
+ Auth --> E
112
+
113
  D --> F
114
+ F --> Sync
115
+ Sync --> O
116
+
117
+ E --> Tables
118
+
119
+ G --> H
120
+ H --> I
121
+ I --> J
122
+ J --> D
123
+
124
+ K --> L
125
+ L --> M
126
+ M --> N
127
+ N --> D
128
+
129
+ %% 初始化流程
130
+ Init[系統啟動] --> LoadData[載入資料]
131
+ LoadData --> O
132
+ O --> E
133
+
134
+ %% 套用風格
135
+ class A,B,C page
136
+ class D,Routes,Auth backend
137
+ class E,Tables database
138
+ class F,O,Sync api
139
  ```
140
 
141
+ ## 資料存儲架構
142
+
143
+ ### Google Sheets(主要資料存儲)
144
+ - 永久保存所有資料
145
+ - 包含參與者資訊、桌次設定
146
+ - 通過 Google Apps Script 進行存取
147
+ - 支援手動編輯和備份
148
+
149
+ ### SQLite(暫存資料庫)
150
+ - 用於應用運行時的資料快取
151
+ - 每次應用啟動時從 Google Sheets 同步
152
+ - 提供高效的資料查詢和修改
153
+ - 應用重啟時會重置
154
+
155
+ ### 資料同步機制
156
+ 1. **應用啟動時**:
157
+ - 從 Google Sheets 讀取所有資料
158
+ - 初始化 SQLite 資料庫
159
+ - 建立資料表結構
160
+
161
+ 2. **資料修改時**:
162
+ - 先更新 SQLite 資料庫
163
+ - 立即同步到 Google Sheets
164
+ - 確保資料一致性
165
+
166
+ 3. **錯誤處理**:
167
+ - 同步失敗時提供錯誤提示
168
+ - 支援手動重新同步
169
+ - 記錄同步錯誤日誌
170
+
171
  ## 主要功能流程
172
 
173
  1. **一般使用者流程**
 
270
  - 問題:無法直接從前端呼叫 Google Apps Script
271
  - 解決:透過後端 API 轉發請求,並處理回應
272
 
273
+ 2. **布林值同步問題**
274
+ - 問題:付款狀態和桌長狀態在 Google Sheets 同步時出現異常
275
+ - 解決:統一使用 'TRUE'/'FALSE' 字串值在 Google Sheets 中儲存,並在應用程式中正確轉換為布林值
276
+
277
  ### 安全性問題
278
 
279
  1. **管理者密碼保護**
 
290
  - 問題:系統錯誤訊息不夠友善
291
  - 解決:使用 SweetAlert2 提供更好的錯誤提示
292
 
293
+ 3. **付款狀態更新問題**
294
+ - 問題:更新單一參與者的付款狀態時會影響到其他參與者
295
+ - 解決:修正資料同步邏輯,確保只更新指定參與者的狀態
296
+
297
+ ### 資料格式處理
298
+
299
+ 1. **布林值格式統一**
300
+ - 問題:布林值在不同系統間的格式不一致(Python布林值、Google Sheets字串、JavaScript布林值)
301
+ - 解決:
302
+ * Google Sheets:使用 'TRUE'/'FALSE' 字串
303
+ * Python:使用 `==True` 或 `=='TRUE'` 進行比較
304
+ * JavaScript:使用 `=== true` 或 `=== 'TRUE'` 進行比較
305
+
306
  ---
307
  Hosted on 🤗 Hugging Face Spaces