· 5 years ago · Jul 13, 2020, 11:42 AM
1
2import random as HeavyMetal
3import sys as matrix
4import sqlite3
5
6conn = sqlite3.connect('card.s3db')
7cur = conn.cursor()
8cur.execute('''
9CREATE TABLE IF NOT EXISTS card (
10 id INTEGER,
11 number TEXT,
12 pin TEXT,
13 balance INTEGER DEFAULT 0,
14 PRIMARY KEY("id")
15)''')
16
17conn.commit()
18
19# To get data returned by SELECT query you can user fetchone(), fetchall() methods:
20# cur.execute('SOME SELECT QUERY')
21# cur.fetchone() # Returns the first row from the response
22# cur.fetchall() # Returns all rows from the response
23# conn.commit()
24
25emety = ''
26
27
28def insert_details(a, b, c=None):
29 global input_id, input_pin
30 if b is None: # это трансфер
31 cur.execute(f"UPDATE card SET balance = balance - {c} WHERE number = '{input_id}'") # отняли у отправителя
32 conn.commit() # страх.
33 cur.execute(f"UPDATE card SET balance = balance + {c} WHERE number = '{a}'") # добавили получателю
34 elif c is not None: # это Income
35 cur.execute(f"UPDATE card SET balance = balance + {c} WHERE number = '{a}' and pin = '{b}'")
36 else: # это создание нового аккаунта с 0-ым балансом.
37 cur.execute(f"INSERT INTO card (number, pin) VALUES ({a}, {b})")
38 conn.commit()
39
40
41input_id, input_pin = None, None
42balance = 0
43
44def card_check(): # сразу тут считываем и баланс на будущее
45 global input_id, input_pin, balance
46 input_id = input('Enter your card number:\n')
47 input_pin = input('Enter your PIN:\n')
48 for i, row in enumerate(cur.execute('SELECT number, pin, balance FROM card')):
49 if input_id in row and input_pin in row:
50 balance = row[-1]
51 print('\nYou have successfully logged in!\n')
52 return True
53 return False
54
55def lunh_controling(string):
56 if str(string).isdigit():
57 # Count control string.
58 number = str(string)[:-1]
59 total_count = number_sum(number)
60 value = int(total_count) + int(str(string)[-1])
61 # Control multiplicity 10
62 return (value % 10 == 0)
63 else:
64 return False
65
66def login_cycle():
67 global balance, input_id, input_pin
68 while True:
69 login_option = input('1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit\n')
70 if login_option == '1':
71 current_balance = balance
72 print(f'Balance: {current_balance}\n')
73 continue
74 if login_option == '2':
75 income = int(input('\nEnter income:\n'))
76 insert_details(input_id, input_pin, c=income)
77 balance += income
78 print('Income was added!\n')
79 continue
80 if login_option == '3':
81 transfer_id = input('\nTransfer\nEnter card number:\n')
82 if lunh_controling(transfer_id) is False:
83 print('Probably you made mistake in the card number. Please try again!\n')
84 continue
85 temp_transfer_id = (f'{transfer_id}',)
86 cur.execute('SELECT number FROM card')
87 if temp_transfer_id not in cur.fetchall():
88 print('Such a card does not exist.\n')
89 continue
90 else: # она есть в базе и работаем
91 money_to_transfer = int(input('Enter how much money you want to transfer:\n'))
92 if money_to_transfer > balance:
93 print('Not enough money!\n')
94 continue
95 else:
96 insert_details(transfer_id, b=None, c=money_to_transfer)
97 balance -= money_to_transfer
98 print('Success!\n')
99 continue
100 if login_option == '4': # Close account == Log out + DELETE FOREVER
101 cur.execute(f'DELETE FROM card WHERE number = {input_id}')
102 conn.commit()
103 print('The account has been closed!')
104 return True
105 if login_option == '5':
106 print('You have successfully logged out!\n')
107 return True
108 if login_option == '0':
109 _exit()
110 matrix.exit()
111
112
113def _exit():
114 print('\nBye!')
115
116
117def generate_id():
118 global emety
119 while True:
120 part_1 = '400000'
121 part_2_str_list = [str(HeavyMetal.randint(0, 9)) for x in range(9)]
122 unique_id1 = str(part_1) + str(emety.join(part_2_str_list))
123 unique_id = to_lunh(unique_id1)
124 break_count = 0
125 for i, row in enumerate(cur.execute('SELECT number, pin, balance FROM card')):
126 if unique_id in row:
127 break_count += 1
128 break # stops the for cycle ^^ not while
129 if break_count == 1:
130 continue
131 return unique_id
132
133
134def number_sum(string):
135 # find sum to all digits without ECC number
136 numbers = list(str(string))
137 number_sum = 0
138 lenght = len(numbers)
139 for x in range(0, lenght):
140 if x % 2 == 0:
141 number = (int(numbers[x]) * 2)
142 if int(number) > 9:
143 double_numbers = list(str(number))
144 number = int(double_numbers[0]) + int(double_numbers[1])
145 else:
146 number = (numbers[x])
147 number_sum += int(number)
148 return(number_sum)
149
150
151def to_lunh(string):
152 # Add control number.
153 if str(string).isdigit():
154 total_count = int(number_sum(string))
155 # Find control number
156 control = 0
157 while control < 10:
158 value = total_count + control
159 if (value % 10 == 0):
160 break
161 else:
162 control += 1
163 #Make new number
164 lunh_number = str(string) + str(control)
165 return(lunh_number)
166
167
168def new_card():
169 luhn_card_num = generate_id()
170 pin_code = str(HeavyMetal.randint(1000, 9999))
171 insert_details(luhn_card_num, pin_code) # БЛОК ДАННЫХ ОТПРАВЛЯЕТЬСЯ В БД!
172 return luhn_card_num, int(pin_code)
173
174
175while True:
176 selection = input('1. Create an account\n2. Log into account\n0. Exit\n')
177 check_list1 = ['0', '1', '2']
178 if selection == '1':
179 NEW_CARD_NUMBER, NEW_PIN = new_card()
180 print(f"""Your card has been created
181Your card number:
182{NEW_CARD_NUMBER}
183Your card PIN:
184{NEW_PIN}\n""")
185 continue
186 if selection == '2':
187 if card_check():
188 pass
189 else:
190 print('Wrong card number or PIN!\n')
191 if login_cycle():
192 continue
193 if selection == '0':
194 matrix.exit()