Advertisement
Guest User

Untitled

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