ichieh commited on
Commit
47dc8a7
·
1 Parent(s): 749655f

修改桌次名稱同步

Browse files
Files changed (1) hide show
  1. app.py +96 -26
app.py CHANGED
@@ -54,12 +54,18 @@ class Table(db.Model):
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):
@@ -121,19 +127,19 @@ def init_db():
121
  print("Google Sheets 返回錯誤:", error_msg)
122
  raise Exception(error_msg)
123
 
 
124
  settings = data.get('settings', {})
125
- tables_data = data.get('tables', [])
126
  total_tables = settings.get('total_tables', 10)
127
  seats_per_table = settings.get('seats_per_table', 10)
128
 
129
- print(f"從 Google Sheets 獲取到的資料:")
130
  print(f"- 總桌數: {total_tables}")
131
  print(f"- 每桌人數: {seats_per_table}")
132
- print(f"- 桌次資料: {tables_data}")
133
 
134
- # 建立桌次 ID 到名稱的對應
 
 
135
  table_names = {table['id']: table['name'] for table in tables_data}
136
- print(f"桌次名稱對應: {table_names}")
137
 
138
  # 檢查現有桌次
139
  existing_tables = {table.id: table for table in Table.query.all()}
@@ -143,12 +149,10 @@ def init_db():
143
  if i in existing_tables:
144
  table = existing_tables[i]
145
  table.capacity = seats_per_table
146
- # 更新名稱(如果在 Google Sheets 中有設定)
147
  if i in table_names:
148
  table.name = table_names[i]
149
  print(f"更新第 {i} 桌名稱為: {table_names[i]}")
150
  else:
151
- # 創建新桌次,使用 Google Sheets 中的名稱(如果有)
152
  table = Table(
153
  id=i,
154
  name=table_names.get(i, ''),
@@ -163,8 +167,42 @@ def init_db():
163
  db.session.delete(table)
164
  print(f"刪除第 {table_id} 桌")
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  db.session.commit()
167
- print(f"已更新桌次設定:總桌數={total_tables}, 每桌��數={seats_per_table}")
168
 
169
  except Exception as e:
170
  print(f"從 Google Sheets 獲取設定時出錯: {str(e)}")
@@ -693,30 +731,62 @@ def delete_participant(participant_id):
693
  db.session.rollback()
694
  return jsonify({'error': str(e)}), 400
695
 
696
- @app.route('/api/tables')
697
  def get_tables():
698
  try:
699
  print("正在獲取桌次資料...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
700
  tables = Table.query.order_by(Table.id).all()
701
  print(f"找到 {len(tables)} 張桌子")
702
 
 
703
  result = {
704
- 'tables': [{
705
- 'id': table.id,
706
- 'name': table.name or '', # 確保 name 不會是 None
707
- 'capacity': table.capacity,
708
- 'participants': [{
709
- 'id': p.id,
710
- 'nickname': p.nickname,
711
- 'fb_link': p.fb_link,
712
- 'introduction': p.introduction,
713
- 'is_table_leader': p.is_table_leader
714
- } for p in sorted(table.participants, key=lambda x: (not x.is_table_leader, x.created_at))]
715
- } for table in tables]
716
  }
717
 
718
  print("桌次資料獲取成功")
719
  return jsonify(result)
 
720
  except Exception as e:
721
  print(f"獲取桌次資料時出錯: {str(e)}")
722
  return jsonify({'error': str(e)}), 500
 
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):
 
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
+ tables_data = data.get('tables', [])
141
+ print(f"- 桌次資料: {tables_data}")
142
  table_names = {table['id']: table['name'] for table in tables_data}
 
143
 
144
  # 檢查現有桌次
145
  existing_tables = {table.id: table for table in Table.query.all()}
 
149
  if i in existing_tables:
150
  table = existing_tables[i]
151
  table.capacity = seats_per_table
 
152
  if i in table_names:
153
  table.name = table_names[i]
154
  print(f"更新第 {i} 桌名稱為: {table_names[i]}")
155
  else:
 
156
  table = Table(
157
  id=i,
158
  name=table_names.get(i, ''),
 
167
  db.session.delete(table)
168
  print(f"刪除第 {table_id} 桌")
169
 
170
+ # 清空現有的參與者資料
171
+ Participant.query.delete()
172
+ print("清空現有參與者資料")
173
+
174
+ # 恢復參與者資料
175
+ participants_data = data.get('participants', [])
176
+ print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料")
177
+
178
+ for p_data in participants_data:
179
+ # 處理 ISO 格式的時間
180
+ created_at_str = p_data['created_at'].replace('T', ' ').replace('.000Z', '')
181
+ created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
182
+
183
+ try:
184
+ participant = Participant(
185
+ id=p_data['id'],
186
+ nickname=p_data['nickname'],
187
+ email=p_data['email'],
188
+ fb_link=p_data.get('fb_link', ''),
189
+ introduction=p_data.get('introduction', ''),
190
+ table_id=int(p_data['table_id']),
191
+ seat_number=int(p_data['seat_number']),
192
+ is_table_leader=bool(p_data.get('is_table_leader', False)),
193
+ created_at=created_at,
194
+ has_paid=bool(p_data.get('has_paid', False)),
195
+ note=p_data.get('note', '')
196
+ )
197
+ db.session.add(participant)
198
+ print(f"已更新參與者: {participant.nickname}")
199
+ except Exception as e:
200
+ print(f"處理參與者資料時出錯: {str(e)}")
201
+ print(f"問題資料: {p_data}")
202
+ continue
203
+
204
  db.session.commit()
205
+ print("資料庫初始化完成")
206
 
207
  except Exception as e:
208
  print(f"從 Google Sheets 獲取設定時出錯: {str(e)}")
 
731
  db.session.rollback()
732
  return jsonify({'error': str(e)}), 400
733
 
734
+ @app.route('/api/tables', methods=['GET'])
735
  def get_tables():
736
  try:
737
  print("正在獲取桌次資料...")
738
+
739
+ # 如果是從管理後台呼叫,先從 Google Sheets 同步資料
740
+ if request.referrer and '/admin' in request.referrer:
741
+ print("從管理後台呼叫,同步 Google Sheets 資料...")
742
+ try:
743
+ response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
744
+ if response.status_code == 200:
745
+ data = response.json()
746
+ if data.get('success'):
747
+ # 更新桌次名稱
748
+ tables_data = data.get('tables', [])
749
+ table_names = {table['id']: table['name'] for table in tables_data}
750
+ for table in Table.query.all():
751
+ if table.id in table_names:
752
+ table.name = table_names[table.id]
753
+
754
+ # 更新參與者資料
755
+ participants_data = data.get('participants', [])
756
+ for p_data in participants_data:
757
+ participant = Participant.query.get(p_data['id'])
758
+ if participant:
759
+ participant.nickname = p_data['nickname']
760
+ participant.email = p_data['email']
761
+ participant.fb_link = p_data.get('fb_link', '')
762
+ participant.introduction = p_data.get('introduction', '')
763
+ participant.table_id = int(p_data['table_id'])
764
+ participant.seat_number = int(p_data['seat_number'])
765
+ participant.is_table_leader = bool(p_data.get('is_table_leader', False))
766
+ participant.has_paid = bool(p_data.get('has_paid', False))
767
+ participant.note = p_data.get('note', '')
768
+
769
+ db.session.commit()
770
+ print("資料已從 Google Sheets 更新")
771
+ else:
772
+ print("從 Google Sheets 獲取資料失敗")
773
+ else:
774
+ print(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}")
775
+ except Exception as e:
776
+ print(f"同步 Google Sheets 資料時出錯: {str(e)}")
777
+
778
+ # 從資料庫獲取桌次資料
779
  tables = Table.query.order_by(Table.id).all()
780
  print(f"找到 {len(tables)} 張桌子")
781
 
782
+ # 轉換成 JSON 格式
783
  result = {
784
+ 'tables': [table.to_dict() for table in tables]
 
 
 
 
 
 
 
 
 
 
 
785
  }
786
 
787
  print("桌次資料獲取成功")
788
  return jsonify(result)
789
+
790
  except Exception as e:
791
  print(f"獲取桌次資料時出錯: {str(e)}")
792
  return jsonify({'error': str(e)}), 500