-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
384 lines (325 loc) · 13.7 KB
/
main.py
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
from flask import Flask, request, jsonify, render_template
from flask_login import LoginManager
from app.routes import routes
from app.models import db, Apoteker
import pyodbc
def create_app():
app = Flask(__name__, template_folder='app/templates', static_folder='app/static')
app.config['SECRET_KEY'] = 'your-secret-key'
# SQL Server connection string for SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pyodbc:///?odbc_connect=' + (
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=(local);'
'DATABASE=Apotek;'
'Trusted_Connection=yes;'
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize extensions
db.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'routes.login'
@login_manager.user_loader
def load_user(user_id):
return Apoteker.query.get(user_id)
# Register the routes blueprint
app.register_blueprint(routes)
# Add error handler for 404
@app.errorhandler(404)
def page_not_found(e):
return render_template('404notfound.html'), 404
@app.route('/add_pharmacist', methods=['POST'])
def add_pharmacist():
try:
data = request.get_json()
# Extract data from JSON
id_apoteker = data['id_apoteker']
nama_apoteker = data['nama_apoteker']
lisensi_apoteker = data['lisensi_apoteker']
no_telp_apoteker = data['no_telp_apoteker']
shift_apoteker = data['shift_apoteker']
jenis_kelamin_apoteker = data['jenis_kelamin_apoteker']
tgl_lahir_apoteker = data['tgl_lahir_apoteker']
alamat_apoteker = data['alamat_apoteker']
tgl_diterima_kerja = data['tgl_diterima_kerja']
password = data['password']
medicines = data['medicines']
# Connect to database using Windows Authentication
conn_str = (
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=(local);'
'DATABASE=Apotek;'
'Trusted_Connection=yes;'
)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
# Add to database
cursor.execute("""
INSERT INTO Apoteker (
id_apoteker, nama_apoteker, lisensi_apoteker,
no_telp_apoteker, shift_apoteker, jenis_kelamin_apoteker,
tgl_lahir_apoteker, alamat_apoteker, tgl_diterima_kerja, password
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
id_apoteker, nama_apoteker, lisensi_apoteker,
no_telp_apoteker, shift_apoteker, jenis_kelamin_apoteker,
tgl_lahir_apoteker, alamat_apoteker, tgl_diterima_kerja, password
))
# Add medicine handling permissions
for medicine_id in medicines:
cursor.execute("""
INSERT INTO Menangani (id_apoteker, id_obat)
VALUES (?, ?)
""", (id_apoteker, medicine_id))
conn.commit()
cursor.close()
conn.close()
return jsonify({'success': True, 'message': 'Data apoteker berhasil ditambahkan'})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
@app.route('/edit_pharmacist', methods=['POST'])
def edit_pharmacist():
try:
data = request.get_json()
# Extract data from JSON
id_apoteker = data['id_apoteker']
nama_apoteker = data['nama_apoteker']
lisensi_apoteker = data['lisensi_apoteker']
no_telp_apoteker = data['no_telp_apoteker']
shift_apoteker = data['shift_apoteker']
jenis_kelamin_apoteker = data['jenis_kelamin_apoteker']
tgl_lahir_apoteker = data['tgl_lahir_apoteker']
alamat_apoteker = data['alamat_apoteker']
tgl_diterima_kerja = data['tgl_diterima_kerja']
password = data['password']
medicines = data['medicines']
# Connect to database using Windows Authentication
conn_str = (
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=(local);'
'DATABASE=Apotek;'
'Trusted_Connection=yes;'
)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
# Update apoteker data
cursor.execute("""
UPDATE Apoteker SET
nama_apoteker = ?,
lisensi_apoteker = ?,
no_telp_apoteker = ?,
shift_apoteker = ?,
jenis_kelamin_apoteker = ?,
tgl_lahir_apoteker = ?,
alamat_apoteker = ?,
tgl_diterima_kerja = ?,
password = ?
WHERE id_apoteker = ?
""", (
nama_apoteker, lisensi_apoteker, no_telp_apoteker,
shift_apoteker, jenis_kelamin_apoteker, tgl_lahir_apoteker,
alamat_apoteker, tgl_diterima_kerja, password, id_apoteker
))
# Update medicine handling permissions
cursor.execute("DELETE FROM Menangani WHERE id_apoteker = ?", (id_apoteker,))
for medicine_id in medicines:
cursor.execute("""
INSERT INTO Menangani (id_apoteker, id_obat)
VALUES (?, ?)
""", (id_apoteker, medicine_id))
conn.commit()
cursor.close()
conn.close()
return jsonify({'success': True, 'message': 'Data apoteker berhasil diperbarui'})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
@app.route('/add_obat', methods=['POST'])
def add_obat():
try:
data = request.get_json()
# Validate required fields
required_fields = ['id_obat', 'nama_obat', 'kategori', 'stok', 'harga',
'supplier', 'tgl_kadaluarsa', 'kemasan']
for field in required_fields:
if not data.get(field):
return jsonify({
'success': False,
'message': f'Field {field} harus diisi'
})
# Validate numeric fields
try:
stok = int(data['stok'])
harga = float(data['harga'])
if stok < 0 or harga < 0:
raise ValueError
except ValueError:
return jsonify({
'success': False,
'message': 'Stok dan harga harus berupa angka positif'
})
# Connect to database
conn_str = (
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=(local);'
'DATABASE=Apotek;'
'Trusted_Connection=yes;'
)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
try:
# Start transaction
cursor.execute("BEGIN TRANSACTION")
# Check if medicine ID already exists
cursor.execute("SELECT id_obat FROM Obat WHERE id_obat = ?", (data['id_obat'],))
if cursor.fetchone():
raise Exception("ID Obat sudah ada")
# Insert medicine data
cursor.execute("""
INSERT INTO Obat (
id_obat, nama_obat, kategori_obat,
stok_obat, harga_obat, id_supplier,
tgl_kedaluarsa, kemasan
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
data['id_obat'], data['nama_obat'], data['kategori'],
data['stok'], data['harga'], data['supplier'],
data['tgl_kadaluarsa'], data['kemasan']
))
# Commit transaction
cursor.execute("COMMIT TRANSACTION")
conn.commit()
return jsonify({
'success': True,
'message': 'Data obat berhasil ditambahkan'
})
except Exception as e:
# Rollback on error
cursor.execute("ROLLBACK TRANSACTION")
conn.rollback()
raise e
finally:
cursor.close()
conn.close()
except Exception as e:
print('Error:', str(e))
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/edit_transaction', methods=['POST'])
def edit_transaction():
try:
data = request.get_json()
# Extract data
id_transaksi = data['id_transaksi']
waktu_transaksi = data['waktu_transaksi']
id_pelanggan = data['id_pelanggan']
medicines = data['medicines']
# Validate required fields
if not all([id_transaksi, waktu_transaksi, id_pelanggan, medicines]):
return jsonify({
'success': False,
'message': 'Semua field harus diisi'
})
# Connect to database
conn_str = (
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=(local);'
'DATABASE=Apotek;'
'Trusted_Connection=yes;'
)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
try:
# Start transaction
cursor.execute("BEGIN TRANSACTION")
# First, get the current medicine quantities to restore stock
cursor.execute("""
SELECT id_obat, kuantitas_obat
FROM Detail_transaksi
WHERE id_transaksi = ?
""", (id_transaksi,))
old_medicines = cursor.fetchall()
# Restore old quantities back to stock
for old_med in old_medicines:
cursor.execute("""
UPDATE Obat
SET stok_obat = stok_obat + ?
WHERE id_obat = ?
""", (old_med[1], old_med[0]))
# Update transaction header
cursor.execute("""
UPDATE Transaksi
SET waktu_transaksi = ?,
id_pelanggan = ?
WHERE id_transaksi = ?
""", (waktu_transaksi, id_pelanggan, id_transaksi))
# Calculate total price
total_price = 0
# Delete existing details
cursor.execute("""
DELETE FROM Detail_transaksi
WHERE id_transaksi = ?
""", (id_transaksi,))
# Insert new details and update stock
for medicine in medicines:
# Validate medicine exists and has enough stock
cursor.execute("""
SELECT stok_obat, harga_obat
FROM Obat
WHERE id_obat = ?
""", (medicine['id_obat'],))
result = cursor.fetchone()
if not result:
raise Exception(f"Obat dengan ID {medicine['id_obat']} tidak ditemukan")
current_stock, harga_obat = result
requested_qty = int(medicine['kuantitas'])
if requested_qty > current_stock:
raise Exception(f"Stok tidak mencukupi untuk obat {medicine['id_obat']}")
# Add to total price
total_price += float(harga_obat) * requested_qty
# Insert new detail
cursor.execute("""
INSERT INTO Detail_transaksi (
id_transaksi, id_obat, kuantitas_obat
) VALUES (?, ?, ?)
""", (
id_transaksi, medicine['id_obat'], requested_qty
))
# Update stock
cursor.execute("""
UPDATE Obat
SET stok_obat = stok_obat - ?
WHERE id_obat = ?
""", (requested_qty, medicine['id_obat']))
# Update total price in transaction
cursor.execute("""
UPDATE Transaksi
SET total_harga = ?
WHERE id_transaksi = ?
""", (total_price, id_transaksi))
# Commit transaction
cursor.execute("COMMIT TRANSACTION")
conn.commit()
return jsonify({
'success': True,
'message': 'Transaksi berhasil diperbarui'
})
except Exception as e:
# Rollback on error
cursor.execute("ROLLBACK TRANSACTION")
conn.rollback()
raise e
finally:
cursor.close()
conn.close()
except Exception as e:
print('Error:', str(e))
return jsonify({
'success': False,
'message': str(e)
})
return app
if __name__ == '__main__':
app = create_app()
app.run(debug=True, port=5000)