ichieh commited on
Commit
dd7cb5f
·
1 Parent(s): 6ef229f

Add Google Sheets backup and restore functionality

Browse files
Files changed (4) hide show
  1. app.py +99 -0
  2. requirements.txt +4 -4
  3. sync_settings.gs +84 -0
  4. templates/admin.html +75 -0
app.py CHANGED
@@ -4,6 +4,7 @@ from datetime import datetime
4
  import os
5
  import time
6
  from functools import wraps
 
7
 
8
  app = Flask(__name__, instance_relative_config=True)
9
 
@@ -157,6 +158,24 @@ def admin_required(f):
157
  return f(*args, **kwargs)
158
  return decorated_function
159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  @app.route('/')
161
  def index():
162
  return render_template('index.html')
@@ -228,6 +247,86 @@ def admin_settings():
228
  db.session.rollback()
229
  return jsonify({'error': str(e)}), 400
230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  @app.route('/api/admin/participants', methods=['GET'])
232
  @admin_required
233
  def get_all_participants():
 
4
  import os
5
  import time
6
  from functools import wraps
7
+ import requests
8
 
9
  app = Flask(__name__, instance_relative_config=True)
10
 
 
158
  return f(*args, **kwargs)
159
  return decorated_function
160
 
161
+ # 添加新的環境變數
162
+ SETTINGS_SCRIPT_URL = os.environ.get('SETTINGS_SCRIPT_URL', '')
163
+
164
+ def sync_settings_to_sheets(action, data):
165
+ """同步設定到 Google Sheets"""
166
+ if not SETTINGS_SCRIPT_URL:
167
+ return None
168
+
169
+ try:
170
+ response = requests.post(SETTINGS_SCRIPT_URL, json={
171
+ 'action': action,
172
+ **data
173
+ })
174
+ return response.json()
175
+ except Exception as e:
176
+ print(f"Error syncing to sheets: {str(e)}")
177
+ return None
178
+
179
  @app.route('/')
180
  def index():
181
  return render_template('index.html')
 
247
  db.session.rollback()
248
  return jsonify({'error': str(e)}), 400
249
 
250
+ @app.route('/api/admin/settings/backup', methods=['POST'])
251
+ @admin_required
252
+ def backup_settings():
253
+ try:
254
+ # 獲取當前所有桌子設定
255
+ tables = Table.query.all()
256
+ total_tables = len(tables)
257
+ seats_per_table = tables[0].capacity if tables else 0
258
+
259
+ # 同步設定到 Sheets
260
+ sync_settings_to_sheets('saveSettings', {
261
+ 'totalTables': total_tables,
262
+ 'seatsPerTable': seats_per_table
263
+ })
264
+
265
+ # 備份參與者資料
266
+ participants = Participant.query.all()
267
+ sync_settings_to_sheets('backupParticipants', {
268
+ 'participants': [{
269
+ 'id': p.id,
270
+ 'nickname': p.nickname,
271
+ 'email': p.email,
272
+ 'fb_link': p.fb_link,
273
+ 'introduction': p.introduction,
274
+ 'table_id': p.table_id,
275
+ 'seat_number': p.seat_number,
276
+ 'created_at': p.created_at.strftime('%Y-%m-%d %H:%M:%S')
277
+ } for p in participants]
278
+ })
279
+
280
+ return jsonify({'message': '備份成功'})
281
+ except Exception as e:
282
+ return jsonify({'error': str(e)}), 500
283
+
284
+ @app.route('/api/admin/settings/restore', methods=['POST'])
285
+ @admin_required
286
+ def restore_settings():
287
+ try:
288
+ # 從 Sheets 恢復設定
289
+ settings = sync_settings_to_sheets('loadSettings', {})
290
+ if settings:
291
+ # 清除現有的桌子
292
+ Table.query.delete()
293
+
294
+ # 重新創建桌子
295
+ for i in range(int(settings['totalTables'])):
296
+ table = Table(
297
+ name=f'第{i+1}桌',
298
+ capacity=int(settings['seatsPerTable'])
299
+ )
300
+ db.session.add(table)
301
+
302
+ db.session.commit()
303
+
304
+ # 從 Sheets 恢復參與者資料
305
+ result = sync_settings_to_sheets('restoreParticipants', {})
306
+ if result and 'participants' in result:
307
+ # 清除現有的參與者
308
+ Participant.query.delete()
309
+
310
+ # 恢復參與者資料
311
+ for p_data in result['participants']:
312
+ participant = Participant(
313
+ nickname=p_data['nickname'],
314
+ email=p_data['email'],
315
+ fb_link=p_data['fb_link'],
316
+ introduction=p_data['introduction'],
317
+ table_id=p_data['table_id'],
318
+ seat_number=p_data['seat_number'],
319
+ created_at=datetime.strptime(p_data['created_at'], '%Y-%m-%d %H:%M:%S')
320
+ )
321
+ db.session.add(participant)
322
+
323
+ db.session.commit()
324
+
325
+ return jsonify({'message': '恢復成功'})
326
+ except Exception as e:
327
+ db.session.rollback()
328
+ return jsonify({'error': str(e)}), 500
329
+
330
  @app.route('/api/admin/participants', methods=['GET'])
331
  @admin_required
332
  def get_all_participants():
requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
- Flask==3.0.0
2
- Flask-SQLAlchemy==3.1.1
3
- SQLAlchemy==2.0.25
4
- python-dotenv==1.0.0
 
1
+ flask==2.0.1
2
+ flask-sqlalchemy==2.5.1
3
+ requests==2.26.0
4
+ python-dotenv==0.19.0
sync_settings.gs ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function doPost(e) {
2
+ var sheet = SpreadsheetApp.getActiveSpreadsheet();
3
+ var settingsSheet = sheet.getSheetByName('Settings') || sheet.insertSheet('Settings');
4
+ var participantsSheet = sheet.getSheetByName('Participants') || sheet.insertSheet('Participants');
5
+
6
+ var data = JSON.parse(e.postData.contents);
7
+ var action = data.action;
8
+
9
+ if (action === 'saveSettings') {
10
+ // 保存桌次設定
11
+ settingsSheet.clear();
12
+ settingsSheet.getRange('A1:B1').setValues([['總桌數', '每桌人數']]);
13
+ settingsSheet.getRange('A2:B2').setValues([[data.totalTables, data.seatsPerTable]]);
14
+ return ContentService.createTextOutput(JSON.stringify({success: true}))
15
+ .setMimeType(ContentService.MimeType.JSON);
16
+ }
17
+
18
+ if (action === 'loadSettings') {
19
+ // 讀取桌次設定
20
+ var settings = settingsSheet.getRange('A2:B2').getValues()[0];
21
+ return ContentService.createTextOutput(JSON.stringify({
22
+ totalTables: settings[0],
23
+ seatsPerTable: settings[1]
24
+ })).setMimeType(ContentService.MimeType.JSON);
25
+ }
26
+
27
+ if (action === 'backupParticipants') {
28
+ // 備份參與者資料
29
+ participantsSheet.clear();
30
+ participantsSheet.getRange('A1:H1').setValues([['ID', '暱稱', 'Email', 'FB連結', '自我介紹', '桌次', '座位號碼', '報名時間']]);
31
+
32
+ var participants = data.participants;
33
+ if (participants && participants.length > 0) {
34
+ var values = participants.map(function(p) {
35
+ return [
36
+ p.id,
37
+ p.nickname,
38
+ p.email,
39
+ p.fb_link,
40
+ p.introduction,
41
+ p.table_id,
42
+ p.seat_number,
43
+ p.created_at
44
+ ];
45
+ });
46
+ participantsSheet.getRange(2, 1, values.length, 8).setValues(values);
47
+ }
48
+
49
+ return ContentService.createTextOutput(JSON.stringify({success: true}))
50
+ .setMimeType(ContentService.MimeType.JSON);
51
+ }
52
+
53
+ if (action === 'restoreParticipants') {
54
+ // 讀取備份的參與者資料
55
+ var range = participantsSheet.getDataRange();
56
+ var values = range.getValues();
57
+ var participants = [];
58
+
59
+ for (var i = 1; i < values.length; i++) {
60
+ var row = values[i];
61
+ participants.push({
62
+ id: row[0],
63
+ nickname: row[1],
64
+ email: row[2],
65
+ fb_link: row[3],
66
+ introduction: row[4],
67
+ table_id: row[5],
68
+ seat_number: row[6],
69
+ created_at: row[7]
70
+ });
71
+ }
72
+
73
+ return ContentService.createTextOutput(JSON.stringify({
74
+ participants: participants
75
+ })).setMimeType(ContentService.MimeType.JSON);
76
+ }
77
+
78
+ return ContentService.createTextOutput(JSON.stringify({error: 'Invalid action'}))
79
+ .setMimeType(ContentService.MimeType.JSON);
80
+ }
81
+
82
+ function doGet(e) {
83
+ return doPost(e);
84
+ }
templates/admin.html CHANGED
@@ -6,10 +6,24 @@
6
  <title>活動座位管理</title>
7
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
8
  <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.css" rel="stylesheet">
 
9
  </head>
10
  <body>
11
  <div class="container mt-4">
12
  <h2>管理員後台</h2>
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  <div class="row">
14
  <div class="col">
15
  <div class="table-responsive">
@@ -214,6 +228,67 @@
214
  }
215
  }
216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  // 初始載入
218
  document.addEventListener('DOMContentLoaded', loadParticipants);
219
  </script>
 
6
  <title>活動座位管理</title>
7
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
8
  <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.css" rel="stylesheet">
9
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
10
  </head>
11
  <body>
12
  <div class="container mt-4">
13
  <h2>管理員後台</h2>
14
+
15
+ <!-- 備份和恢復按鈕 -->
16
+ <div class="row mb-4">
17
+ <div class="col">
18
+ <button class="btn btn-success me-2" onclick="backupData()">
19
+ <i class="bi bi-cloud-upload"></i> 備份資料到 Sheets
20
+ </button>
21
+ <button class="btn btn-warning" onclick="restoreData()">
22
+ <i class="bi bi-cloud-download"></i> 從 Sheets 恢復資料
23
+ </button>
24
+ </div>
25
+ </div>
26
+
27
  <div class="row">
28
  <div class="col">
29
  <div class="table-responsive">
 
228
  }
229
  }
230
 
231
+ // 備份資料到 Google Sheets
232
+ async function backupData() {
233
+ try {
234
+ const response = await fetch('/api/admin/settings/backup', {
235
+ method: 'POST',
236
+ headers: {
237
+ 'Content-Type': 'application/json'
238
+ }
239
+ });
240
+
241
+ const data = await response.json();
242
+
243
+ if (response.ok) {
244
+ Swal.fire('成功', '資料已成功備份到 Google Sheets', 'success');
245
+ } else {
246
+ throw new Error(data.error);
247
+ }
248
+ } catch (error) {
249
+ console.error('Error:', error);
250
+ Swal.fire('錯誤', error.message || '備份失敗', 'error');
251
+ }
252
+ }
253
+
254
+ // 從 Google Sheets 恢復資料
255
+ async function restoreData() {
256
+ try {
257
+ const result = await Swal.fire({
258
+ title: '確認恢復資料?',
259
+ text: '這將會覆蓋目前的所有資料!',
260
+ icon: 'warning',
261
+ showCancelButton: true,
262
+ confirmButtonColor: '#3085d6',
263
+ cancelButtonColor: '#d33',
264
+ confirmButtonText: '是,恢復資料',
265
+ cancelButtonText: '取消'
266
+ });
267
+
268
+ if (result.isConfirmed) {
269
+ const response = await fetch('/api/admin/settings/restore', {
270
+ method: 'POST',
271
+ headers: {
272
+ 'Content-Type': 'application/json'
273
+ }
274
+ });
275
+
276
+ const data = await response.json();
277
+
278
+ if (response.ok) {
279
+ await Swal.fire('成功', '資料已成功恢復', 'success');
280
+ // 重新載入頁面以顯示恢復的資料
281
+ location.reload();
282
+ } else {
283
+ throw new Error(data.error);
284
+ }
285
+ }
286
+ } catch (error) {
287
+ console.error('Error:', error);
288
+ Swal.fire('錯誤', error.message || '恢復失敗', 'error');
289
+ }
290
+ }
291
+
292
  // 初始載入
293
  document.addEventListener('DOMContentLoaded', loadParticipants);
294
  </script>