registration.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. from email import message
  2. import json
  3. # from urllib.request import Request
  4. from fastapi_login import LoginManager
  5. from fastapi import APIRouter, Form, Depends, HTTPException, File, UploadFile,Request
  6. from typing import List,Optional,Union
  7. from fastapi.responses import FileResponse
  8. from random import randint
  9. from fastapi.security import OAuth2PasswordRequestForm
  10. from app.models.models import Registration,User,User_information,Class_list,Class_name,Schools,Class_date,User_resume,Class_detail,User_point
  11. from app.api import deps
  12. from sqlalchemy.orm import Session
  13. from typing import Any, Dict
  14. import secrets
  15. from fastapi_login.exceptions import InvalidCredentialsException
  16. from fastapi_login import LoginManager
  17. from datetime import timedelta,datetime,date
  18. from jose import jwt
  19. from emails.template import JinjaTemplate
  20. from tortoise.queryset import Q
  21. from fastapi.responses import HTMLResponse
  22. import rpyc
  23. from app.log import my_log
  24. from app.api.classes import count_point
  25. registration = APIRouter()
  26. IMAGEDIR = "/var/www/ntcri/assets/resume_pic/"
  27. IMAGEDIR_short = "assets/resume_pic/"
  28. def send_email(
  29. email_to: str,
  30. token: str,
  31. subject_template: str = "",
  32. html_template: str = "",
  33. environment: Dict[str, Any] = {},
  34. ):
  35. # message = emails.Message(
  36. # subject=JinjaTemplate(subject_template),
  37. # html=JinjaTemplate(html_template),
  38. # mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
  39. # )
  40. subject=subject_template
  41. html=html_template
  42. mailobj={}
  43. mailobj['toaddr']=email_to
  44. mailobj['title']=subject
  45. mailobj['totext']=html
  46. conn = rpyc.connect("192.168.192.80", 12345)
  47. conn.root.mailto(mailobj)
  48. return {"message":f"send email"}
  49. @registration.post("/upload_user_resume_imgs")
  50. async def upload_user_resume_imgs(files:Optional[List[UploadFile]] = File(None),old_file:Optional[str]=None):
  51. files_url = []
  52. if old_file:
  53. old_list = eval(old_file)
  54. for file_name in old_list:
  55. files_url.append(file_name)
  56. if files :
  57. for file in files:
  58. contents = await file.read()
  59. #save the file
  60. with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
  61. f.write(contents)
  62. files_url.append(f"{IMAGEDIR_short}{file.filename}" )
  63. return files_url
  64. async def check_token(access_token: str):
  65. result = await User.filter(token=access_token).first()
  66. if not result:
  67. print("no access")
  68. return None
  69. user_id = result.id
  70. return user_id
  71. async def check_permissions(user_id):
  72. user = await User.get(id=user_id)
  73. if user.is_superuser:
  74. return True
  75. else:
  76. return False
  77. # @registration.get("/protected")
  78. # def protected_route(user_id=Depends(check_token)):
  79. # if not user_id:
  80. # return {"message": "no access"}
  81. # return {'user': user_id}
  82. @registration.get("/get_registration_class")
  83. async def get_registration_class(
  84. event_id : Optional[int] = None,
  85. check_user_id = Depends(check_token)
  86. ):
  87. #inform_list = await Registration.filter(event_id=event_id,is_del=0,reg_confirm=1).all() #use for 8/25 after
  88. check_list1 = await User.get(id = check_user_id).all()
  89. check_list2 = await Class_list.get(id = event_id).all()
  90. if 2!=check_list1.is_superuser:
  91. if check_list2.create_user_id !=check_user_id:
  92. return {"msg": "permissions denied", "code": 200,"registrations":[]}
  93. inform_list = await Registration.filter(event_id=event_id,is_del=0).all()
  94. class_data =[]
  95. for infor in inform_list:
  96. reg_data = {
  97. "event_id" : infor.event_id,
  98. "user_id" : infor.user_id,
  99. "is_attend" : infor.is_attend,
  100. "payment_status":infor.payment_status,
  101. "five_digits":infor.five_digits,
  102. "reg_confirm":infor.reg_confirm,
  103. }
  104. user = await User.get(id=infor.user_id)
  105. inform = await User_information.get(user_id=infor.user_id)
  106. reg_data["real_name"] = inform.name
  107. reg_data["phone"] = inform.phone
  108. reg_data["email"] = user.email
  109. class_data.append(reg_data )
  110. return {"msg": "success", "code": 200,"registrations":class_data}
  111. @registration.post("/update_registration_class")
  112. async def update_registration_class(
  113. event_id : Optional[int] ,
  114. user_id : Optional[int] ,
  115. is_attend : int = Form(default=None),
  116. payment_status : int = Form(default=None),
  117. reg_confirm : int = Form(default=None),
  118. five_digits : str = Form(default=None),
  119. check_user_id = Depends(check_token),
  120. ):
  121. #inform_list = await Registration.filter(event_id=event_id,is_del=0,reg_confirm=1,user_id=user_id).all() #use for 8/25 after
  122. inform_list = await Registration.filter(event_id=event_id,is_del=0,user_id=user_id).all()
  123. check_list1 = await User.get(id = check_user_id).all()
  124. check_list2 = await Class_list.get(id = event_id).all()
  125. if 2!=check_list1.is_superuser:
  126. if check_list2.create_user_id !=check_user_id:
  127. return {"msg": "permissions denied", "code": 500}
  128. class_data =[]
  129. for infor in inform_list:
  130. if is_attend is not None:
  131. infor.is_attend = is_attend
  132. if payment_status is not None:
  133. infor.payment_status = payment_status
  134. if reg_confirm is not None:
  135. infor.reg_confirm = reg_confirm
  136. if five_digits is not None :
  137. if len(five_digits)==5:
  138. infor.five_digits = five_digits
  139. if five_digits=='00000':
  140. infor.five_digits = None
  141. else:
  142. return {"msg": "five_digits must be five_digits", "code": 500}
  143. await infor.save()
  144. return {"msg": "success", "code": 200, "user_id": infor.user_id,"event_id": infor.event_id}
  145. @registration.get("/get_registration")
  146. async def get_registration(
  147. user_id = Depends(check_token),
  148. get_all : Optional[int] = None,
  149. event_id : Optional[int] = None,
  150. registration_id : Optional[int] = None,
  151. is_check : Optional[int] = None
  152. ):
  153. try :
  154. if not user_id :
  155. return {"msg": "please log in", "code": 200}
  156. if get_all:
  157. inform_list = Registration.all()
  158. else:
  159. inform_list = Registration.filter(user_id=user_id).all()
  160. if event_id:
  161. inform_list = inform_list.filter(event_id=event_id)
  162. if is_check != None:
  163. inform_list = inform_list.filter(reg_confirm=is_check)
  164. if registration_id:
  165. reg_list_tmp = await inform_list.filter(id=registration_id,is_del=0).all().order_by("-event_id","create_time")
  166. else:
  167. reg_list_tmp = await inform_list.filter(is_del=0).all().order_by("-event_id","create_time")
  168. reg_list = []
  169. for infor in reg_list_tmp:
  170. try :
  171. reg_data = {
  172. "Registration_id" : infor.id,
  173. "event_id" : infor.event_id,
  174. "user_id" : infor.user_id,
  175. "reg_confirm" : infor.reg_confirm,
  176. "create_time" : infor.create_time
  177. }
  178. except:
  179. reg_data = {
  180. "msg" : "fail to get data"
  181. }
  182. try:
  183. class_detail = await Class_detail.filter(class_list_id = infor.event_id)
  184. hours = 0.0
  185. for detail in class_detail:
  186. hours += float(detail.hour)
  187. reg_data["hours"] = hours
  188. except Exception as e:
  189. print(str(e))
  190. try :
  191. class_obj = await Class_list.get(id = infor.event_id)
  192. class_name_obj = await Class_name.get(id = class_obj.name_id)
  193. school_obj = await Schools.get(id = class_name_obj.school_id)
  194. reg_data["school_name"] = school_obj.name
  195. reg_data["class_name"] = class_name_obj.name
  196. reg_data["class_event"] = class_obj.event
  197. reg_data["start_time"] = str(class_obj.start_time)
  198. reg_data["end_time"] =str(class_obj.end_time)
  199. except Exception as e:
  200. await Registration.filter(id =infor.id).delete()
  201. reg_data = {
  202. "event_id" : infor.event_id,
  203. "msg" : "no this class (auto delete)"
  204. }
  205. reg_list.append(reg_data)
  206. continue
  207. try:
  208. user = await User.get(id=infor.user_id)
  209. inform = await User_information.get(user_id=infor.user_id)
  210. reg_data["real_name"] = inform.name
  211. reg_data["phone"] = inform.phone
  212. reg_data["email"] = user.email
  213. except Exception as e:
  214. reg_data["user_data"] = str(e)
  215. reg_list.append(reg_data)
  216. return {"msg": "success", "code": 200,"registrations":reg_list}
  217. except Exception as e:
  218. return {"msg": str(e), "code": 500}
  219. @registration.post("/input_information")
  220. async def input_information(
  221. name : str = Form(default=''),
  222. user_name : str = Form(default=''),
  223. birthday : date = Form(default=datetime.now().date()),
  224. gender : str = Form(default=''),
  225. phone : str = Form(default=''),
  226. address : str = Form(default=''),
  227. user_id = Depends(check_token),
  228. position: str = Form(default='[1]'),
  229. identity:str = Form(default='[]')
  230. ):
  231. try :
  232. if not user_id :
  233. return {"msg": "no access", "code": 200}
  234. position_list = json.loads(position)
  235. d = {"學員":0,"開課工藝家":0,"其他":0}
  236. if 1 in position_list:
  237. d["學員"] = 1
  238. if 2 in position_list:
  239. d["開課工藝家"] = 1
  240. if 3 in position_list:
  241. d["其他"] = 1
  242. infor,created = await User_information.get_or_create(
  243. user_id=user_id,
  244. defaults={
  245. 'name': name,
  246. 'birthday' :birthday,
  247. 'gender': gender,
  248. 'phone': phone,
  249. 'address': address,
  250. 'position': d,
  251. "identity": identity
  252. }
  253. )
  254. if not created:
  255. if name != '':
  256. infor.name = name
  257. if birthday != datetime.now().date():
  258. infor.birthday = birthday
  259. if gender != '':
  260. infor.gender = gender
  261. if phone != '':
  262. infor.phone = phone
  263. if address != '':
  264. infor.address = address
  265. if identity != None :
  266. infor.identity = identity
  267. if user_name != '':
  268. global user
  269. user = await User.get(id = user_id)
  270. user.username = user_name
  271. if position != '':
  272. infor.position = d
  273. await infor.save()
  274. await user.save()
  275. msg = "Update success"
  276. else :
  277. msg = "input success"
  278. return {"msg": "success", "code": 200, "user_inform_id": infor.id,"is_exist":not created}
  279. except Exception as e:
  280. return {"msg": str(e), "code": 500}
  281. @registration.post("/update_information")
  282. async def update_information(
  283. user_name : str = Form(default=''),
  284. name : str = Form(default=''),
  285. birthday : date = Form(default=None),
  286. gender : str = Form(default=''),
  287. phone : str = Form(default=''),
  288. address : str = Form(default=''),
  289. user_id = Depends(check_token),
  290. position : str = Form(default='[1]'),
  291. is_superuser : int = Form(default=None),
  292. identity : str = Form(default=None),
  293. change_user_id : int = Form(default=None)
  294. ):
  295. try :
  296. if not user_id :
  297. return {"msg": "no access", "code": 200}
  298. if change_user_id is None:
  299. change_user_id = user_id
  300. infor = await User_information.get(user_id = change_user_id)
  301. user = await User.get(id = change_user_id)
  302. operator = await User.get(id = user_id)
  303. position_list = json.loads(position)
  304. d = {"學員":0,"開課工藝家":0,"其他":0}
  305. if 1 in position_list:
  306. d["學員"] = 1
  307. if 2 in position_list:
  308. d["開課工藝家"] = 1
  309. if 3 in position_list:
  310. d["其他"] = 1
  311. if is_superuser != None :
  312. if is_superuser == 2:
  313. if operator.is_superuser != 2:
  314. return {"msg": "no access", "code": 500}
  315. user.is_superuser = is_superuser
  316. await user.save()
  317. if name != '':
  318. infor.name = name
  319. if birthday != None:
  320. infor.birthday = birthday
  321. if gender != '':
  322. infor.gender = gender
  323. if phone != '':
  324. infor.phone = phone
  325. if address != '':
  326. infor.address = address
  327. if user_name != '':
  328. user.username = user_name
  329. if position != '':
  330. infor.position = d
  331. if identity != None :
  332. infor.identity = identity
  333. await infor.save()
  334. await user.save()
  335. return {"msg": "success", "code": 200, "user_inform_id": infor.id}
  336. except Exception as e:
  337. return {"msg": str(e), "code": 500}
  338. @registration.get("/get_user_information")
  339. async def get_user_information(
  340. user_id = Depends(check_token),
  341. get_all : int = 0,
  342. get_detail_information : int = 1
  343. ):
  344. try:
  345. if not user_id :
  346. return {"msg": "no access", "code": 200}
  347. try:
  348. if get_all == 1:
  349. user_list = await User.all()
  350. else:
  351. user_list = await User.filter(id = user_id).all()
  352. except:
  353. return {"msg": "user table run fail", "code": 500}
  354. user_inform_list = []
  355. for user_obj in user_list:
  356. user_point = await User_point.get_or_none(user_id=user_obj.id)
  357. points = 0
  358. if user_point is not None :
  359. points = user_point.points
  360. user_inform = {
  361. "user_id" : user_obj.id,
  362. "user_name" : user_obj.username,
  363. "email" : user_obj.email,
  364. "points" : points,
  365. "is_superuser" :user_obj.is_superuser
  366. }
  367. if get_detail_information:
  368. try :
  369. inform = await User_information.get(user_id=user_obj.id)
  370. user_inform["name"] = inform.name
  371. user_inform["birthday"] = inform.birthday
  372. user_inform["gender"] = inform.gender
  373. user_inform["phone"] = inform.phone
  374. user_inform["address"] = inform.address
  375. user_inform["msg"] = "user information exist"
  376. user_inform["exist"] = True
  377. user_inform["position"] = inform.position
  378. user_inform["identify"] = inform.identity
  379. except:
  380. user_inform["msg"] = "no user information"
  381. user_inform["exist"] = False
  382. user_inform_list.append(user_inform)
  383. return {"msg":"success","code":200,"user_inform": user_inform_list}
  384. except Exception as e:
  385. return {"msg": str(e), "code": 500}
  386. # @registration.post("/update_superuser")
  387. # async def update_superuser(
  388. # change_id : int ,
  389. # is_superuser : int ,
  390. # user_id = Depends(check_token),
  391. # ):
  392. # if not user_id :
  393. # return {"msg": "no exit", "code": 200}
  394. # user = await User.get(id=user_id)
  395. # if user.is_superuser != 2:
  396. # return {"msg": "no access", "code": 200}
  397. # user_list = await User.filter(id = change_id).all()
  398. # for infor in user_list:
  399. # if is_superuser is not None:
  400. # infor.is_superuser = is_superuser
  401. # await infor.save()
  402. # return {"msg": "success", "code": 200}
  403. @registration.get("/change_class_reg_number")
  404. async def change_class_reg_number(
  405. event_id: int = 0,
  406. reduce_number : int = 1,
  407. check_in_time : bool = True
  408. ):
  409. try:
  410. if event_id:
  411. try:
  412. await Class_list.get(id = event_id)
  413. except Exception as e:
  414. return {"msg": "no this event", "code": 200}
  415. try:
  416. class_date = await Class_date.get(class_list_id = event_id)
  417. except Exception as e:
  418. return {"msg": "no this class' number limit", "code": 200}
  419. #確認是否在報名時間內
  420. if check_in_time:
  421. today = datetime.now()
  422. if today <= class_date.registration_end.replace(tzinfo=None) and today >= class_date.registration_start.replace(tzinfo=None):
  423. print("尚可報名")
  424. else :
  425. return {"msg": "未在報名時間內", "code": 200}
  426. #if class_date.amount_left ==0 and reduce_number>0:
  427. if class_date.amount_left ==0:
  428. return {"msg": "課程報名已滿", "code": 200,"amount_left":-1}
  429. elif class_date.amount_left == class_date.number_limit and reduce_number<0:
  430. return {"msg": "class is empty", "code": 200,"amount_left":class_date.amount_left }
  431. else:
  432. class_date.amount_left = class_date.amount_left-reduce_number
  433. await class_date.save()
  434. return {"msg": "success", "code": 200,"amount_left":class_date.amount_left}
  435. except Exception as e:
  436. return {"msg": str(e), "code": 500}
  437. @registration.post("/input_registration")
  438. async def input_registration(
  439. request : Request,
  440. event_id : int = Form(default=0),
  441. user_id = Depends(check_token)
  442. ):
  443. try :
  444. if not user_id :
  445. return {"msg": "please log in", "code": 500}
  446. try:
  447. event = await Class_list.get(id = event_id)
  448. class_name = await Class_name.get(id = event.name_id)
  449. except Exception as e:
  450. return {"msg": "no this event", "code": 500}
  451. # if check_if_id_exeit(User_information,user_inform_id):
  452. # return {"msg": "no user information", "code": 200}
  453. # if check_if_id_exeit(Class_list,event_id):
  454. # return {"msg": "no class list", "code": 200}
  455. try:
  456. user = await User_information.get(user_id=user_id)
  457. except:
  458. return {"msg": "no user information", "code": 500}
  459. try:
  460. existing_registration = await Registration.get(
  461. event_id=event_id,
  462. user_id=user_id
  463. )
  464. new_registration = existing_registration
  465. is_register = 0
  466. except:
  467. existing_registration = None
  468. if existing_registration is None:
  469. is_register = 1
  470. if is_register:
  471. amount_left_obj = await change_class_reg_number(event_id=event_id)
  472. msg = amount_left_obj["msg"]
  473. else:
  474. msg = "已經有報名過了"
  475. if msg == 'success':
  476. new_registration = await Registration.create(
  477. event_id=event_id,
  478. user_id=user_id,
  479. reg_confirm=0,
  480. is_del=0,
  481. create_time=datetime.now(),
  482. is_attend = 0,
  483. payment_status = 0
  484. )
  485. if event.create_user_id: # 取得課程創建者資料
  486. try:
  487. creater = await User.get(id=event.create_user_id)
  488. email = creater.email
  489. message = f"報名人姓名:{user.name}<br>報名課程名稱:{class_name.name}<br>場次名稱:{event.event}"
  490. subject = '報名通知'
  491. send_email(email,"",subject,message)
  492. except:
  493. print("creater no exixt,no sending email")
  494. try:
  495. user_email = await User.get(id=user_id)
  496. user_info = await User_information.get_or_none(user_id=user_id)
  497. email = user_email.email
  498. # message = f"親愛的學員{user.name}您好,<br>\
  499. # 恭喜您在工藝學校找到心儀的課程,課程名稱為:{class_name.name}!<br>\
  500. # 工藝老師正在確認您的報名資料,將盡快給您後續通知。<br>\
  501. # 若於開課前10日尚未收到通知,請將後台畫面、聯絡資訊等截圖寄送至客服信箱:<br>\
  502. # craftology@ntcri.gov.tw,以便客服為您查詢。<br>\
  503. # 註:此封信件為系統自動發送,請勿回信,謝謝。"
  504. with open("/var/www/ntcri/assets/edm/sign_up/index.html", 'r', encoding='utf-8') as html_file:
  505. html_template = html_file.read()
  506. message = html_template.replace("{username}",user_info.name)
  507. subject = '報名通知'
  508. send_email(email,"",subject,message)
  509. except:
  510. client_ip = request.client.host
  511. my_log("error",__name__,f"Client IP: {client_ip} - send email fail")
  512. return {"msg": msg, "code": 200,"new_registration_id":new_registration.id,"is_already_exist":not is_register}
  513. else:
  514. return {"msg": msg, "code": 200,"new_registration_id":None,"is_already_exist":not is_register}
  515. #new_registration = await Registration.get_or_create(
  516. # event_id = event_id,
  517. # user_id = user_id,
  518. # defaults = {
  519. # "reg_confirm" : 0,
  520. # "is_del" : 0 ,
  521. # "create_time" : datetime.now(),
  522. #
  523. # }
  524. #)
  525. #print(new_registration)
  526. #if new_registration[1]:
  527. #return {"msg": msg, "code": 200,"new_registration_id":new_registration[0].id,"is_already_exist":not new_registration[1]}
  528. #return {"msg": msg, "code": 200,"new_registration_id":new_registration.id,"is_already_exist":not is_register}
  529. except Exception as e:
  530. return {"msg": str(e), "code": 500}
  531. @registration.post("/confirm_reg")
  532. async def confirm_reg(
  533. #user_id = Depends(check_token),
  534. # request = Request,
  535. registration_id : int = 0
  536. ):
  537. try:
  538. try:
  539. registration_obj = await Registration.get(id=registration_id)
  540. except:
  541. return {"msg": "can't find registration", "code": 500}
  542. registration_obj.reg_confirm = 1
  543. await registration_obj.save()
  544. student = await User.get(id = registration_obj.user_id)
  545. student_info = await User_information.get(user_id = registration_obj.user_id)
  546. class_event = await Class_list.get(id = registration_obj.event_id)
  547. class_name = await Class_name.get(id = class_event.name_id)
  548. subject = "報名確認通知信"
  549. # message = f"報名人:{student_info.name}<br>課程名稱:{class_name.name}"
  550. # message = f'親愛的學員 {student_info.name}您好,<br>\
  551. # 感謝您報名課程:{class_name.name},<br>\
  552. # 課程費用完成付款後請聯絡您的工藝老師!<br>\
  553. # 以下是匯款資訊及聯絡方式:<br>\
  554. # (帳戶資訊)<br>\
  555. # (聯絡電話或e-mail)<br>\
  556. # *若需臨時改期請於開課前10日主動聯繫工藝老師,以便老師準備材料包數量<br>\
  557. # 註:此封信件為系統自動發送,請勿回信,謝謝。'
  558. with open("/var/www/ntcri/assets/edm/pass_sign_up/index.html", 'r', encoding='utf-8') as html_file:
  559. html_template = html_file.read()
  560. message = html_template.replace("{username}",student_info.name)
  561. message =message.replace("{classname}",class_name.name)
  562. try:
  563. send_email(student.email,"",subject,message)
  564. except:
  565. client_ip = "0.0.0.0"#request.client.host
  566. my_log("info",__name__,f"Client IP: {client_ip} - error to send email")
  567. return {"msg": "success", "code": 200,"registration_id":registration_obj.id}
  568. except Exception as e:
  569. return {"msg": str(e), "code": 500}
  570. @registration.post("/recover_registration")
  571. async def delete_registration(
  572. user_id = Depends(check_token),
  573. event_id : int = 0
  574. ):
  575. try:
  576. if not user_id :
  577. return {"msg": "please log in", "code": 200}
  578. registration_obj = await Registration.get(event_id=event_id,user_id=user_id)
  579. amount_left_obj = await change_class_reg_number(event_id=registration_obj.event_id)
  580. msg = amount_left_obj["msg"]
  581. if msg == "class is full":
  582. return {"msg": msg+" cannot recover registration", "code": 200}
  583. registration_obj.is_del = 0
  584. await registration_obj.save()
  585. return {"msg": msg, "code": 200}
  586. except Exception as e:
  587. return {"msg": str(e), "code": 500}
  588. @registration.post("/delete_registration")
  589. async def delete_registration(
  590. user_id = Depends(check_token),
  591. super_ad_input_user_id : int = 0,
  592. event_id : int = 0
  593. ):
  594. try:
  595. if not user_id :
  596. return {"msg": "please log in", "code": 200}
  597. if super_ad_input_user_id:
  598. registration_obj = await Registration.get(event_id=event_id,user_id=super_ad_input_user_id)
  599. else:
  600. registration_obj = await Registration.get(event_id=event_id,user_id=user_id)
  601. registration_obj.is_del = 1
  602. amount_left_obj = await change_class_reg_number(event_id=registration_obj.event_id,reduce_number=-1)
  603. msg = amount_left_obj["msg"]
  604. await registration_obj.save()
  605. return {"msg": msg , "code": 200}
  606. except Exception as e:
  607. return {"msg": str(e), "code": 500}
  608. @registration.post("/input_user_resume")
  609. async def input_user_resume(
  610. user_id = Depends(check_token),
  611. imgs = Depends(upload_user_resume_imgs),
  612. teacher_name : str = Form(default=''),
  613. work_type : str = Form(default=''),
  614. experience : str = Form(default=''),
  615. expertise : str = Form(default=''),
  616. license : str = Form(default=''),
  617. media : str = Form(default=''),
  618. introduction: str = Form(default='')
  619. ):
  620. try:
  621. if not user_id :
  622. return {"msg": "please log in", "code": 200}
  623. msg = ''
  624. user_resume, created = await User_resume.get_or_create(
  625. user_id = user_id,
  626. defaults = {
  627. "teacher_name": teacher_name,
  628. "work_type": work_type,
  629. "experience": experience,
  630. "expertise": expertise,
  631. "license": license,
  632. "media": media,
  633. "imgs": imgs,
  634. "introduction": introduction
  635. }
  636. )
  637. if not created:
  638. if teacher_name.strip() != '' :
  639. user_resume.teacher_name = teacher_name
  640. if work_type.strip() != '' :
  641. user_resume.work_type= work_type
  642. if experience.strip() != '' :
  643. user_resume.experience= experience
  644. if expertise.strip() != '' :
  645. user_resume.expertise= expertise
  646. if license.strip() != '' :
  647. user_resume.license= license
  648. if media.strip() != '' :
  649. user_resume.media= media
  650. if imgs != '[]' :
  651. user_resume.imgs= imgs
  652. if introduction.strip() != '' :
  653. user_resume.introduction= introduction
  654. await user_resume.save()
  655. msg = "Update success"
  656. else :
  657. msg = "input success"
  658. return {"msg": msg , "code": 200}
  659. except Exception as e:
  660. return {"msg": str(e), "code": 500}
  661. @registration.get("/get_user_resume")
  662. async def get_user_resume(
  663. user_id = Depends(check_token)
  664. ):
  665. try:
  666. if not user_id :
  667. return {"msg": "please log in", "code": 200}
  668. user_resume = await User_resume.get(user_id = user_id)
  669. data = user_resume.show_data()
  670. return {"msg": "success" , "code": 200,"user_resume":data}
  671. except Exception as e:
  672. return {"msg": str(e), "code": 500}
  673. @registration.post("/check_is_user")
  674. async def check_is_user(
  675. email : str = None
  676. ):
  677. try:
  678. try:
  679. await User.get(email=email,is_active=1)
  680. except:
  681. return {"msg": "error" , "code": 200,"result":"此使用者未註冊,請先去註冊"}
  682. return {"msg": "success" , "code": 200,"result":"此使用者已註冊,可以使用"}
  683. except Exception as e:
  684. return {"msg": str(e), "code": 500}
  685. @registration.post("/delete_user")
  686. async def get_user_resume(
  687. user_id : Optional[int] = None,
  688. check_user_id = Depends(check_token)
  689. ):
  690. try:
  691. #inform_list = await Registration.filter(event_id=event_id,is_del=0,reg_confirm=1).all() #use for 8/25 after
  692. check_list1 = await User.get(id = check_user_id).all()
  693. if 2!=check_list1.is_superuser:
  694. if check_list1.create_user_id !=check_user_id:
  695. return {"msg": "permissions denied", "code": 200,"registrations":[]}
  696. await User.filter(user_id = user_id).delete()
  697. return {"msg": "success" , "code": 200}
  698. except Exception as e:
  699. return {"msg": str(e), "code": 500}
  700. @registration.get("/get_registration_count")
  701. async def get_registration_count(
  702. class_id_list : str = None
  703. ):
  704. try:
  705. result = []
  706. distinct_class_name_ids = []
  707. if class_id_list :
  708. distinct_class_name_ids = eval(class_id_list)
  709. else:
  710. # 使用 Tortoise ORM 的 count 方法進行統計
  711. distinct_class_name_ids = await Registration.all().values_list('event_id')
  712. print(distinct_class_name_ids)
  713. for entry in distinct_class_name_ids:
  714. class_list = await Class_list.get_or_none(id = entry[0])
  715. class_name = await Class_name.get_or_none(id = class_list.name_id)
  716. if class_name != None :
  717. count = await Registration.filter(event_id=entry[0]).count()
  718. result.append({"class_name":class_name.name,"name_id":class_list.name_id,"event_id":entry[0],"count":count})
  719. return {"msg": "success" , "code": 200,"result":result}
  720. except Exception as e:
  721. return {"msg": str(e), "code": 500}