File size: 7,970 Bytes
6bed1e4
 
fa3a1a9
 
0059b56
 
 
6bed1e4
fa3a1a9
 
 
0059b56
 
fa3a1a9
6bed1e4
 
 
 
 
 
 
 
 
5720959
e8a1353
 
 
 
55b202d
 
 
 
 
 
 
 
e8a1353
55b202d
 
 
e8a1353
 
55b202d
 
 
 
 
 
 
 
 
 
 
 
 
e8a1353
55b202d
 
 
 
 
 
 
 
 
 
e8a1353
 
 
 
 
 
 
f05f818
0718aa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05f818
0718aa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05f818
0718aa4
 
 
 
f05f818
0718aa4
 
 
 
f05f818
0718aa4
 
 
 
f05f818
0718aa4
 
 
 
f05f818
0718aa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05f818
 
 
 
fa3a1a9
 
 
 
 
 
 
 
 
 
0059b56
6bed1e4
fa3a1a9
 
7cf4e47
fa3a1a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0059b56
6bed1e4
0059b56
fa3a1a9
 
0059b56
 
 
fa3a1a9
0059b56
 
 
 
 
 
fa3a1a9
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
from flask import Flask, request, jsonify, render_template_string
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
import os
import io
import datetime
import json

app = Flask(__name__)

SPREADSHEET_ID = '1rcIJflbC1VIc70F6dnASLFvGQ90TXHhCx0iyxsXR7Ww'
FOLDER_ID = '1brmLNqOMCvRS0TDY6ECHvIBmlRx8pcPz'

# Create service account credentials from environment variable
CREDS_JSON = os.environ.get('GOOGLE_CREDENTIALS')
if CREDS_JSON:
    CREDS_INFO = json.loads(CREDS_JSON)
    CREDENTIALS = Credentials.from_service_account_info(
        CREDS_INFO,
        scopes=['https://www.googleapis.com/auth/spreadsheets',
                'https://www.googleapis.com/auth/drive.file']
    )

def ensure_headers():
    try:
        sheets_service = build('sheets', 'v4', credentials=CREDENTIALS)
        
        # Directly update first row with headers
        headers = [
            ['姓名 Name', '學號 Student ID', '購買商品 Product', 
             '金額 Cost', '發票檔案 Receipt File', '時間 Timestamp', 'IP位址 IP Address']
        ]
        
        # Update A1:G1 with headers
        sheets_service.spreadsheets().values().update(
            spreadsheetId=SPREADSHEET_ID,
            range='Sheet1!A1:G1',
            valueInputOption='RAW',
            body={'values': headers}
        ).execute()
        
        # Format headers to be bold and centered
        requests = [{
            'repeatCell': {
                'range': {
                    'sheetId': 0,
                    'startRowIndex': 0,
                    'endRowIndex': 1
                },
                'cell': {
                    'userEnteredFormat': {
                        'horizontalAlignment': 'CENTER',
                        'textFormat': {
                            'bold': True
                        }
                    }
                },
                'fields': 'userEnteredFormat(horizontalAlignment,textFormat)'
            }
        }]
        
        sheets_service.spreadsheets().batchUpdate(
            spreadsheetId=SPREADSHEET_ID,
            body={'requests': requests}
        ).execute()
            
    except Exception as e:
        print(f"Error setting headers: {str(e)}")
@app.before_first_request
def initialize():
    ensure_headers()

HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
    <title>Purchase Record Form</title>
    <meta charset="UTF-8">
    <style>
        body { 
            font-family: Arial, sans-serif; 
            max-width: 600px; 
            margin: 20px auto;
            padding: 20px;
        }
        .form-group { 
            margin-bottom: 20px; 
        }
        label { 
            display: block; 
            margin-bottom: 8px;
            font-weight: bold;
        }
        input { 
            width: 100%; 
            padding: 10px; 
            border: 1px solid #ddd; 
            border-radius: 4px;
            font-size: 16px;
        }
        button { 
            background-color: #4CAF50; 
            color: white; 
            padding: 12px 24px; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer;
            font-size: 16px;
            width: 100%;
        }
        button:hover { 
            background-color: #45a049; 
        }
        #status { 
            margin-top: 20px; 
            padding: 15px;
            border-radius: 4px;
            display: none;
        }
        .success { 
            background-color: #dff0d8; 
            color: #3c763d; 
        }
        .error { 
            background-color: #f2dede; 
            color: #a94442; 
        }
    </style>
</head>
<body>
    <h2>購買記錄表單 Purchase Record Form</h2>
    <form id="purchaseForm">
        <div class="form-group">
            <label for="name">姓名 Name:</label>
            <input type="text" id="name" name="name" required>
        </div>
        
        <div class="form-group">
            <label for="studentId">學號 Student ID:</label>
            <input type="text" id="studentId" name="studentId" required>
        </div>
        
        <div class="form-group">
            <label for="product">購買商品 Product:</label>
            <input type="text" id="product" name="product" required>
        </div>
        
        <div class="form-group">
            <label for="cost">金額 Cost:</label>
            <input type="number" id="cost" name="cost" required>
        </div>
        
        <div class="form-group">
            <label for="receipt">發票 Receipt:</label>
            <input type="file" id="receipt" name="receipt" accept="image/*,.pdf" required>
        </div>
        
        <button type="submit">提交 Submit</button>
    </form>
    <div id="status"></div>

    <script>
        document.getElementById('purchaseForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const status = document.getElementById('status');
            status.style.display = 'block';
            status.textContent = '提交中... Submitting...';
            status.className = '';
            
            const formData = new FormData(e.target);
            
            try {
                const response = await fetch('/submit', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    status.className = 'success';
                    status.textContent = '提交成功! ' + result.message;
                    e.target.reset();
                } else {
                    status.className = 'error';
                    status.textContent = '錯誤:' + result.message;
                }
            } catch (error) {
                status.className = 'error';
                status.textContent = '提交錯誤 Error submitting form';
            }
        });
    </script>
</body>
</html>
'''

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

@app.route('/submit', methods=['POST'])
def submit():
    try:
        name = request.form['name']
        student_id = request.form['studentId']
        product = request.form['product']
        cost = request.form['cost']
        file = request.files['receipt']

        # Upload file to Drive
        drive_service = build('drive', 'v3', credentials=CREDENTIALS)
        
        file_metadata = {
            'name': f"{student_id}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}_{file.filename}",
            'parents': [FOLDER_ID]
        }
        
        media = MediaIoBaseUpload(
            io.BytesIO(file.read()),
            mimetype=file.content_type,
            resumable=True
        )
        
        uploaded_file = drive_service.files().create(
            body=file_metadata,
            media_body=media,
            fields='id,webViewLink'
        ).execute()
        
        file_url = uploaded_file.get('webViewLink', '')

        # Update Google Sheet
        sheets_service = build('sheets', 'v4', credentials=CREDENTIALS)
        
        timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ip_address = request.remote_addr

        values = [[name, student_id, product, cost, file_url, timestamp, ip_address]]
        body = {'values': values}
        
        sheets_service.spreadsheets().values().append(
            spreadsheetId=SPREADSHEET_ID,
            range='Sheet1!A:G',
            valueInputOption='USER_ENTERED',
            body=body
        ).execute()

        return jsonify({'success': True, 'message': 'Data submitted successfully!'})

    except Exception as e:
        return jsonify({'success': False, 'message': f'Error: {str(e)}'})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)