user.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import csv
  2. from . import DBBit
  3. from .db import DB
  4. from tool.type_ import *
  5. from tool.login import create_uid, randomPassword
  6. from tool.time_ import mysql_time
  7. from core.user import NormalUser, ManagerUser, User
  8. from conf import Config
  9. from . import garbage
  10. def update_user_score(where: str, score: score_t, db: DB) -> int:
  11. if len(where) == 0 or score < 0:
  12. return -1
  13. cur = db.update(table="user", kw={"score": score}, where=where)
  14. if cur is None:
  15. return -1
  16. return cur.rowcount
  17. def update_user_reputation(where: str, reputation: score_t, db: DB) -> int:
  18. if len(where) == 0 or reputation <= 1 or reputation >= 1000:
  19. return -1
  20. cur = db.update(table="user", kw={"Reputation": reputation}, where=where)
  21. if cur is None:
  22. return -1
  23. return cur.rowcount
  24. def search_user_by_fields(columns, uid: uid_t, name: uname_t, phone: phone_t, db: DB):
  25. where = ""
  26. if uid is not None:
  27. where += f"UserID=‘{uid}’ AND "
  28. if name is not None:
  29. where += f"Name='{name}' AND "
  30. if phone is not None:
  31. where += f"Phone='{phone}' AND "
  32. if len(where) != 0:
  33. where = where[0:-4] # 去除末尾的AND
  34. return search_from_user_view(columns, where, db)
  35. def search_from_user_view(columns, where: str, db: DB):
  36. cur = db.search(columns=columns,
  37. table="user",
  38. where=where)
  39. if cur is None:
  40. return None
  41. return cur.fetchall()
  42. def find_user_by_id(uid: uid_t, db: DB) -> Optional[User]:
  43. cur = db.search(columns=["UserID", "Name", "IsManager", "Score", "Reputation"],
  44. table="user",
  45. where=f"UserID = '{uid}'")
  46. if cur is None or cur.rowcount == 0:
  47. return None
  48. assert cur.rowcount == 1
  49. res = cur.fetchone()
  50. assert len(res) == 5
  51. uid: uid_t = res[0]
  52. name: uname_t = str(res[1])
  53. manager: bool = res[2] == DBBit.BIT_1
  54. if manager:
  55. return ManagerUser(name, uid)
  56. else:
  57. score: score_t = res[3]
  58. reputation: score_t = res[4]
  59. rubbish: count_t = garbage.count_garbage_by_time(uid, db)
  60. return NormalUser(name, uid, reputation, rubbish, score) # rubbish 实际计算
  61. def find_user_by_name(name: uname_t, passwd: passwd_t, db: DB) -> Optional[User]:
  62. uid = create_uid(name, passwd)
  63. return find_user_by_id(uid, db)
  64. def is_user_exists(uid: uid_t, db: DB) -> bool:
  65. cur = db.search(columns=["UserID"],
  66. table="user",
  67. where=f"UserID = '{uid}'")
  68. if cur is None or cur.rowcount == 0:
  69. return False
  70. assert cur.rowcount == 1
  71. return True
  72. def update_user(user: User, db: DB, not_commit: bool = False) -> bool:
  73. if not is_user_exists(user.get_uid(), db):
  74. return False
  75. uid = user.get_uid()
  76. info: Dict[str, str] = user.get_info()
  77. is_manager = info['manager']
  78. if is_manager == '1':
  79. cur = db.update(table="user",
  80. kw={"IsManager": is_manager},
  81. where=f"UserID = '{uid}'", not_commit=not_commit)
  82. else:
  83. score = info['score']
  84. reputation = info['reputation']
  85. cur = db.update(table="user",
  86. kw={"IsManager": is_manager,
  87. "Score": f"{score}",
  88. "Reputation": f"{reputation}"},
  89. where=f"UserID = '{uid}'", not_commit=not_commit)
  90. return cur is not None
  91. def create_new_user(name: Optional[uname_t], passwd: Optional[passwd_t], phone: phone_t,
  92. manager: bool, db: DB) -> Optional[User]:
  93. if name is None:
  94. name = f'User-{phone[-6:]}'
  95. if passwd is None:
  96. passwd = randomPassword()
  97. if len(phone) != 11:
  98. return None
  99. uid = create_uid(name, passwd)
  100. if is_user_exists(uid, db):
  101. return None
  102. is_manager = '1' if manager else '0'
  103. cur = db.insert(table="user",
  104. columns=["UserID", "Name", "IsManager", "Phone", "Score", "Reputation", "CreateTime"],
  105. values=f"'{uid}', '{name}', {is_manager}, '{phone}', {Config.default_score}, "
  106. f"{Config.default_reputation}, {mysql_time()}")
  107. if cur is None:
  108. return None
  109. if is_manager:
  110. return ManagerUser(name, uid)
  111. return NormalUser(name, uid, Config.default_reputation, 0, Config.default_score)
  112. def get_user_phone(uid: uid_t, db: DB) -> Optional[str]:
  113. cur = db.search(columns=["Phone"], table="user", where=f"UserID = '{uid}'")
  114. if cur is None or cur.rowcount == 0:
  115. return None
  116. assert cur.rowcount == 1
  117. return cur.fetchall()[0]
  118. def del_user(uid: uid_t, db: DB) -> bool:
  119. cur = db.search(columns=["GarbageID"], table="garbage_time", where=f"UserID = '{uid}'") # 确保没有引用
  120. if cur is None or cur.rowcount != 0:
  121. return False
  122. cur = db.delete(table="user", where=f"UserID = '{uid}'")
  123. if cur is None or cur.rowcount == 0:
  124. return False
  125. assert cur.rowcount == 1
  126. return True
  127. def del_user_from_where_scan(where: str, db: DB) -> int:
  128. cur = db.search(columns=["UserID"], table="user", where=where)
  129. if cur is None:
  130. return -1
  131. return cur.rowcount
  132. def del_user_from_where(where: str, db: DB) -> int:
  133. cur = db.search(columns=["GarbageID"], table="garbage_time", where=where) # 确保没有引用
  134. if cur is None or cur.rowcount != 0:
  135. return False
  136. cur = db.delete(table="user", where=where)
  137. if cur is None:
  138. return -1
  139. return cur.rowcount
  140. def creat_user_from_csv(path, db: DB) -> List[User]:
  141. res = []
  142. with open(path, "r") as f:
  143. reader = csv.reader(f)
  144. first = True
  145. name_index = 0
  146. passwd_index = 0
  147. phone_index = 0
  148. manager_index = 0
  149. for item in reader:
  150. if first:
  151. try:
  152. name_index = item.index('Name')
  153. passwd_index = item.index('Passwd')
  154. phone_index = item.index('Phone')
  155. manager_index = item.index('Manager')
  156. except (ValueError, TypeError):
  157. return []
  158. first = False
  159. continue
  160. name = item[name_index]
  161. passwd = item[passwd_index]
  162. phone = item[phone_index]
  163. if item[manager_index].upper() == "TRUE":
  164. is_manager = True
  165. elif item[manager_index].upper() == "FALSE":
  166. is_manager = False
  167. else:
  168. continue
  169. user = create_new_user(name, passwd, phone, is_manager, db)
  170. if user is not None:
  171. res.append(user)
  172. return res
  173. def creat_auto_user_from_csv(path, db: DB) -> List[User]:
  174. res = []
  175. with open(path, "r") as f:
  176. reader = csv.reader(f)
  177. first = True
  178. phone_index = 0
  179. for item in reader:
  180. if first:
  181. try:
  182. phone_index = item.index('Phone')
  183. except (ValueError, TypeError):
  184. return []
  185. first = False
  186. continue
  187. phone = item[phone_index]
  188. user = create_new_user(None, None, phone, False, db)
  189. if user is not None:
  190. res.append(user)
  191. return res