Advertisement
Guest User

Untitled

a guest
Dec 12th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.05 KB | None | 0 0
  1. import sqlite3
  2. import string
  3.  
  4. import pandas as pd
  5. import seaborn as sns
  6. from matplotlib import lines
  7. import matplotlib.pyplot as plt
  8. from email_validator import validate_email, EmailNotValidError
  9.  
  10. SalesDataFull = pd.ExcelFile("SalesDataFull.xlsx")
  11. conn = sqlite3.connect('OS_employee.db')
  12. OrdersOnlyData = SalesDataFull.parse("Orders")
  13.  
  14. def checkChoice():
  15. print("Welcome to Office Solutions")
  16. choice = input("Existing user?")
  17. while choice != 'no' and choice != 'yes' and choice != "x":
  18. choice = input("Error. Please enter yes/no or x to Exit: ")
  19. if choice == "yes":
  20. login()
  21. elif choice == "no":
  22. register()
  23. elif choice == "x":
  24. print("Thank you for visiting Office Solutions.")
  25. exit()
  26.  
  27. def login():
  28. with conn:
  29. cur = conn.cursor()
  30. try:
  31. loginTest = False # main condition to loop if email and password not met
  32. while not loginTest: # wrong email loopy
  33. userEmail = input("Email please: ")
  34. userEmail = userEmail.lower().replace(" ", "")
  35. userPassword = input("Password: ").strip()
  36. cur.execute(
  37. "SELECT COUNT (*) FROM Employee WHERE(Email= '" + userEmail.lower() + "' AND Password= '" + userPassword + "')")
  38. results = cur.fetchone() # return very first thing it finds that matches
  39. print(results[0]) # print first thing
  40. if results[0] == 1:
  41. print("Login successful")
  42. loginTest = True
  43. else:
  44. print("Login Unsuccessful")
  45. existingUser = input("Existing user?[yes/no]")
  46. if existingUser == "no":
  47. register()
  48. except:
  49. print("connection failed")
  50.  
  51. def emailCheck():
  52. Email = input("Email: ")
  53. while Email:
  54. try:
  55. v = validate_email(Email)
  56. break
  57. except EmailNotValidError:
  58. print("Error")
  59. Email = input("Email: ")
  60. #check email duplication
  61. with conn:
  62. cur = conn.cursor()
  63. try:
  64. cur.execute("SELECT COUNT (*) FROM Employee WHERE(Email = '" + Email + "')")
  65. results = cur.fetchone()
  66. while results[0] == 1:
  67. Email = input("Email existed. Please enter again: ")
  68. cur.execute("SELECT COUNT (*) FROM Employee WHERE(Email = '" + Email + "')")
  69. results = cur.fetchone()
  70. return Email
  71. except:
  72. print("Connected Failed")
  73.  
  74. def EmployeeID_DuplicationCheck():
  75. with conn:
  76. cur = conn.cursor()
  77. try:
  78. EmployeeID = input("Enter New Employee ID: ")
  79. while EmployeeID == "":
  80. EmployeeID = input("What's your Employee ID:")
  81. # check EmployeeID duplication
  82. cur.execute("SELECT COUNT (*) FROM Employee WHERE(EmployeeID = '" + EmployeeID + "')")
  83. results = cur.fetchone()
  84. while results[0] == 1:
  85. EmployeeID = input("EmployeeID existed. Please enter again: ")
  86. cur.execute("SELECT COUNT (*) FROM Employee WHERE(EmployeeID = '" + EmployeeID + "')")
  87. results = cur.fetchone()
  88. return EmployeeID
  89. except sqlite3.Error as e:
  90. print(e)
  91.  
  92. def register():
  93. with conn:
  94. cur = conn.cursor()
  95. try:
  96. EmployeeID = EmployeeID_DuplicationCheck()
  97.  
  98. FirstName = input("What's your first name:")
  99. while FirstName == "":
  100. FirstName = input("What's your first name:")
  101.  
  102. LastName = input("What's your last name: ")
  103. while LastName == "":
  104. LastName = input("What's your last name:")
  105.  
  106. email = emailCheck()
  107.  
  108. password = input("Enter a password: ")
  109. while password == "":
  110. password = input("Enter a password: ")
  111. cur.execute("""
  112. INSERT INTO Employee (EmployeeID, FirstName, LastName,Email, Password) VALUES (?, ?, ?, ?, ?)""",
  113. (EmployeeID, FirstName, LastName, email, password))
  114. cur.execute('select * from employee where EmployeeId=?', (EmployeeID,))
  115. results = cur.fetchall()
  116. print(results)
  117. # After registering, user is sent back to the main page.
  118. print("You have been successfully registered!\n")
  119. except:
  120. print("Connected Failed")
  121.  
  122.  
  123. def totalProfit_month():
  124. #total profit by month
  125. ProfitDataMonth = OrdersOnlyData
  126. ProfitDataMonth["Profit"] = ProfitDataMonth["Profit"].sum()
  127. ProfitDataMonth["Month"] = ProfitDataMonth["Order Date"].dt.month
  128. MonthlyProfit = ProfitDataMonth[["Month", "Profit"]]
  129. MonthlyProfitSum = MonthlyProfit.groupby(by="Month").sum()
  130. MonthlyProfitSum['Profit'] = MonthlyProfitSum['Profit'].map("{:.2f}".format)
  131. MonthlyProfitSum['Profit'] = pd.np.where(MonthlyProfitSum['Profit'].astype(float)
  132. < 0, '-$' + MonthlyProfitSum['Profit'].astype(str).str[1:],
  133. '$' + MonthlyProfitSum['Profit'].astype(str))
  134. print(MonthlyProfitSum)
  135. MonthlyProfitSum = MonthlyProfitSum.reset_index()
  136. #barchart
  137. barchart_mostProfitable_month = sns.barplot(x="Month", y="Profit", data=MonthlyProfit[["Month", "Profit"]])
  138. barchart_mostProfitable_month.set_title("Sales by Profit")
  139.  
  140. #piechart
  141. # labels = ProfitDataMonth
  142. # sizes = [ProfitDataMonth[["Month", "Profit"]]]
  143. #
  144. # fig1, ax1 = plt.subplots()
  145. # ax1.pie(sizes, labels=labels,
  146. # shadow=True, startangle=90)
  147. # ax1.axis('equal')
  148. plt.show()
  149.  
  150. def Overallprofit_region():
  151. OrdersOnlyData = SalesDataFull.parse("Orders")
  152. profit_region = OrdersOnlyData[["Region", "Profit"]]
  153. overall_prof = profit_region.groupby(by="Region").sum().sort_values(by="Profit", ascending=False)
  154. print("\nThese are the total profits for each region: ")
  155. print(overall_prof.head(4))
  156.  
  157. prof_cols_sub = OrdersOnlyData[["Region", "Profit"]]
  158. prof_cols_sub.groupby("Region").sum().plot(kind="bar")
  159. plt.show()
  160.  
  161. #Data display part
  162. #montly most profitable product
  163. def mostProfitable_month():
  164. OrdersOnlyData = SalesDataFull.parse("Orders")
  165. df_month = OrdersOnlyData["Order Date"].dt.month
  166. OrdersOnlyData["Month"] = df_month
  167. month = int(input("Enter month (1-12): "))
  168. while not (1 <= month <= 12):
  169. print("Invalid Month")
  170. month = int(input("Enter month (1-12): "))
  171. month_profit_headers = OrdersOnlyData[['Month', 'Product Name', 'Profit']]
  172. month_profit_sum = month_profit_headers.groupby(['Product Name']).sum().sort_values(by='Profit', ascending=True).reset_index()
  173. print("The 10 least profitable products ")
  174. month_profit_sum['Profit'] = month_profit_sum['Profit'].map("{:.2f}".format)
  175. month_profit_sum['Profit'] = pd.np.where(month_profit_sum['Profit'].astype(float)
  176. < 0, '-$' + month_profit_sum['Profit'].astype(str).str[1:],
  177. '$' + month_profit_sum['Profit'].astype(str))
  178. print("10 least profitable product by month")
  179. print(month_profit_sum.tail(10).round(2))
  180. print(lines)
  181.  
  182.  
  183. # OrdersOnlyData = ProfitableData
  184. # OrdersOnlyData["Month"] = OrdersOnlyData["Order Date"].dt.month
  185. # month_profit_headers = OrdersOnlyData[["Product Name", "Profit"]]
  186. # month_profit_sum = month_profit_headers.groupby(by="Profit").sum().sort_values(by="Profit", ascending=False).head(10).round(2)
  187. # month_profit_sum = month_profit_sum.reset_index()
  188. # print("10 most profitable product by month")
  189. # print(month_profit_sum)
  190. # print("--------------")
  191.  
  192. #10 least profitable product
  193. def leastProfitable_month():
  194. OrdersOnlyData = SalesDataFull.parse("Orders")
  195. df_month = OrdersOnlyData["Order Date"].dt.month
  196. OrdersOnlyData["Month"] = df_month
  197. month = int(input("Enter month (1-12): "))
  198. while not (1 <= month <= 12):
  199. print("Invalid Month")
  200. month = int(input("Enter month (1-12): "))
  201. month_profit_headers = OrdersOnlyData[['Month', 'Product Name', 'Profit']]
  202. month_profit_sum = month_profit_headers.groupby(['Product Name']).sum().sort_values(by='Profit', ascending=False).reset_index()
  203. print("The 10 least profitable products ")
  204. month_profit_sum['Profit'] = month_profit_sum['Profit'].map("{:.2f}".format)
  205. month_profit_sum['Profit'] = pd.np.where(month_profit_sum['Profit'].astype(float)
  206. < 0, '-$' + month_profit_sum['Profit'].astype(str).str[1:], '$' + month_profit_sum['Profit'].astype(str))
  207. print("10 least profitable product by month")
  208. print(month_profit_sum.tail(10).round(2))
  209. print(lines)
  210.  
  211.  
  212. #def state():
  213. def stateTopProfit():
  214. states = OrdersOnlyData.State.unique()
  215. for pos_state in states:
  216. state_select = OrdersOnlyData.loc[OrdersOnlyData["State"] == pos_state]
  217. state_prof = state_select[["State", "Product Name", "Profit"]]
  218. best_state = state_prof.groupby("Product Name").sum().sort_values(by="Profit", ascending=True).reset_index()
  219. print("\nBest Product(s) in {} ".format(pos_state))
  220. print("--------------------------------------------")
  221. print(best_state.head(5).round(2))
  222.  
  223. def stateLeastProfit():
  224. states = OrdersOnlyData.State.unique()
  225. for neg_state in states:
  226. state_select = OrdersOnlyData.loc[OrdersOnlyData["State"] == neg_state]
  227. state_prof = state_select[["State", "Product Name", "Profit"]]
  228. worse_state = state_prof.groupby("Product Name").sum().sort_values(by="Profit").reset_index()
  229. print("\nWorst Product(s) in {} ".format(neg_state))
  230. print("--------------------------------------------")
  231. print(worse_state.tail(5).round(2))
  232.  
  233.  
  234. #def quarter():
  235. # def mostProfitable_quarter():
  236. # df_quarter = OrdersOnlyData["Order Date"].dt.quarter
  237. # OrdersOnlyData["Quarter"] = df_quarter
  238. # month_profit_headers = OrdersOnlyData[['Quarter', 'Product Name', 'Profit']]
  239. # month_profit_sum = month_profit_headers.groupby(by=['Quarter']).sum().sort_values(by='Profit', ascending=False).reset_index()
  240. # quarter = int(input("Enter quarter (1, 2, 3, 4): "))
  241. #
  242. # while not (1 <= quarter <= 4):
  243. # print("Invalid entry, please try again")
  244. # quarter = int(input("Enter quarter: (1, 2, 3, 4"))
  245. # print([month_profit_sum['Quarter'] == quarter])
  246. #
  247. # if quarter == 1:
  248. # print("The 10 most profitable products ")
  249. # quarter1Profit_most = df_quarter.loc[month_profit_sum['Quarter'] == df_quarter].head(10).round(2)
  250. # print(quarter1Profit_most)
  251. #
  252. # elif quarter == 2:
  253. # print("The 10 most profitable products ")
  254. # quarter2Profit_most = df_quarter.loc[month_profit_sum['Quarter'] == df_quarter].head(10).round(2)
  255. # print(quarter2Profit_most)
  256. #
  257. # elif quarter == 3:
  258. # print("The 10 most profitable products ")
  259. # quarter3Profit_most = df_quarter.loc[month_profit_sum['Quarter'] == df_quarter].head(10).round(2)
  260. # print(quarter3Profit_most)
  261. #
  262. # elif quarter == 4:
  263. # print("The 10 most profitable products ")
  264. # quarter4Profit_most = df_quarter.loc[month_profit_sum['Quarter'] == df_quarter].head(10).round(2)
  265. # print(quarter4Profit_most)
  266. #
  267. #
  268. # def leastProfitable_quarter():
  269. # df_quarter = OrdersOnlyData["Order Date"].dt.quarter
  270. # OrdersOnlyData["Quarter"] = df_quarter
  271. # month_profit_headers = OrdersOnlyData[['Quarter', 'Product Name', 'Profit']]
  272. # month_profit_sum = month_profit_headers.groupby(by=['Quarter']).sum().sort_values(by='Profit', ascending=False).reset_index()
  273. #
  274. # quarter = int(input("Enter quarter (1, 2, 3, 4): "))
  275. #
  276. # while not (1 <= quarter <= 4):
  277. # print("Invalid entry, please try again")
  278. # quarter = int(input("Enter quarter: (1, 2, 3, 4"))
  279. # print([month_profit_sum['Quarter'] == quarter])
  280. #
  281. # if quarter == 1:
  282. # print("The 10 least profitable products ")
  283. # quarter1Profit_most = df_quarter.loc[month_profit_sum['Quarter'] == df_quarter].tail(10).round(2)
  284. # print(quarter1Profit_most)
  285. #
  286. # elif quarter == 2:
  287. # print("The 10 least profitable products ")
  288. # quarter2Profit_most = df_quarter.loc[month_profit_sum['Quarter'] == df_quarter].tail(10).round(2)
  289. # print(quarter2Profit_most)
  290. #
  291. # elif quarter == 3:
  292. # print("The 10 least profitable products ")
  293. # quarter3Profit_most = df_quarter.loc[month_profit_sum['Quarter'] == df_quarter].tail(10).round(2)
  294. # print(quarter3Profit_most)
  295. #
  296. # elif quarter == 4:
  297. # print("The 10 least profitable products ")
  298. # quarter4Profit_most = df_quarter.loc[month_profit_sum['Quarter'] == df_quarter].tail(10).round(2)
  299. # print(quarter4Profit_most)
  300. #
  301. #
  302.  
  303. #def city():
  304.  
  305. totalProfit_month()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement