0% found this document useful (0 votes)
6 views11 pages

Electricity Bill Management System

The document is a Python script for an Electricity Bill Management System that connects to a MySQL database. It includes functionalities for user login, customer registration, bill generation, payment processing, and complaint management. The script also features validation functions and logging mechanisms for tracking user actions and errors.

Uploaded by

sit23cs088
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

Electricity Bill Management System

The document is a Python script for an Electricity Bill Management System that connects to a MySQL database. It includes functionalities for user login, customer registration, bill generation, payment processing, and complaint management. The script also features validation functions and logging mechanisms for tracking user actions and errors.

Uploaded by

sit23cs088
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Untitled-1

1 import random as rd

2 import tabulate as tb

3 import datetime as dt

4 import [Link] as my

5 print("✦"*45)

6 print('\t ELECTRICITY BILL MANAGEMENT')

7 print("✦"*45)

8 #Connecting python with mysql interface

9 try:

10
con=[Link](host='localhost',user='root',password='Praham@123',database='electricity_bill')

11 except [Link] as err:

12 print(f"Error: Could not connect to Database {err}")

13 exit() # Exit the Program if connection fails

14

15 #Function for logging in

16 def login():

17 while True:

18 a=input('Are you an Employee or a Customer - ').strip().lower()

19 if a not in ['employee','customer']:

20 print(" Invalid Input ")

21 continue

22 if a=='employee':

23 loginusernameandpass­
()

24 p='select role from logins where username=%s and passw=%s and role in
("admin","user")'

25 c=[Link]()

26 [Link](p,(un,pw))

27 rs=[Link]()

28 if rs:

29 role=rs[0]

30 if role=='admin':

31 admin_menu()

32 elif role=='user':

33 continue

34 else:
35 print('Invalid Employee Credentials')

36

37 elif a=='customer':

38 r=input('Do you have an account - ').strip().lower()

39 if r in ('yes','y'):

40 loginusernameandpass­
()

41 p='select role from logins where username=%s and passw=%s and role="user"'

42 c=[Link]()

43 [Link](p,(un,pw))

44 rs=[Link]()

45 if rs:

46 user_menu()

47 else:

48 print('Invalid Customer Credentials')

49 elif r in ('no','n'):

50 register_customer()

51 else:

52 print(" Invalid Input ")

53 break

54

55 def logcus(message):

56 try:

57 with open('log_customer.txt','a') as lgf:

58 t=[Link]().strftime("%d-%m-%y %H:%M:%S")

59 [Link](f"[{t}] {message}\n")

60 except IOError as e:

61 print(f"Error writing to log file: {e}")

62 def loginusernameandpass­
():

63 while True:

64 print('\t LOGIN')

65 un = input('Enter UserName : ').strip()

66 if not validate_username(un):

67 print("Invalid username. Please try again.")

68 continue # Go back to asking for the username and password

69

70 pw = input('Enter Password : ').strip()

71 if not validate_password(pw):

72 print("Invalid password. Please try again.")


73 continue # Go back to asking for the username and password

74

75 # If both username and password are valid, break out of the loop

76 print("Login successful!")

77 break # Exit the loop if login is successful

78 def logbill(message):

79 try:

80 with open('log_bills.txt','a') as lf:

81 t=[Link]().strftime("%d-%m-%y %H:%M:%S")

82 [Link](f"[{t}] {message}\n")

83 except IOError as e:

84 print(f"Error writing to log file: {e}")

85

86 def logcomp(message):

87 try:

88 with open('log_complaints.txt','a') as fi:

89 t=[Link]().strftime("%d-%m-%y %H:%M:%S")

90 [Link](f"[{t}] {message}\n")

91 except IOError as e:

92 print(f"Error writing to log file: {e}")

93

94 def show_tables(head,data):

95 table=[Link](data, headers=head, tablefmt='github',colalign=('left',),stralign=


('left',))

96 print(table)

97

98 def validate_password(password):

99 if len(password)<8:

100 print('Password must atleast be 8-characters long')

101 return False

102 return True

103 def validate_username(username):

104 if len(username)<3:

105 print('Username must be at least 3-characters long')

106 return False

107 if not [Link]():

108 print("Username can only contain letters and numbers")

109 return False


110 return True

111 def validate_phone(phone_number):

112 if phone_number.isdigit() and len(phone_number)==10:

113 return True

114 print("Invalid Phone Number -> It should be 10 Digits")

115 return False

116 def showadmins():

117 c1=[Link]()

118 [Link]('Select username,passw from logins where role="admin"')

119 res=[Link]()

120 print(' ','-'*48)

121 print(' List of Admins')

122 print(' ','-'*48)

123 head=['Usernames','Passwords']

124 show_tables(head,res)

125

126 def register_customer():

127 print("\t REGISTER NEW CUSTOMER ")

128 try:

129 while True:

130 un = input('Enter your Username: ').strip()

131 if not validate_username(un):

132 continue # Ask for username again if invalid

133

134 # Check if the username already exists in the logins table

135 c = [Link]()

136 [Link]("SELECT username FROM logins WHERE username = %s", (un,))

137 existing_user = [Link]()

138

139 if existing_user:

140 print("Username has already been taken. Please choose a different one.")

141 continue # Ask for username again

142 else:

143 break # If username is available, proceed

144

145 pw = input('Enter your Password: ').strip()

146 if not validate_password(pw):

147 return
148

149 # Insert new customer into the logins table

150 p = "INSERT INTO logins (username, passw) VALUES (%s, %s)"

151 val = (un, pw)

152 [Link](p, val)

153 [Link]()

154 print('\t CUSTOMER ACCOUNT SUCCESSFULLY CREATED ')

155 user_menu()

156

157 except [Link] as err:

158 print(f"Error: Could Not create customer account - {err}")

159

160 def admin_menu():

161 while True:

162 print("-"*50)

163 print("\t CHOOSE AN OPERATION")

164 print("-"*50)

165 print("Press 1 - Add a New Customer")

166 print("Press 2 - Deleting an Existing Customer")

167 print("Press 3 - Show all Customers")

168 print("Press 4 - Generate the Bill")

169 print("Press 5 - Mark The Bill As Paid")

170 print("Press 6 - Show All Unpaid Bills")

171 print("Press 7 - Show Complaints")

172 print("Press 8 - Mark As Rectified")

173 print("Press 9 - Show Admins")

174 print("Press 10 - Quit")

175 try:

176 ch=int(input("Enter Your Choice : "))

177 except ValueError:

178 print("Invalid Output - Please enter a Valid Choice Number")

179 continue

180 if ch==1:

181 addcustomer()

182 elif ch==2:

183 delcustomer()

184 elif ch==3:

185 showcustomers()
186 elif ch==4:

187 generatebill()

188 elif ch==5:

189 paybill()

190 elif ch==6:

191 showunpaid()

192 elif ch==7:

193 scomplaints()

194 elif ch==8:

195 markrect()

196 elif ch==9:

197 showadmins()

198 elif ch==10:

199 break

200 else:

201 print('Invalid Choice')

202 def user_menu():

203 while True:

204 print("-"*50)

205 print("\t CHOOSE AN OPERATION")

206 print("-"*50)

207 print("Press 1 - Pay the Bill")

208 print("Press 2 - Generate the Bill")

209 print("Press 3 - Raise Complaints")

210 print("Press 4 - Quit")

211 try:

212 ch=int(input("Enter Your Choice : "))

213 except ValueError:

214 print('Invalid Choice - Enter a Valid Choice Number')

215 continue

216 if ch==1:

217 paybill()

218 elif ch==2:

219 generatebill()

220 elif ch==3:

221 rscomplaints()

222 elif ch==4:

223 break
224 else:

225 print('Invalid Choice')

226

227 def delcustomer():

228 print("*"*50)

229 print('\t DELETING A CUSTOMER')

230 print("*"*50)

231 try:

232 cd=input('Enter Customer Id : ')

233 c3=[Link]()

234 q="delete from customers where customer_id=%s"

235 [Link](q,(cd,))

236 [Link]()

237 print(' CUSTOMER SUCCESSFULLY DELETED ')

238 except [Link] as err:

239 print(f"Error: Could not delete the customer {err}")

240

241 def addcustomer():

242 print("*"*50)

243 print('\t WELCOME TO ELECTRICITY MANAGEMENT ')

244 print("*"*50)

245 try:

246 q='select customer_id from customers'

247 c=[Link]()

248 [Link](q)

249 x=[Link]()

250 def custid():

251 return [Link](10000,99999)

252 cd=custid()

253 while (cd,) in x:

254 cd=custid()

255 cname=input('Enter Customer Name : ')

256 addr=input('Enter Customer Address : ')

257 pho=input('Enter Phone Number : ')

258 if not validate_phone(pho):

259 return

260 email=input('Enter Email : ')

261 mtr=input('Enter Meter Number: ')


262 print("Your Customer ID : ",cd)

263 print()

264 c4=[Link]()

265 q='Insert into customers values (%s,%s,%s,%s,%s,%s)'

266 val=(cd,cname,addr,pho,email,mtr)

267 [Link](q,val)

268 [Link]()

269 print(' CUSTOMER SUCCESSFULLY ADDED ')

270 logcus(f"NEW CUSTOMER - Customer ID: {cd},Name: {cname}, Address: {addr}, Phone:
{pho}, Email: {email}, Meter No: {mtr}")

271 user_menu()

272 except [Link] as err:

273 print(f"Error: Could not add the customer {err}")

274 logcus(f"Failed to add customer - Name : {cname} Error: {err}")

275 except ValueError:

276 print('Invalid Input')

277

278 def showcustomers():

279 c5=[Link]()

280 [Link]('Select customer_id,customer_name,phone_number,meter_no,email from customers')

281 res=[Link]()

282 print(" ","-"*48)

283 print(" CUSTOMER DETAILS " )

284 print(" ","-"*48)

285 headers=["ID","NAME","PHONE","METER NO","EMAIL"]

286 show_tables(headers,res)

287

288 def generatebill():

289 try:

290 name=input('Enter Name: ')

291 bid=input('Enter the Bill_ID : ')

292 mtr=input('Enter Meter Number : ')

293 dt=input("Enter the date of Bill Generation : ")

294 cunits=int(input('Enter Current Units on Meter : '))

295 punits=int(input('Enter Previous Units on Meter : '))

296 consumed=cunits-punits

297 if consumed<200:

298 bill=4*consumed
299 elif consumed<400:

300 bill=6*consumed

301 else:

302 bill=8*consumed

303 print("Total Units Consumed : ",consumed)

304 print("Total Amount to be paid : ",bill)

305 duedt=input('Enter the Due Date of Payment : ')

306 q="Insert into bills values(%s,%s,%s,%s,%s,%s,%s,%s,'No')"

307 val=(bid,mtr,dt,cunits,punits,consumed,bill,duedt)

308 c6=[Link]()

309 [Link](q,val)

310 print(" BILL GENERATED SUCCESSFULLY !! ")

311 [Link]()

312 logbill(f"Generated bill for {name} - BILL ID: {bid}, METER NO: {mtr}, UNIT CONSUMED :
{consumed}, AMOUNT: {bill}, DUE DATE: {duedt}")

313 except [Link] as err:

314 print(f"Error: Could not generate bill {err}")

315 logbill(f"Failed to generate bill for Meter No: {mtr} Error: {err}")

316 except ValueError:

317 print('Invalid Input')

318 except TypeError:

319 print("Invalid Input")

320

321 def showunpaid():

322 c7=[Link]()

323 [Link]('Select meter_no,bill_date,total_amount,due_date from bills where paid="No"')

324 res=[Link]()

325 if res==[]:

326 print('------------NO UNPAID BILLS------------')

327 else:

328 print(" ","-"*40)

329 print(" LIST OF UNPAID BILLS ")

330 print(" ","-"*40)

331 headers=["METER NO","BILL DATE","TOTAL AMOUNT","DUE DATE"]

332 show_tables(headers,res)

333

334 def paybill():

335 try:
336 c8=[Link]()

337 mtr=input('Enter the Meter Number : ')

338 bdate=input('Enter the bill date for the bill to be paid : ')

339 mp=input('Please Select The Mode of Payment (Cash/Cheque/Card) : ')

340 if [Link]()=='cash':

341 mo=float(input('Enter the amount : '))

342 print('₹ ',mo,' received')

343 print(" -------------------------TRANSACTION COMPLETE------------------------- ")

344 q="update bills set paid='Yes' where bill_date<%s and %s<due_date and meter_no=%s"

345 val=(bdate,bdate,mtr)

346 [Link](q,val)

347 [Link]()

348 except [Link] as err:

349 print(f"Error: Could not mark the bill as paid {err}")

350 except ValueError:

351 print('Invalid Input')

352 except TypeError:

353 print('Invalid Input')

354

355 def rscomplaints():

356 try:

357 a=input("Enter Customer ID : ")

358 b=input("Enter your Complaint : ")

359 c=[Link]()

360 q='insert into complaints (Customer_ID,complaints) values (%s,%s)'

361 val=(a,b)

362 [Link](q,val)

363 [Link]()

364 print(' COMPLAINT SUCCESSFULLY GIVEN ')

365 logcomp(f"Complaint raised by Customer ID: {a}. Complaint : {b}")

366 except [Link] as err:

367 print(f"Error: Could not register Complaint {err}")

368 logcomp(f"Error: Failed to register complaint for Customer ID: {a}. Error: {err}")

369 except ValueError:

370 print('Invalid Input')

371

372 def scomplaints():

373 c=[Link]()
374 [Link]("Select customer_id,complaints from complaints where rectified='No'")

375 res=[Link]()

376 if res==[]:

377 print('------------NO UNRECTIFIED COMPLAINTS------------')

378 else:

379 print(" ","-"*40)

380 print(" LIST OF UNRECTIFIED COMPLAINTS ")

381 print(" ","-"*40)

382 headers=["CUSTOMER_ID","COMPLAINTS"]

383 show_tables(headers,res)

384

385 def markrect():

386 c=[Link]()

387 q="update complaints set rectified='Yes'"

388 [Link](q)

389 print(" -------------------------COMPLAINT RECTIFIED------------------------- ")

390 [Link]()

391

392 try:

393 login()

394 except Exception as err:

395 print(f"Unexpected Error Occured: {err}")

396

You might also like