registration.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. import json
  2. from fastapi_login import LoginManager
  3. from fastapi import APIRouter, Form, Depends, HTTPException, File, UploadFile
  4. from typing import List,Optional,Union
  5. from fastapi.responses import FileResponse
  6. from random import randint
  7. from fastapi.security import OAuth2PasswordRequestForm
  8. from app.models.models import Registration,User,User_information,Class_list,Class_name,Schools,Class_date,User_resume
  9. from app.api import deps
  10. from sqlalchemy.orm import Session
  11. from typing import Any, Dict
  12. import secrets
  13. from fastapi_login.exceptions import InvalidCredentialsException
  14. from fastapi_login import LoginManager
  15. from datetime import timedelta,datetime,date
  16. from jose import jwt
  17. from emails.template import JinjaTemplate
  18. from tortoise.queryset import Q
  19. from fastapi.responses import HTMLResponse
  20. from app.api.users import manager
  21. registration = APIRouter()
  22. IMAGEDIR = "/var/www/ntcri/assets/resume_pic/"
  23. IMAGEDIR_short = "assets/resume_pic/"
  24. @registration.post("/upload_user_resume_imgs")
  25. async def create_upload_files(files:Optional[List[UploadFile]] = File(None)):
  26. files_url = []
  27. if files :
  28. for file in files:
  29. contents = await file.read()
  30. #save the file
  31. with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
  32. f.write(contents)
  33. files_url.append(f"{IMAGEDIR_short}{file.filename}" )
  34. return files_url
  35. async def check_token(access_token: str):
  36. result = await User.filter(token=access_token).first()
  37. if not result:
  38. print("no access")
  39. return None
  40. user_id = result.id
  41. return user_id
  42. async def check_permissions(user_id):
  43. user = await User.get(id=user_id)
  44. if user.is_superuser:
  45. return True
  46. else:
  47. return False
  48. # @registration.get("/protected")
  49. # def protected_route(user_id=Depends(check_token)):
  50. # if not user_id:
  51. # return {"message": "no access"}
  52. # return {'user': user_id}
  53. @registration.get("/get_registration")
  54. async def get_registration(
  55. user_id = Depends(check_token),
  56. get_all : Optional[int] = None,
  57. event_id : Optional[int] = None,
  58. registration_id : Optional[int] = None,
  59. is_check : Optional[int] = None
  60. ):
  61. try :
  62. if not user_id :
  63. return {"msg": "please log in", "code": 200}
  64. if get_all:
  65. inform_list = Registration.all()
  66. else:
  67. inform_list = Registration.filter(user_id=user_id).all()
  68. if event_id:
  69. inform_list = inform_list.filter(event_id=event_id)
  70. if is_check != None:
  71. inform_list = inform_list.filter(reg_confirm=is_check)
  72. if registration_id:
  73. reg_list_tmp = await inform_list.filter(id=registration_id,is_del=0).all().order_by("-event_id","create_time")
  74. else:
  75. reg_list_tmp = await inform_list.filter(is_del=0).all().order_by("-event_id","create_time")
  76. reg_list = []
  77. for infor in reg_list_tmp:
  78. try :
  79. reg_data = {
  80. "Registration_id" : infor.id,
  81. "event_id" : infor.event_id,
  82. "user_id" : infor.user_id,
  83. "reg_confirm" : infor.reg_confirm,
  84. "create_time" : infor.create_time
  85. }
  86. except:
  87. reg_data = {
  88. "msg" : "fail to get data"
  89. }
  90. try :
  91. class_obj = await Class_list.get(id = infor.event_id)
  92. class_name_obj = await Class_name.get(id = class_obj.name_id)
  93. school_obj = await Schools.get(id = class_name_obj.school_id)
  94. reg_data["school_name"] = school_obj.name
  95. reg_data["class_name"] = class_name_obj.name
  96. reg_data["class_event"] = class_obj.event
  97. reg_data["start_time"] = str(class_obj.start_time)
  98. reg_data["end_time"] =str(class_obj.end_time)
  99. except Exception as e:
  100. reg_data["class_data"] = str(e)
  101. try:
  102. user = await User.get(id=infor.user_id)
  103. inform = await User_information.get(user_id=infor.user_id)
  104. reg_data["real_name"] = inform.name
  105. reg_data["phone"] = inform.phone
  106. reg_data["email"] = user.email
  107. except Exception as e:
  108. reg_data["user_data"] = str(e)
  109. reg_list.append(reg_data)
  110. return {"msg": "success", "code": 200,"registrations":reg_list}
  111. except Exception as e:
  112. return {"msg": str(e), "code": 500}
  113. @registration.post("/input_information")
  114. async def input_information(
  115. name : str = Form(default=''),
  116. user_name : str = Form(default=''),
  117. birthday : date = Form(default=datetime.now().date()),
  118. gender : str = Form(default=''),
  119. phone : str = Form(default=''),
  120. address : str = Form(default=''),
  121. user_id = Depends(check_token),
  122. position: str = Form(...),
  123. ):
  124. try :
  125. if not user_id :
  126. return {"msg": "no access", "code": 200}
  127. position_list = json.loads(position)
  128. d = {"學員":0,"開課工藝家":0,"其他":0}
  129. if 1 in position_list:
  130. d["學員"] = 1
  131. if 2 in position_list:
  132. d["開課工藝家"] = 1
  133. if 3 in position_list:
  134. d["其他"] = 1
  135. print(d)
  136. inform = await User_information.get_or_create(
  137. user_id=user_id,
  138. defaults={
  139. 'name': name,
  140. 'birthday' :birthday,
  141. 'gender': gender,
  142. 'phone': phone,
  143. 'address': address,
  144. 'position': d,
  145. }
  146. )
  147. if user_name != '':
  148. user = await User.get(id = user_id)
  149. user.username = user_name
  150. await user.save()
  151. return {"msg": "success", "code": 200, "user_inform_id": inform[0].id,"is_exist":not inform[1]}
  152. except Exception as e:
  153. return {"msg": str(e), "code": 500}
  154. @registration.post("/update_information")
  155. async def update_information(
  156. user_name : str = Form(default=''),
  157. name : str = Form(default=''),
  158. birthday : date = Form(default=datetime.now().date()),
  159. gender : str = Form(default=''),
  160. phone : str = Form(default=''),
  161. address : str = Form(default=''),
  162. user_id = Depends(check_token),
  163. position : str = Form(default=''),
  164. ):
  165. try :
  166. if not user_id :
  167. return {"msg": "no access", "code": 200}
  168. infor = await User_information.get(user_id = user_id)
  169. user = await User.get(id = user_id)
  170. position_list = json.loads(position)
  171. d = {"學員":0,"開課工藝家":0,"其他":0}
  172. if 1 in position_list:
  173. d["學員"] = 1
  174. if 2 in position_list:
  175. d["開課工藝家"] = 1
  176. if 3 in position_list:
  177. d["其他"] = 1
  178. if name != '':
  179. infor.name = name
  180. if birthday != datetime.now().date():
  181. infor.birthday = birthday
  182. if gender != '':
  183. infor.gender = gender
  184. if phone != '':
  185. infor.phone = phone
  186. if address != '':
  187. infor.address = address
  188. if user_name != '':
  189. user.username = user_name
  190. if position != '':
  191. infor.position = d
  192. await infor.save()
  193. await user.save()
  194. return {"msg": "success", "code": 200, "user_inform_id": infor.id}
  195. except Exception as e:
  196. return {"msg": str(e), "code": 500}
  197. @registration.get("/get_user_information")
  198. async def get_user_information(
  199. user_id = Depends(check_token),
  200. get_all : int = 0,
  201. get_detail_information : int = 1
  202. ):
  203. try:
  204. if not user_id :
  205. return {"msg": "no access", "code": 200}
  206. try:
  207. if get_all:
  208. user_list = await User.all()
  209. else:
  210. user_list = await User.filter(id = user_id)
  211. except:
  212. return {"msg": "user table run fail", "code": 500}
  213. user_inform_list = []
  214. for user_obj in user_list:
  215. user_inform = {
  216. "user_id" : user_obj.id,
  217. "user_name" : user_obj.username,
  218. "email" : user_obj.email
  219. }
  220. if get_detail_information:
  221. try :
  222. inform = await User_information.get(user_id=user_obj.id)
  223. user_inform["name"] = inform.name
  224. user_inform["birthday"] = inform.birthday
  225. user_inform["gender"] = inform.gender
  226. user_inform["phone"] = inform.phone
  227. user_inform["address"] = inform.address
  228. user_inform["msg"] = "user information exist"
  229. user_inform["exist"] = True
  230. user_inform["position"] = inform.position
  231. except:
  232. user_inform["msg"] = "no user information"
  233. user_inform["exist"] = False
  234. user_inform_list.append(user_inform)
  235. print(user_inform_list)
  236. return {"msg":"success","code":200,"user_inform": user_inform_list}
  237. except Exception as e:
  238. return {"msg": str(e), "code": 500}
  239. @registration.get("/change_class_reg_number")
  240. async def change_class_reg_number(
  241. event_id: int = 0,
  242. reduce_number : int = 1
  243. ):
  244. try:
  245. if event_id:
  246. try:
  247. await Class_list.get(id = event_id)
  248. except Exception as e:
  249. return {"msg": "no this event", "code": 200}
  250. try:
  251. class_date = await Class_date.get(class_list_id = event_id)
  252. except Exception as e:
  253. return {"msg": "no this class' number limit", "code": 200}
  254. if class_date.amount_left ==0 and reduce_number>0:
  255. return {"msg": "class is full", "code": 200,"amount_left":-1}
  256. elif class_date.amount_left == class_date.number_limit and reduce_number<0:
  257. return {"msg": "class is empty", "code": 200,"amount_left":class_date.amount_left }
  258. else:
  259. class_date.amount_left = class_date.amount_left-reduce_number
  260. await class_date.save()
  261. return {"msg": "success", "code": 200,"amount_left":class_date.amount_left}
  262. except Exception as e:
  263. return {"msg": str(e), "code": 500}
  264. @registration.post("/input_registration")
  265. async def input_registration(
  266. event_id : int = Form(default=0),
  267. user_id = Depends(check_token)
  268. ):
  269. try :
  270. if not user_id :
  271. return {"msg": "please log in", "code": 500}
  272. try:
  273. await Class_list.get(id = event_id)
  274. except Exception as e:
  275. return {"msg": "no this event", "code": 500}
  276. # if check_if_id_exeit(User_information,user_inform_id):
  277. # return {"msg": "no user information", "code": 200}
  278. # if check_if_id_exeit(Class_list,event_id):
  279. # return {"msg": "no class list", "code": 200}
  280. try:
  281. await User_information.get(user_id=user_id)
  282. except:
  283. return {"msg": "no user information", "code": 500}
  284. new_registration = await Registration.get_or_create(
  285. event_id = event_id,
  286. user_id = user_id,
  287. defaults = {
  288. "reg_confirm" : 0,
  289. "is_del" : 0 ,
  290. "create_time" : datetime.now()
  291. }
  292. )
  293. if new_registration[1]:
  294. amount_left_obj = await change_class_reg_number(event_id=event_id)
  295. msg = amount_left_obj["msg"]
  296. else:
  297. msg = "already registrate"
  298. return {"msg": msg, "code": 200,"new_registration_id":new_registration[0].id,"is_already_exist":not new_registration[1]}
  299. except Exception as e:
  300. return {"msg": str(e), "code": 500}
  301. @registration.post("/confirm_reg")
  302. async def confirm_reg(
  303. #user_id = Depends(check_token),
  304. registration_id : int
  305. ):
  306. try:
  307. registration_obj = await Registration.get(id=registration_id)
  308. registration_obj.reg_confirm = 1
  309. await registration_obj.save()
  310. return {"msg": "success", "code": 200,"registration_id":registration_obj.id}
  311. except Exception as e:
  312. return {"msg": str(e), "code": 500}
  313. @registration.post("/recover_registration")
  314. async def delete_registration(
  315. user_id = Depends(check_token),
  316. event_id : int = 0
  317. ):
  318. try:
  319. if not user_id :
  320. return {"msg": "please log in", "code": 200}
  321. registration_obj = await Registration.get(event_id=event_id,user_id=user_id)
  322. amount_left_obj = await change_class_reg_number(event_id=registration_obj.event_id)
  323. msg = amount_left_obj["msg"]
  324. if msg == "class is full":
  325. return {"msg": msg+" cannot recover registration", "code": 200}
  326. registration_obj.is_del = 0
  327. await registration_obj.save()
  328. return {"msg": msg, "code": 200}
  329. except Exception as e:
  330. return {"msg": str(e), "code": 500}
  331. @registration.post("/delete_registration")
  332. async def delete_registration(
  333. user_id = Depends(check_token),
  334. super_ad_input_user_id : int = 0,
  335. event_id : int = 0
  336. ):
  337. try:
  338. if not user_id :
  339. return {"msg": "please log in", "code": 200}
  340. if super_ad_input_user_id:
  341. registration_obj = await Registration.get(event_id=event_id,user_id=super_ad_input_user_id)
  342. else:
  343. registration_obj = await Registration.get(event_id=event_id,user_id=user_id)
  344. registration_obj.is_del = 1
  345. amount_left_obj = await change_class_reg_number(event_id=registration_obj.event_id,reduce_number=-1)
  346. msg = amount_left_obj["msg"]
  347. await registration_obj.save()
  348. return {"msg": msg , "code": 200}
  349. except Exception as e:
  350. return {"msg": str(e), "code": 500}
  351. @registration.post("/input_user_resume")
  352. async def input_user_resume(
  353. user_id = Depends(check_token),
  354. teacher_name : str = Form(default=''),
  355. work_type : str = Form(default=''),
  356. experience : str = Form(default=''),
  357. expertise : str = Form(default=''),
  358. license : str = Form(default=''),
  359. media : str = Form(default=''),
  360. imgs : str = Form(default='[]'),
  361. introduction: str = Form(default='')
  362. ):
  363. try:
  364. if not user_id :
  365. return {"msg": "please log in", "code": 200}
  366. msg = ''
  367. user_resume, created = await User_resume.get_or_create(
  368. user_id = user_id,
  369. defaults = {
  370. "teacher_name": teacher_name,
  371. "work_type": work_type,
  372. "experience": experience,
  373. "expertise": expertise,
  374. "license": license,
  375. "media": media,
  376. "imgs": imgs,
  377. "introduction": introduction
  378. }
  379. )
  380. if not created:
  381. if teacher_name.strip() != '' :
  382. user_resume.teacher_name = teacher_name
  383. if work_type.strip() != '' :
  384. user_resume.work_type= work_type
  385. if experience.strip() != '' :
  386. user_resume.experience= experience
  387. if license.strip() != '' :
  388. user_resume.license= license
  389. if media.strip() != '' :
  390. user_resume.media= media
  391. if imgs | imgs.strip() != '[]' :
  392. user_resume.imgs= imgs
  393. if introduction.strip() != '' :
  394. user_resume.introduction= introduction
  395. await user_resume.save()
  396. msg = "Update success"
  397. else :
  398. msg = "input success"
  399. return {"msg": msg , "code": 200}
  400. except Exception as e:
  401. return {"msg": str(e), "code": 500}
  402. @registration.get("/get_user_resume")
  403. async def get_user_resume(
  404. user_id = Depends(check_token)
  405. ):
  406. try:
  407. if not user_id :
  408. return {"msg": "please log in", "code": 200}
  409. user_resume = await User_resume.get(user_id = user_id)
  410. data = user_resume.show_data()
  411. return {"msg": "success" , "code": 200,"user_resume":data}
  412. except Exception as e:
  413. return {"msg": str(e), "code": 500}