-
Notifications
You must be signed in to change notification settings - Fork 0
/
manageDB.py
1609 lines (1237 loc) · 47.4 KB
/
manageDB.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sqlite3
import os
import time
import datetime
import calc
# init() -> returns an int
'''
initialises the cursor and connection. Returns:
0: database file was present and not remade. connection is successfully opened.
1: database was made connection successfully opened.
2: database could not be opened.
'''
def init():
global conn
global curs
global dbname
dbname = 'bus_db.db'
r = 2
#checks if the file is already present
if os.path.isfile(dbname):
r = 0
try:
conn = sqlite3.connect(dbname)
curs = conn.cursor()
r = 1 if r != 0 else 0
except:
r = 2
return r
# show_table_names()
'''
Returns names of all the tables. For debugging purpose.
'''
def get_table_names():
table_names = None
if init() != 2:
try:
tblcmd = "SELECT name FROM sqlite_master WHERE type='table'"
curs.execute(tblcmd)
table_names = curs.fetchall()
except:
table_names = 2
return table_names
# get_table(table_name)
'''
Returns contents of the table with name table_name. Headers and content are sent separately.
Example:
mdb.get_table('route_table')
(['route_id', 'source', 'stop_1', 'stop_2', 'destination'], [('AS1', 'Kolkata', 'Bardhaman', '', 'Asansol'), ('AS2', 'Kolkata', 'Bardhaman', 'Durgapur', 'Asansol'), ('ML1', 'Kolkata', '', '', 'Malda'), ('ML2', 'Kolkata', 'Bardhaman', '', 'Malda'), ('MID1', 'Kolkata', 'Kolaghat', 'Kharagpur', 'Midnapore'), ('MID2', 'Kolkata', 'Kharagpur', '', 'Midnapore'), ('HL1', 'Howrah', 'Kolaghat', '', 'Haldia'), ('HL2', 'Howrah', '', '', 'Haldia'), ('DUR1', 'Howrah', 'Bardhaman', '', 'Durgapur'), ('DUR2', 'Howrah', '', '', 'Durgapur')])
'''
def get_table(table_name):
data = []
headers = []
if init() != 2:
try:
tblcmd = "SELECT * FROM " + table_name
curs.execute(tblcmd)
data = curs.fetchall()
headers = [data[0] for data in curs.description]
except: pass
return headers, data
# isTablePresent(table_name {str}) -> returns bool
'''
Returns True if table with table_name is present, else False. For debugging purpose and internal use.
'''
def isTablePresent(table_name):
presence = False
if init() != 2:
try:
tblcount = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='" + table_name + "'"
curs.execute(tblcount)
c = curs.fetchall()
if c != [(0,)]:
presence = True
except:
pass
return presence
# create_route_table(n {0|1}, table_name {str}) -> returns an int
'''
Creates the bus_table. Returns:
0 if table was present
1 if table was not present and created
2 if table could not be made
n : pass 1 to recreate table
'''
def create_bus_table(n = 0, table_name = 'bus_table'):
r = 2
if isTablePresent(table_name) == False or n == 1:
try:
# delete old table if user selects to recreate data
tbldelete = "DROP TABLE IF EXISTS " + table_name
curs.execute(tbldelete)
# create table
tblcreate = "CREATE TABLE " + table_name + "(bus_id char(5) PRIMARY KEY, route_id char(5), type char(3), total_seats int(3))"
curs.execute(tblcreate)
#insert records
tblins = "INSERT INTO " + table_name + " values(?, ?, ?, ?)"
curs.execute(tblins, ('S1', 'AS1', 'Ordinary', 58))
curs.execute(tblins, ('AC1', 'AS1', 'Air conditioned', 45))
curs.execute(tblins, ('SL1', 'AS1', 'Sleeper', 40))
curs.execute(tblins, ('S2', 'AS2', 'Ordinary', 56))
curs.execute(tblins, ('SL2', 'AS2', 'Sleeper', 40))
curs.execute(tblins, ('S3', 'ML1', 'Ordinary', 40))
curs.execute(tblins, ('AC3', 'ML1', 'Air conditioned', 45))
curs.execute(tblins, ('S4', 'ML2', 'Ordinary', 58))
curs.execute(tblins, ('SL4', 'ML2', 'Sleeper', 45))
curs.execute(tblins, ('S5', 'MID1', 'Ordinary', 58))
curs.execute(tblins, ('AC5', 'MID1', 'Air conditioned', 45))
curs.execute(tblins, ('V5', 'MID1', 'Volvo', 40))
curs.execute(tblins, ('S6', 'MID2', 'Ordinary', 50))
curs.execute(tblins, ('SL6', 'MID2', 'Sleeper', 40))
curs.execute(tblins, ('S7', 'HL1', 'Ordinary', 56))
curs.execute(tblins, ('V7', 'HL1', 'Volvo', 40))
curs.execute(tblins, ('S8', 'HL2', 'Ordinary', 45))
curs.execute(tblins, ('AC8', 'HL2', 'Air conditioned', 40))
curs.execute(tblins, ('SL8', 'HL2', 'Sleeper', 40))
curs.execute(tblins, ('S9', 'DUR1', 'Ordinary', 58))
curs.execute(tblins, ('SL9', 'DUR1', 'Sleeper', 50))
curs.execute(tblins, ('S10', 'DUR2', 'Ordinary', 45))
curs.execute(tblins, ('SL10', 'DUR2', 'Sleeper', 40))
curs.execute(tblins, ('V10', 'DUR2', 'Volvo', 40))
conn.commit()
r = 1
except:
r = 2
else:
r = 0
return r, table_name
# create_route_table(n {0|1}, table_name {str}) -> returns an int
'''
Creates the route_table. Returns:
0 if table was present
1 if table was not present and created
2 if table could not be made
n : pass 1 to recreate table
'''
def create_route_table(n = 0, table_name = 'route_table'):
r = 2
if isTablePresent(table_name) == False or n == 1:
try:
# delete old table if user selects to recreate data
tbldelete = "DROP TABLE IF EXISTS " + table_name
curs.execute(tbldelete)
# create table
tblcreate = "CREATE TABLE " + table_name + "(route_id char(5) PRIMARY KEY, source text, stop_1 text, stop_2 text, destination)"
curs.execute(tblcreate)
#insert records
tblins = "INSERT INTO " + table_name + " values(?, ?, ?, ?, ?)"
curs.execute(tblins, ('AS1', 'Kolkata', 'Bardhaman', '', 'Asansol'))
curs.execute(tblins, ('AS2', 'Kolkata', 'Bardhaman', 'Durgapur', 'Asansol'))
curs.execute(tblins, ('ML1', 'Kolkata', '', '', 'Malda'))
curs.execute(tblins, ('ML2', 'Kolkata', 'Bardhaman', '', 'Malda'))
curs.execute(tblins, ('MID1', 'Kolkata', 'Kolaghat', 'Kharagpur', 'Midnapore'))
curs.execute(tblins, ('MID2', 'Kolkata', 'Kharagpur', '', 'Midnapore'))
curs.execute(tblins, ('HL1', 'Howrah', 'Kolaghat', '', 'Haldia'))
curs.execute(tblins, ('HL2', 'Howrah', '', '', 'Haldia'))
curs.execute(tblins, ('DUR1', 'Howrah', 'Bardhaman', '', 'Durgapur'))
curs.execute(tblins, ('DUR2', 'Howrah', '', '', 'Durgapur'))
conn.commit()
r = 1
except:
r = 2
else:
r = 0
return r, table_name
# create_fare_chart(n {0|1}, table_name {str}) -> returns an int
'''
Creates the fare chart + time table. Returns:
0 if table was present
1 if table was not present and created
2 if table could not be made
n : pass 1 to recreate table
'''
def create_fare_chart(n = 0, table_name = 'fare_chart'):
r = 2
if isTablePresent(table_name) == False or n == 1:
try:
# delete old table if user selects to recreate data
tbldelete = "DROP TABLE IF EXISTS " + table_name
curs.execute(tbldelete)
# create table
tblcreate = "CREATE TABLE " + table_name + "(bus_id char(5) PRIMARY KEY, source_time text, stop_1_time text, fare_1 int(5), stop_2_time text, fare_2 int(5), destination_time text, fare_d int(5))"
curs.execute(tblcreate)
#insert records
tblins = "INSERT INTO " + table_name + " values(?, ?, ?, ?, ?, ?, ?, ?)"
# fares in order: Ordinary, AC, Sleeper, Volvo. Example: for AS1,
curs.execute(tblins, ('S1', '06:30', '07:30', 200, None, None, '08:30', 300))
curs.execute(tblins, ('AC1', '06:00', '07:00', 300, None, None, '08:00', 450))
curs.execute(tblins, ('SL1', '20:00', '21:00', 270, None, None, '22:00', 430))
curs.execute(tblins, ('S2', '05:00', '06:00', 200, '06:30', 270, '08:00', 350))
curs.execute(tblins, ('SL2', '23:00', '00:00', 270, '00:30', 350, '03:00 +1', 450))
curs.execute(tblins, ('S3', '09:00', None, None, None, None, '13:00', 400))
curs.execute(tblins, ('AC3', '10:00', None, None, None, None, '14:00', 400))
curs.execute(tblins, ('S4', '09:30', '11:00', 250, None, None, '13:30', 450))
curs.execute(tblins, ('SL4', '19:30', '21:00', 300, None, None, '23:30', 470))
curs.execute(tblins, ('S5', '07:30', '09:00', 200, '11:00', 300, '14:30', 400))
curs.execute(tblins, ('AC5', '09:00', '11:30', 300, '13:30', 400, '15:30', 500))
curs.execute(tblins, ('V5', '17:00', '18:00', 350, '19:30', 490, '20:00', 570))
curs.execute(tblins, ('S6', '08:30', '10:00', 200, None, None, '14:00', 370))
curs.execute(tblins, ('SL6', '18:30', '20:00', 300, None, None, '22:00', 450))
curs.execute(tblins, ('S7', '09:30', '11:00', 250, None, None, '15:00', 300))
curs.execute(tblins, ('V7', '08:00', '09:30', 350, None, None, '13:00', 500))
curs.execute(tblins, ('S8', '07:00', None, None, None, None, '13:00', 330))
curs.execute(tblins, ('AC8', '11:00', None, None, None, None, '16:30', 450))
curs.execute(tblins, ('SL8', '21:00', None, None, None, None, '02:00 +1', 380))
curs.execute(tblins, ('S9', '07:30', '09:30', 300, None, None, '12:00', 400))
curs.execute(tblins, ('SL9', '19:30', '21:30', 370, None, None, '00:30 +1', 450))
curs.execute(tblins, ('S10', '06:00', None, None, None, None, '10:30', 430))
curs.execute(tblins, ('SL10', '00:20', None, None, None, None, '04:00', 480))
curs.execute(tblins, ('V10', '12:00', None, None, None, None, '15:45', 500))
conn.commit()
r = 1
except:
r = 2
else:
r = 0
return r, table_name
# validate_route(route_id {str}, starting {str}, ending {str}) -> returns tuple
'''
Checks if starting and ending positions are feasible for a route.
If present: returns a tuple of (beginning stop index, ending stop index)
If not found: returns None
Example:
mdb.validate_route('MID1', 'Kolaghat', 'Kharagpur')
(1, 2)
mdb.validate_route('MID1', 'Kolaghat', 'Malda') -> returns None
'''
def validate_route(route_id, starting, ending):
r = None
r1, rtn = create_route_table(0)
if r1 != 2:
# get all available route_id
curs.execute("SELECT route_id FROM " + rtn)
routes = curs.fetchall()
rt = (route_id,)
if rt in routes:
# get the source, stops and destination of the selected route_id
curs.execute("SELECT source, stop_1, stop_2, destination FROM " + rtn + " WHERE route_id=" + "'" + route_id + "'")
places = curs.fetchall()
places = places[0] #fetchall() returns a list with only one tuple element. This line extracts that tuple.
# Remove all None from route
places = [i for i in places if i != '']
if starting in places and ending in places:
# both starting and ending must be present in the route_id
s = places.index(starting)
e = places.index(ending)
if s < e:
# also starting should be before ending
r = (s, e)
return r
# getRouteFromBusID(bus_id {str}) -> returns str
'''
Takes a bus_id and returns its route_id.
Example:
mdb.getRouteFromBusID('AC8')
'HL2'
'''
def getRouteFromBusID(bus_id):
r = ''
r1, rtn = create_bus_table(0)
if r1 != 2:
try:
curs.execute("SELECT route_id FROM " + rtn + " WHERE bus_id='" + bus_id + "'")
rids = curs.fetchall()
if rids != []:
r = rids[0][0]
except: pass
return r
# getFare(bus_id {str}, source {str}, destination {str}) -> returns int
'''
Takes a bus_id and returns journey fare from source to destination.
Example:
mdb.getFare('S5', 'Kolkata', 'Kharagpur')
300
'''
def getFare(bus_id, source, destination):
fare = 0
r1, table_name = create_fare_chart(0)
route_id = getRouteFromBusID(bus_id)
if route_id != 0:
t = validate_route(route_id, source, destination) #index of source and destination as in route_table
if t != None:
try:
s = t[0]
e = t[1]
tblfares = "SELECT fare_1, fare_2, fare_d FROM " + table_name + " WHERE bus_id='" + bus_id + "'"
curs.execute(tblfares)
fares = curs.fetchall()
fares = [i for i in fares[0] if i != None]
fares = [0] + fares # source has zero fare
fare = fares[e] - fares[s] #fare calculated by subtracting starting from ending
except:
fare = ''
return fare
# getTime(bus_id {str}, source {str}, destination {str}) -> returns str
'''
Takes a bus_id and returns journey time from source to destination.
Example:
mdb.getTime('S5', 'Kolkata', 'Kharagpur')
'03:30'
'''
def getTime(bus_id, source, destination):
time = 0
r1, table_name = create_fare_chart(0)
route_id = getRouteFromBusID(bus_id)
if route_id != 0:
t = validate_route(route_id, source, destination) #index of source and destination as in route_table
if t != None:
try:
s = t[0]
e = t[1]
tbltimes = "SELECT source_time, stop_1_time, stop_2_time, destination_time FROM " + table_name + " WHERE bus_id='" + bus_id + "'"
curs.execute(tbltimes)
times = curs.fetchall()
times = [i for i in times[0] if i != None]
ts, te = times[s], times[e]
# operations performed if journey extends next day: example: ts = '23:00', te = '02:30 +1'
te = te.split(' +') # te = ['02:30', '1']
if len(te) == 1: te = te[0]
elif len(te) == 2:
te = str(int(te[0].split(':')[0]) + 24*int(te[1])) + ':' + te[0].split(':')[1] # te = (02 + 24*1):(30) = '26:30'
ts = int(ts.split(':')[0])*60 + int(ts.split(':')[1]) # ts = '23:00' = 23*60 + 30
te = int(te.split(':')[0])*60 + int(te.split(':')[1]) # te = '26:30' = 26*60 + 30
td = te - ts
time = '{:02d}'.format(int(td/60)) + ':' + '{:02d}'.format(int(td%60)) # converting to hours and minutes
except:
time = ''
return time
# getBusType(bus_id {str}) -> returns str
'''
Takes a bus_id and returns its type.
Example:
mdb.getBusType('V10')
'Volvo'
'''
def getBusType(bus_id):
btype = None
r1, table_name = create_bus_table(0)
if r1 != 2:
try:
curs.execute("SELECT type FROM " + table_name + " WHERE bus_id='" + bus_id + "'")
btype = curs.fetchall()
btype = btype[0][0] if btype != [] else None
except: pass
return btype
# create_revenue_table(n {0|1}, table_name {str}) -> returns an int
'''
Creates the frevenue_table. Returns:
0 if table was present
1 if table was not present and created
2 if table could not be made
n : pass 1 to recreate table
'''
def create_revenue_table(n = 0, table_name = 'revenue_table'):
r = 2
if isTablePresent(table_name) == False or n == 1:
try:
# delete old table if user selects to recreate data
tbldelete = "DROP TABLE IF EXISTS " + table_name
curs.execute(tbldelete)
# create table
tblcreate = "CREATE TABLE " + table_name + "(mode , username text, ticket_no text, date text, amount int(5), discount_or_penalty)"
curs.execute(tblcreate)
conn.commit()
r = 1
except:
r = 2
else:
r = 0
return r, table_name
# add_revenue(mode {'reservation'|'cancellation'}, username {str}, ticket_no {str}, amount {int}, discount_or_penalty {int}) -> returns bool
'''
Used to add revenue to revenue_table. Returns True if successfully recorded else False. For internal use.
'''
def add_revenue(mode, username, ticket_no, amount, discount_or_penalty = 0):
success = False
r1, revenueTName = create_revenue_table(0)
if r1 != 2:
try:
tblins = "INSERT INTO '" + revenueTName + "' values(?, ?, ?, ?, ?, ?)"
curs.execute(tblins, (mode, username, ticket_no, time.strftime('%d/%m/%Y'), amount, discount_or_penalty))
conn.commit()
success = True
except:
success = False
return success
# create_reservation_table(n {0|1}, table_name {str}) -> returns an int
'''
Creates the reservation_table. Returns:
0 if table was present
1 if table was not present and created
2 if table could not be made
n : pass 1 to recreate table
'''
def create_reservation_table(n = 0, table_name = 'reservation_table'):
r = 2
if isTablePresent(table_name) == False or n == 1:
try:
# delete old table if user selects to recreate data
tbldelete = "DROP TABLE IF EXISTS " + table_name
curs.execute(tbldelete)
# create table
tblcreate = "CREATE TABLE " + table_name + "(route_id char(5), bus_id char(5), username text, starting text, ending text, date text, seat_no int(3), amount int(5), ticket_no text PRIMARY KEY, reserved_on text)"
curs.execute(tblcreate)
conn.commit()
r = 1
except:
r = 2
else:
r = 0
return r, table_name
# makeTicket (bus_id {str}, starting {str}, ending {str}, date {str}, seat_no {int}) -> returns ticket number as string
'''
This method combines the inputs and route_id from given bus_id and provides a ticket number.
'''
def makeTicket(bus_id, starting, ending, date, seat_no):
route_id = getRouteFromBusID(bus_id)
ticket_no = 0
if route_id != '':
indices = validate_route(route_id, starting, ending) # get starting and ending indices
if indices != None:
d = ''.join(date.split('/')) # 13/07/2017 will be formatted to 13072017
# processing ticket
ticket_no = d + bus_id + '{:03d}'.format(seat_no) + route_id + 'F' + str(indices[0]+1) + 'T' + str(indices[1]+1)
return ticket_no
# isReservationPossible(bus_id {str}, starting {str}, ending {str}, date {str}, seat_no {int}) -> returns bool
'''
This method returns if a requested reservation overlaps with a previous reservation
Example: assume seat 20 is booked in S5 from Kolaghat to Kharagpur on 25/08/2017
mdb.isReservationPossible('S5', 'Kolkata', 'Midnapore', '25/08/2017', 20)
False
mdb.isReservationPossible('S5', 'Kolkata', 'Kolaghat', '25/08/2017', 20)
True
mdb.isReservationPossible('S5', 'Kolkata', 'Kolaghat', '25/08/2017', 110) # invalid seat
False
'''
def isReservationPossible(bus_id, starting, ending, date, seat_no):
possibility = False
route_id = getRouteFromBusID(bus_id)
r1, reserveTName = create_reservation_table(0)
if r1 != 2 and route_id != '' :
r2, bus_table_name = create_bus_table(0)
curs.execute("SELECT total_seats FROM " + bus_table_name + " WHERE bus_id='" + bus_id + "'")
total_seats = curs.fetchall()
total_seats = total_seats[0][0]
indices = validate_route(route_id, starting, ending)
if indices != None and calc.isValidTransactionDate(date) and 0 < seat_no <= total_seats:
try:
possibility = True
# getting probable clashable routes
tblcmd = "SELECT starting, ending FROM '" + reserveTName + "' WHERE bus_id='" + bus_id + "' AND seat_no='" + str(seat_no) + "' AND date='" + date + "'"
curs.execute(tblcmd)
similarReservations = curs.fetchall()
currentStartingIndex = indices[0]
currentEndingIndex = indices[1]
currentStops = set(range(currentStartingIndex, currentEndingIndex)) # a set is made with the range from starting index to ending index
for similar in similarReservations:
i = validate_route(route_id, similar[0], similar[1])
similarStartingIndex = i[0]
similarEndingIndex = i[1]
similarStops = set(range(similarStartingIndex, similarEndingIndex)) # a set is made for all similar reservations
# comparing the two sets. If no common is found, then reservation is possible
if len(currentStops & similarStops) != 0:
possibility = False
break
except:
pass
return possibility
# add_reservation(bus_id {str}, username {str}, starting {str}, ending {str}, date {str}, seat_no {int}, amount {int}) -> returns ticket number
'''
Used to add reservation records to reservation_table. Returns:
ticket_no if reservation was added
0 if reservation could not be added
Example:
mdb.add_reservation('S5', 'ag', 'Kolkata', 'Kolaghat', '25/08/2017', 20, 250)
'25082017S5020MID1F1T2'
mdb.add_reservation('S5', 'ag', 'Kolkata', 'Kolaghat', '25/08/2015', 20, 250) # invalid date
0
mdb.add_reservation('S5', 'ag', 'Kolkata', 'Delhi', '25/08/2017', 20, 250) #invalid route
0
mdb.add_reservation('S5', 'abc', 'Kolkata', 'Kolaghat', '25/08/2017', 20, 250) #username not registered
0
mdb.add_reservation('S5', 'ag', 'Kolkata', 'Kolaghat', '25/08/2017', 110, 250) #seat number not present
0
'''
def add_reservation(bus_id, username, starting, ending, date, seat_no, amount):
ticket_no = 0
r1, table_name = create_reservation_table(0)
r2, cancelTName = create_cancellation_table(0)
r3, user_activities_table = create_user_activities_table(0)
route_id = getRouteFromBusID(bus_id)
if r1 != 2 and r2 != 2 and r3 != 2 and route_id != '' and checkUsernamePresence(username, user_activities_table) and isReservationPossible(bus_id, starting, ending, date, seat_no):
ticket_no = makeTicket(bus_id, starting, ending, date, seat_no)
if ticket_no != 0:
try:
tblins = "INSERT INTO " + table_name + " values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
curs.execute(tblins, (route_id, bus_id, username, starting, ending, date, seat_no, amount, ticket_no, time.strftime("%d/%m/%Y")))
# delete from cancellation_table
try: curs.execute("DELETE FROM " + cancelTName + " WHERE ticket_no='" + ticket_no + "'")
except: pass
conn.commit()
# add to revenue
if add_revenue('reservation', username, ticket_no, amount, (getFare(bus_id, starting, ending) - amount)) == False:
print ('Error adding revenue.')
# add to user_activities
reservation_string = (ticket_no + '_' + time.strftime("%d/%m/%Y") + '_' + bus_id + '_' + starting + '_' + ending + '_' + date + '_' + str(seat_no) + '_' + str(amount))
if change_user_activity(username, 'reservations', reservation_string, 1) != 1:
print ('Error adding to user_activities.')
except: ticket_no = 0
return ticket_no
# create_cancellation_table(n {0|1}, table_name {str}) -> returns an int
'''
Creates the cancellation_table. Returns:
0 if table was present
1 if table was not present and created
2 if table could not be made
n : pass 1 to recreate table
'''
def create_cancellation_table(n = 0, table_name = 'cancellation_table'):
r = 2
if isTablePresent(table_name) == False or n == 1:
try:
# delete old table if user selects to recreate data
tbldelete = "DROP TABLE IF EXISTS " + table_name
curs.execute(tbldelete)
# create table
tblcreate = "CREATE TABLE " + table_name + "(cancellation_date text, username text, route_id char(5), bus_id char(5), starting text, ending text, reservation_date text, seat_no text, ticket_no text PRIMARY KEY, amount_forfeited int(3))"
curs.execute(tblcreate)
conn.commit()
r = 1
except:
r = 2
else:
r = 0
return r, table_name
# ticketDetails(ticket_no {str}, table_name) -> returns a tuple
'''
Verifies if an entry with the given ticket number is present in the table_name. Returns:
None if no entry was found with the given ticket number
a tuple with all information of the entry, if found
For internal use.
'''
def ticketDetails(ticket_no, table_name):
r = None
if init() != 2:
try:
tblcmd = "SELECT * FROM '" + table_name + "' WHERE ticket_no='" + ticket_no + "'"
curs.execute(tblcmd)
r = curs.fetchall()
r = None if r == [] else r[0]
except:
pass
return r
# add_cancellation(ticket_no {str}, amount_forfeited {int}) -> returns an int
'''
Used to add a cancellation record to cancellation_table. Also removes the specific entry from reservation_table. Returns:
0 if there is no reservation with the given ticket_no
1 if record was successfully processed
2 if there was any error
Example:
mdb.add_reservation('V10', 'src', 'Howrah', 'Durgapur', '14/08/2017', 35, 550)
'14082017V10035DUR2F1T2'
mdb.add_cancellation('14082017V10035DUR2F1T2', 50)
1
'''
def add_cancellation(ticket_no, amount_forfeited = 0):
r = 2
r1, cancelTName = create_cancellation_table(0)
r2, reservTName = create_reservation_table(0)
details = ticketDetails(ticket_no, reservTName)
if details == None:
r = 0
elif r1 != 2 and r2 != 2:
try:
username = details[2]
route_id = details[0]
bus_id = details[1]
starting = details[3]
ending = details[4]
reservation_date = details[5]
seat_no = details[6]
amount = details[7]
if calc.isValidTransactionDate(reservation_date):
# removing from reservation_table
tblremove = "DELETE FROM '" + reservTName + "' WHERE ticket_no='" + ticket_no + "'"
curs.execute(tblremove)
# adding to cancellation_table
tbladd = "INSERT INTO '" + cancelTName + "' values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
curs.execute(tbladd, (time.strftime("%d/%m/%Y"), username, route_id, bus_id, starting, ending, reservation_date, seat_no, ticket_no, amount_forfeited))
conn.commit()
# add to revenue_table
if add_revenue('cancellation', username, ticket_no, -(amount - amount_forfeited), amount_forfeited) != 1:
print('Error adding revenue.')
# add to user_activities
cancellation_string = ticket_no + '_' + time.strftime("%d/%m/%Y") + '_' + bus_id + '_' + starting + '_' + ending + '_' + reservation_date + '_' + str(seat_no) + '_' + str(amount)
if change_user_activity(username, 'cancellations', cancellation_string, 1) != 1:
print ('Error adding to user_activities.')
r = 1
else: r = -1
except: r = 2
return r
# create_user_details_table(n {0|1}, table_name {str}) -> returns an int
'''
Creates the user_details table to store personal information like name, password etc. Returns:
0 if table was present
1 if table was not present and created
2 if table could not be made
n : pass 1 to recreate table
'''
def create_user_details_table(n = 0, table_name = 'user_details'):
r = 2
if isTablePresent(table_name) == False or n == 1:
try:
# delete old table if user selects to recreate data
tbldelete = "DROP TABLE IF EXISTS " + table_name
curs.execute(tbldelete)
# create table
tblcreate = "CREATE TABLE " + table_name + "(name text, username text PRIMARY KEY, type char(5), password text, security_ques text, security_answer text, payments text)"
curs.execute(tblcreate)
conn.commit()
# add a default administrator account
dtlins = "INSERT INTO '" + table_name + "' values(?, ?, ?, ?, ?, ?, ?)"
curs.execute(dtlins, ('Administrator', 'admin', 'admin', 'admin', '', '', '')) # '' -> payment kept blank
conn.commit()
r = 1
except: r = 2
else:
r = 0
return r, table_name
# checkUsernamePresence(username {str}) -> returns bool
'''
Checks for the presence of a username in user_details table. All usernames must be unique.
Returns True if present else False
Example:
mdb.checkUsernamePresence('ad')
True
'''
def checkUsernamePresence(username, table_name = ''):
presence = False
r1 = 0
if table_name == '': r1, table_name = create_user_details_table(0)
if r1 != 2 and init() != 2:
try:
tblcmd = "SELECT username FROM '" + table_name + "'"
curs.execute(tblcmd)
usernames = curs.fetchall()
if (username,) in usernames:
presence = True
else: presence = False
except:
pass
return presence
# add_user(name {str}, username {str}, password {str}, security_ques {str}, security_answer {str}) -> returns an int
'''
Adds a user to user_details table. Returns:
0 if username was present and user can't be added
1 if username was not present and user successfully added
2 in case of error
Example:
mdb.add_user('Dummy user', 'ag', 'dup', 'demo_q', 'demo_a') # 'ag' username is already present
0
mdb.add_user('Dummy user', 'du', 'dup', 'demo_q', 'demo_a')
1
'''
def add_user(name, username, password, security_ques, security_answer):
r = 2
r1, userTName = create_user_details_table(0)
r2, userActivityTable = create_user_activities_table(0)
if r1 != 2 and r2 != 2:
if checkUsernamePresence(username, userTName) == False:
try:
# insert into user_details
dtlins = "INSERT INTO '" + userTName + "' values(?, ?, ?, ?, ?, ?, ?)"
curs.execute(dtlins, (name, username, 'cust', password, security_ques, security_answer, '')) # '' -> payment kept blank
# insert into user_activities
actins = "INSERT INTO '" + userActivityTable + "' values(?, ?, ?, ?, ?)"
curs.execute(actins, (username, '', '', '', ''))
conn.commit()
r = 1
except:
r = 2
else:
r = 0
return r
# ************** internal use only ****************
'''
This method adds or removes a given element from an object returned by curs.fetchall(). Returned is a string with line breaks.
source - data returned from curs.fetchall()
entry - the entry to be added to or removed from source
job - 1-> add entry to source, 2-> remove entry from source
Return:
2: error
1: success
-2: could not remove
'''
def entryAdditionRemoval(source, entry, job):
source = source[0][0]
r = 2
if job == 1:
if source == None or source == '':
source = entry
r = 1
else:
source = source.split('\n')
if entry not in source:
source.append(entry)
r = 1
else:
r = 0
source = '\n'.join(source)
source = source.strip()
elif job == 0:
if source == None:
pass
elif entry == '':
source = ''
elif entry == None:
source = None
else:
source = source.split('\n')
try:
source.remove(entry)
r = 1
except: r = -2
source = '\n'.join(source)
source = source.strip()
return r, source
# doesPasswordMatch(username {str}, password {str}) -> returns an int
'''
Used to verify if entered username matches with password. Returns:
1: match
-1: doesn't match
0: username not found
2: any other error
'''
def doesPasswordMatch(username, password):
r = 2
r1, userTName = create_user_details_table(0)
if r1 != 2:
if checkUsernamePresence(username, userTName):
try:
tblselect = "SELECT password FROM '" + userTName + "' WHERE username='" + username + "'"
curs.execute(tblselect)
passwd = curs.fetchall()
if passwd[0][0] == password: r = 1
else: r = -1
except: r = 2
else: r = 0
return r
# verifyAdmin(username {str}, password {str}) -> returns bool
'''
Used to verify if entered username and password matches with administrator. Returns True or False as the case may be.
'''
def verifyAdmin(username, password):
v = False
r1, table_name = create_user_details_table(0)
if r1 != 2 and doesPasswordMatch(username, password) == 1:
try:
curs.execute("SELECT type FROM " + table_name + " WHERE username='" + username + "'")
t = curs.fetchall()
t = t[0][0]
if t == 'admin': v = True
else: v = False
except: pass
return v
# change_user_payment(username {str}, password {str}, payment {str}, mode {0|1}) -> returns an int
'''
This method is used to add or remove payment options for a specified username. Returns:
0 if username is not found
1 if payment method is successfully added or removed
-1 if password is incorrect
-2 if payment method was already present and no changes were made (only for adding payment method)
-3 payment removal error
2 if there was any other error
mode = 1: add the payment method, 0: remove the payment method
Example:
mdb.change_user_payment('sr', 'srp', '4321-5678-1573-2389', 1)
1
'''
def change_user_payment(username, password, payment, mode = 1):
r = 2