classes.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  1. from fastapi import APIRouter, Form, Depends, HTTPException, File, UploadFile
  2. from typing import List,Optional
  3. from fastapi.responses import FileResponse
  4. from random import randint
  5. from fastapi.security import OAuth2PasswordRequestForm
  6. from app.models.models import User,User_information,Favorite_course,Article_list,Class_date,Attend_record,One_day_class,Outter_class_list
  7. from app.models.models import Class_list,Schools,Class_detail,Class_name,Registration,Group_name,Online_course
  8. from app.api import deps
  9. from sqlalchemy.orm import Session
  10. from typing import Any, Dict
  11. import secrets
  12. from fastapi_login.exceptions import InvalidCredentialsException
  13. from fastapi_login import LoginManager
  14. from datetime import timedelta,datetime
  15. from app.config import settings
  16. from pathlib import Path
  17. from jose import jwt
  18. from emails.template import JinjaTemplate
  19. from tortoise.queryset import Q
  20. from fastapi.responses import HTMLResponse
  21. import requests
  22. import json
  23. from itertools import chain
  24. from tortoise import fields
  25. from datetime import datetime
  26. classes = APIRouter()
  27. async def check_token(access_token: str):
  28. result = await User.filter(token=access_token).first()
  29. if not result:
  30. print("no access")
  31. return None
  32. user_id = result.id
  33. return user_id
  34. IMAGEDIR = "/var/www/ntcri/assets/"
  35. IMAGEDIR_short = "assets/"
  36. async def check_token(access_token: str):
  37. result = await User.filter(token=access_token).first()
  38. if not result:
  39. print("no access")
  40. return None
  41. user_id = result.id
  42. return user_id
  43. async def update_location_time(location_id: int):
  44. if location_id:
  45. school = await Schools.get(id=location_id)
  46. school.update_time = datetime.now()
  47. await school.save()
  48. return {"msg": "success", "code": 200}
  49. @classes.post("/insert_school")
  50. async def insert_school(
  51. location_name: str = Form(default=''),
  52. Lng: str = Form(default=''),
  53. Lat: str = Form(default=''),
  54. address : str = Form(default=''),
  55. introduction : str = Form(default=''),
  56. email : str = Form(default=''),
  57. phone : str = Form(default=''),
  58. access_token:str = Form(default=None)
  59. ):
  60. try:
  61. user_id = None
  62. if access_token:
  63. user_id = await check_token(access_token)
  64. new_school = await Schools.create(
  65. name=location_name,
  66. longitude=Lng,
  67. latitude=Lat,
  68. address = address,
  69. update_time = datetime.now(),
  70. introduction = introduction ,
  71. email= email,
  72. phone = phone,
  73. create_user_id = user_id
  74. )
  75. return {"msg": "success", "code": 200, "location_id": new_school.id}
  76. except Exception as e:
  77. return {"msg": str(e), "code": 500}
  78. @classes.post("/insert_class_name")
  79. async def insert_class_name(
  80. name: str = Form(default=''),
  81. location_id: int = Form(default=1),
  82. category: str = Form(default='詳細 請至觀看課程資訊 查看'),
  83. introduction: str = Form(default='詳細 請至觀看課程資訊 查看'),
  84. organizer: str = Form(default='詳細 請至觀看課程資訊 查看'),
  85. cover_img_file:UploadFile = File(default=''),
  86. group_id : int = Form(default=1),
  87. group_sort :str = Form(default='詳細 請至觀看課程資訊 查看'),
  88. recommend: int = Form(default=0),
  89. special_class_list_name : str = Form(default=None),
  90. is_inner : int = Form(default=1),
  91. is_check : int = Form(default=1),
  92. access_token:str = Form(default=None)
  93. ):
  94. try:
  95. cover_img = ''
  96. if cover_img_file != '':
  97. contents = await cover_img_file.read()
  98. #save the file
  99. with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
  100. f.write(contents)
  101. cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
  102. user_id = None
  103. if access_token:
  104. user_id = await check_token(access_token)
  105. new_class_name = await Class_name.create(
  106. name=name,
  107. school_id=location_id,
  108. category=category,
  109. introduction=introduction,
  110. organizer=organizer,
  111. cover_img=cover_img,
  112. group_id=group_id,
  113. group_sort=group_sort,
  114. recommend = recommend,
  115. special_class_list_name = special_class_list_name,
  116. is_inner = is_inner,
  117. is_check = is_check,
  118. create_user_id = user_id
  119. )
  120. update_location_time(location_id= location_id)
  121. return {"msg": "success", "code": 200, "new_class_name_id": new_class_name.id}
  122. except Exception as e:
  123. return {"msg": str(e), "code": 500}
  124. @classes.post("/insert_event")
  125. async def insert_event(
  126. name_id: int = Form(default=0),
  127. event: str = Form(default='詳細 請至觀看課程資訊 查看'),
  128. start_time: datetime = Form(default=datetime.now()),
  129. end_time: datetime = Form(default=datetime.now()),
  130. contact: str = Form(default='詳細 請至觀看課程資訊 查看'),
  131. lecturer: str = Form(default='詳細 請至觀看課程資訊 查看'),
  132. location: str = Form(default='詳細 請至觀看課程資訊 查看'),
  133. content: str = Form(default='詳細 請至觀看課程資訊 查看'),
  134. URL: str = Form(default='詳細 請至觀看課程資訊 查看'),
  135. people : str = Form(default='詳細 請至觀看課程資訊 查看'),
  136. fee_method: str = Form(default='詳細 請至觀看課程資訊 查看'),
  137. registration_way: str = Form(default='詳細 請至觀看課程資訊 查看'),
  138. registration_start: datetime = Form(default=datetime.now()),
  139. registration_end: datetime = Form(default=datetime.now()),
  140. number_limit: int = Form(default=0),
  141. remark : str = Form(default='詳細 請至觀看課程資訊 查看'),
  142. ATM_address: str = Form(default=''),
  143. access_token:str = Form(default=None),
  144. fee_payment: str = Form(default=''),
  145. ):
  146. try:
  147. user_id = None
  148. if access_token:
  149. user_id = await check_token(access_token)
  150. # 檢查是否有該課程
  151. class_name_list = await Class_name.filter(id=name_id).all()
  152. if class_name_list == []:
  153. return {"msg": "沒有此課程", "code": 200}
  154. new_class = await Class_list.create(
  155. name_id=name_id,
  156. event =event,
  157. start_time=start_time,
  158. end_time=end_time,
  159. contact=contact,
  160. lecturer=lecturer,
  161. location=location,
  162. content=content,
  163. URL=URL,
  164. people=people,
  165. fee_method=fee_method,
  166. registration_way=registration_way,
  167. remark=remark,
  168. ATM_address=ATM_address,
  169. create_user_id = user_id,
  170. fee_payment = fee_payment
  171. )
  172. try:
  173. await Class_date.create(
  174. class_list_id = new_class.id,
  175. registration_start = registration_start,
  176. registration_end = registration_end,
  177. number_limit = number_limit,
  178. amount_left = number_limit
  179. )
  180. except:
  181. pass
  182. return {"msg": "success", "code": 200, "class_id": new_class.id}
  183. except Exception as e:
  184. return {"msg": str(e), "code": 500}
  185. @classes.post("/auto_create_session")
  186. async def auto_create_session(
  187. class_event_id : int = Form(default=0),
  188. week_day_str : str = Form(default="[]"),
  189. start_week_time : str = Form(default="[]"),
  190. end_week_time : str = Form(default="[]"),
  191. ):
  192. try:
  193. week_day = eval(week_day_str)
  194. start_week_time= eval(start_week_time)
  195. end_week_time= eval(end_week_time)
  196. #print(week_day)
  197. class_obj = await Class_list.get(id = class_event_id)
  198. time_stemp = class_obj.start_time
  199. session = 1
  200. session_list = await Class_detail.filter(class_list_id=class_event_id).delete()
  201. while time_stemp <= class_obj.end_time:
  202. if week_day[time_stemp.weekday()]:
  203. s_start_time = time_stemp.date().strftime("%Y-%m-%d")+" "+start_week_time[time_stemp.weekday()]
  204. s_end_time = time_stemp.date().strftime("%Y-%m-%d")+" "+end_week_time[time_stemp.weekday()]
  205. #time_del = class_obj.end_time.hour - time_stemp.hour
  206. #time_del_minutes = class_obj.end_time.minute - time_stemp.minute
  207. #time_end = time_stemp + timedelta(hours=time_del,minutes=time_del_minutes)
  208. #print(time_end,class_obj.end_time.hour)
  209. day1 = datetime.strptime(s_start_time, '%Y-%m-%d %H:%M:%S')
  210. day2 = datetime.strptime(s_end_time, '%Y-%m-%d %H:%M:%S')
  211. time_difference = day2 - day1
  212. total_minutes = int(time_difference.total_seconds() // 60)
  213. hour=total_minutes//60 + round((total_minutes%60)/60,1)
  214. new_session = await Class_detail.create(
  215. class_list_id=class_event_id,
  216. #start_time=time_stemp,
  217. #end_time=time_end,
  218. start_time=s_start_time,
  219. end_time=s_end_time,
  220. hour = hour,
  221. sessions=session,
  222. content = ""
  223. )
  224. session+=1
  225. time_stemp = time_stemp + timedelta(days=1)
  226. return {"msg": "success", "code": 200}
  227. except Exception as e:
  228. return {"msg": str(e), "code": 500}
  229. @classes.post("/insert_session")
  230. async def insert_session(
  231. class_event_id : int = Form(default=0),
  232. start_time: datetime = Form(default=datetime.now()),
  233. end_time: datetime = Form(default=datetime.now()),
  234. content : str = Form(default='')
  235. ):
  236. try:
  237. session_list = await Class_detail.filter(class_list_id=class_event_id).all()
  238. session = 0
  239. if session_list != []:
  240. for session_obj in session_list:
  241. if session < session_obj.sessions:
  242. session = session_obj.sessions
  243. time_difference = end_time - start_time
  244. total_minutes = int(time_difference.total_seconds() // 60)
  245. hour=total_minutes//60 + round((total_minutes%60)/60,1)
  246. print(round((total_minutes%60)/60,1))
  247. new_session = await Class_detail.create(
  248. class_list_id=class_event_id,
  249. start_time=start_time,
  250. end_time=end_time,
  251. sessions=session +1,
  252. content = content,
  253. hour = hour
  254. )
  255. return {"msg": "success", "code": 200, "new_session_id": new_session.id}
  256. except Exception as e:
  257. return {"msg": str(e), "code": 500}
  258. @classes.post("/update_school")
  259. async def update_school(
  260. location_id: int = Form(default=0),
  261. location_name: str = Form(default=''),
  262. Lng: str = Form(default=''),
  263. Lat: str = Form(default=''),
  264. address : str = Form(default=''),
  265. introduction : str = Form(default=None),
  266. email : str = Form(default=None),
  267. phone : str = Form(default=None)
  268. ):
  269. try:
  270. school = await Schools.get(id=location_id)
  271. if location_name.strip() != '':
  272. school.name = location_name
  273. if Lng != '':
  274. school.longitude = Lng
  275. if Lat.strip() != '':
  276. school.latitude = Lat
  277. if address.strip() != '':
  278. school.address = address
  279. if introduction:
  280. school.introduction = introduction
  281. if email:
  282. school.email = email
  283. if phone:
  284. school.phone = phone
  285. await school.save()
  286. update_location_time(location_id= location_id)
  287. return {"msg": "success", "code": 200}
  288. except Exception as e:
  289. return {"msg": str(e), "code": 500}
  290. @classes.post("/update_class_name")
  291. async def update_class_name(
  292. class_name_id: int = Form(default=0),
  293. name: str = Form(default=''),
  294. location_id: int = Form(default=0),
  295. category: str = Form(default=''),
  296. introduction: str = Form(default=''),
  297. organizer: str = Form(default=''),
  298. cover_img_file:UploadFile = File(default=''),
  299. group_id : int = Form(default=0),
  300. group_sort : str = Form(default=''),
  301. recommend: int = Form(default=None),
  302. special_class_list_name : str = Form(default=None),
  303. is_inner : int = Form(default=None),
  304. is_check : int = Form(default=None)
  305. ):
  306. try:
  307. class_name = await Class_name.get(id=class_name_id)
  308. if name.strip() != '':
  309. class_name.name = name
  310. if location_id != 0:
  311. class_name.school_id = location_id
  312. update_location_time(location_id= location_id)
  313. if category.strip() != '':
  314. class_name.category = category
  315. if introduction.strip() != '':
  316. class_name.introduction = introduction
  317. if organizer.strip() != '':
  318. class_name.organizer = organizer
  319. if group_id != 0 :
  320. class_name.group_id = group_id
  321. if is_inner is not None:
  322. class_name.is_inner = is_inner
  323. if cover_img_file != '':
  324. contents = await cover_img_file.read()
  325. with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
  326. f.write(contents)
  327. class_name.cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
  328. if group_sort != '':
  329. class_name.group_sort = group_sort
  330. if recommend is not None:
  331. class_name.recommend = recommend
  332. if is_check is not None:
  333. class_name.is_check = is_check
  334. if special_class_list_name:
  335. class_name.special_class_list_name = special_class_list_name
  336. await class_name.save()
  337. return {"msg": "success", "code": 200}
  338. except Exception as e:
  339. return {"msg": str(e), "code": 500}
  340. @classes.post("/update_event")
  341. async def update_event(
  342. id: int = Form(default=0),
  343. name_id: int = Form(default=0),
  344. event: str = Form(default=''),
  345. start_time: datetime = Form(default=datetime.now()),
  346. end_time: datetime = Form(default=datetime.now()),
  347. contact: str = Form(default=''),
  348. lecturer: str = Form(default=''),
  349. location: str = Form(default=''),
  350. content: str = Form(default=''),
  351. URL: str = Form(default=''),
  352. people : str = Form(default=''),
  353. fee_method: str = Form(default=''),
  354. registration_way: str = Form(default=''),
  355. registration_start: datetime = Form(default=datetime.now()),
  356. registration_end: datetime = Form(default=datetime.now()),
  357. number_limit: int = Form(default=0),
  358. remark : str = Form(default=''),
  359. ATM_address :str = Form(default=''),
  360. fee_payment : str = Form(default='')
  361. ):
  362. try:
  363. class_obj = await Class_list.get(id=id)
  364. if name_id != 0:
  365. class_obj.name_id = name_id
  366. if event.strip() != '':
  367. class_obj.event = event
  368. if start_time:
  369. class_obj.start_time = start_time
  370. if end_time:
  371. class_obj.end_time = end_time
  372. if lecturer.strip() != '':
  373. class_obj.lecturer = lecturer
  374. if location.strip() != '':
  375. class_obj.location = location
  376. if contact.strip() != '':
  377. class_obj.contact = contact
  378. if content.strip() != '':
  379. class_obj.content = content
  380. if URL.strip() != '':
  381. class_obj.URL = URL
  382. if people.strip() != '':
  383. class_obj.people = people
  384. if fee_method.strip() != '':
  385. class_obj.fee_method = fee_method
  386. if registration_way.strip() != '':
  387. class_obj.registration_way = registration_way
  388. if remark.strip() != '':
  389. class_obj.remark = remark
  390. if ATM_address.strip() != '':
  391. class_obj.ATM_address = ATM_address
  392. if fee_payment.strip() != '':
  393. class_obj.fee_payment = fee_payment
  394. try :
  395. class_date_obj = await Class_date.get(class_list_id=id)
  396. if registration_start != datetime.now():
  397. class_date_obj.registration_start = registration_start
  398. if registration_end != datetime.now():
  399. class_date_obj.registration_end = registration_end
  400. if number_limit != 0:
  401. class_date_obj.number_limit = number_limit
  402. await class_date_obj.save()
  403. except:
  404. await Class_date.create(
  405. class_list_id = id,
  406. registration_start = registration_start,
  407. registration_end = registration_end,
  408. number_limit = number_limit,
  409. amount_left = number_limit
  410. )
  411. await class_obj.save()
  412. return {"msg": "success", "code": 200}
  413. except Exception as e:
  414. return {"msg": str(e), "code": 500}
  415. @classes.post("/update_session")
  416. async def update_session(
  417. session_id : int = Form(default=0),
  418. class_event_id : int = Form(default=0),
  419. start_time: datetime = Form(default=datetime.now()),
  420. end_time: datetime = Form(default=datetime.now()),
  421. sessions: str = Form(default=0),
  422. content : str = Form(default='')
  423. ):
  424. try:
  425. class_session_obj = await Class_detail.get(id=session_id)
  426. if class_event_id != 0:
  427. class_session_obj.class_list_id = class_event_id
  428. if start_time != '':
  429. class_session_obj.start_time = start_time
  430. if end_time != '':
  431. class_session_obj.end_time = end_time
  432. if sessions.strip() != '':
  433. class_session_obj.sessions = sessions
  434. if content.strip() != '':
  435. class_session_obj.content = content
  436. await class_session_obj.save()
  437. return {"msg": "success", "code": 200}
  438. except Exception as e:
  439. return {"msg": str(e), "code": 500}
  440. @classes.post("/delete_school")
  441. async def delete_school(location_id: int):
  442. if location_id:
  443. await Schools.filter(id=location_id).delete()
  444. return {"msg": "success", "code": 200}
  445. @classes.post("/delete_session")
  446. async def delete_session(id: int):
  447. if id:
  448. await Class_detail.filter(id=id).delete()
  449. return {"msg": "success", "code": 200}
  450. @classes.post("/delete_event")
  451. async def delete(id: int):
  452. if id:
  453. await Class_detail.filter(class_list_id=id).delete()
  454. await Class_list.filter(id=id).delete()
  455. await Class_date.filter(class_list_id=id).delete()
  456. return {"msg": "success", "code": 200}
  457. @classes.post("/delete_class_name")
  458. async def delete(id: int):
  459. if id:
  460. class_event_list = await Class_list.filter(name_id=id).all()
  461. for class_event_obj in class_event_list:
  462. await Class_detail.filter(class_list_id=class_event_obj.id).delete()
  463. await Class_date.filter(class_list_id=class_event_obj.id).delete()
  464. await Class_list.filter(name_id=id).delete()
  465. await Class_name.filter(id=id).delete()
  466. return {"msg": "success", "code": 200}
  467. @classes.get("/get_class_state")
  468. async def check_date_state(
  469. class_name_id : Optional[int] = None,
  470. class_event_id : Optional[int] = None,
  471. special_class_list_name : Optional[str] = None,
  472. ):
  473. if class_name_id:
  474. Q_word = Q(name_id=class_name_id)
  475. elif class_event_id:
  476. Q_word = Q(id=class_event_id)
  477. else:
  478. return {"msg": 'please input ID', "code": 500}
  479. if special_class_list_name == "one_day_class":
  480. class_list = await One_day_class.filter(Q_word).all()
  481. elif special_class_list_name == "outter_class_list":
  482. class_list = await Outter_class_list.filter(Q_word).all()
  483. else :
  484. class_list = await Class_list.filter(Q_word).all()
  485. result = {"state": "尚未開放報名(詳情請見官網)"}
  486. try:
  487. for class_obj in class_list:
  488. try:
  489. if class_obj.start_time.replace(tzinfo=None) <= datetime.now() and class_obj.end_time.replace(tzinfo=None) >= datetime.now():
  490. result["state"] = "開課中"
  491. break
  492. elif class_obj.end_time.replace(tzinfo=None) < datetime.now():
  493. result["state"] = "課程已結束"
  494. break
  495. else:
  496. pass
  497. except Exception as e:
  498. pass
  499. if special_class_list_name == "one_day_class":
  500. if class_obj.reg_deadline.replace(tzinfo=None) >= datetime.now() :
  501. result["state"] = "報名中"
  502. break
  503. elif class_obj.reg_deadline.replace(tzinfo=None) < datetime.now():
  504. result["state"] = "報名截止(人數已滿)"
  505. break
  506. else :
  507. try:
  508. class_date_obj = await Class_date.get(class_list_id=class_obj.id)
  509. if class_date_obj.registration_start.replace(tzinfo=None) <= datetime.now() and class_date_obj.registration_end.replace(tzinfo=None) >= datetime.now() :
  510. if class_date_obj.amount_left == 0:
  511. result["start_class"] = "報名截止(人數已滿)"
  512. break
  513. else:
  514. result["start_class"] = "報名中"
  515. break
  516. elif class_date_obj.registration_end.replace(tzinfo=None) < datetime.now():
  517. result["start_class"] = "報名截止(人數已滿)"
  518. break
  519. except Exception as e:
  520. pass
  521. return {"msg": "success", "code": 200, "result": result}
  522. except Exception as e:
  523. return {"msg": str(e), "code": 500}
  524. @classes.get("/get_event")
  525. async def search_event(
  526. class_name_id: Optional[int] = None,
  527. event_id : Optional[int] = None,
  528. access_token: Optional[str] = None
  529. ):
  530. try:
  531. try :
  532. class_name_obj = await Class_name.get(id=class_name_id)
  533. except:
  534. return {"msg": "no this class id", "code": 500}
  535. special_class_list_name = class_name_obj.special_class_list_name
  536. Q_word = Q()
  537. if class_name_id:
  538. Q_word = Q_word | Q(name_id = class_name_id)
  539. elif event_id:
  540. Q_word = Q_word | Q(id = event_id)
  541. else :
  542. return {"msg": "please input class_name_id or event_id", "code": 200}
  543. user_id = None
  544. if access_token:
  545. user_id = await check_token(access_token)
  546. if user_id:
  547. Q_word = Q_word & Q(create_user_id = user_id)
  548. model_fields =[]
  549. state = {}
  550. if special_class_list_name==None:
  551. class_list = Class_list.filter(Q_word).all().order_by("-start_time")
  552. # 获取模型类中的所有字段
  553. model_fields = [attr for attr in dir(Class_list) if isinstance(getattr(Class_list, attr), fields.Field)]
  554. try:
  555. state = await check_date_state(class_event_id=class_name_id)
  556. except:
  557. state["result"] = {
  558. "state" : "fail to get data"
  559. }
  560. elif special_class_list_name=='one_day_class':
  561. class_list = One_day_class.filter(Q_word).all().order_by("-start_time")
  562. # model_fields = [attr for attr in dir(One_day_class) if isinstance(getattr(One_day_class, attr), fields.Field)]
  563. try:
  564. state = await check_date_state(class_name_id=class_name_id,special_class_list_name=special_class_list_name)
  565. except:
  566. state["result"] = {
  567. "state" : "fail to get data"
  568. }
  569. elif special_class_list_name=='outter_class_list':
  570. class_list = Outter_class_list.filter(Q_word).all().order_by("-start_time")
  571. # model_fields = [attr for attr in dir(One_day_class) if isinstance(getattr(One_day_class, attr), fields.Field)]
  572. try:
  573. state = await check_date_state(class_name_id=class_name_id,special_class_list_name=special_class_list_name)
  574. except:
  575. state["result"] = {
  576. "state" : "fail to get data"
  577. }
  578. else:
  579. class_list = Class_list.filter(Q_word).all().order_by("-start_time")
  580. # 获取模型类中的所有字段
  581. model_fields = [attr for attr in dir(Class_list) if isinstance(getattr(Class_list, attr), fields.Field)]
  582. try:
  583. state = await check_date_state(class_event_id=class_name_id)
  584. except:
  585. state["result"] = {
  586. "state" : "fail to get data"
  587. }
  588. class_list = await class_list.all()
  589. classes = []
  590. for class_obj in class_list:
  591. class_name_obj = await Class_name.get(id=class_obj.name_id)
  592. class_name = class_name_obj.name
  593. try :
  594. class_data = class_obj.show_data()
  595. class_data["class_name"] = class_name
  596. class_data["state"] = state["result"]["state"]
  597. try:
  598. class_date_obj = await Class_date.get(class_list_id=class_obj.id)
  599. class_data["registration_start"] = class_date_obj.registration_start
  600. class_data["registration_end"] = class_date_obj.registration_end
  601. class_data["number_limit"] = class_date_obj.number_limit
  602. class_data["amount_left"] = class_date_obj.amount_left
  603. model_fields.append("registration_start","registration_end","number_limit","amount_left")
  604. except:
  605. pass
  606. except:
  607. class_data = {
  608. "msg" : "fail to get data"
  609. }
  610. classes.append(class_data)
  611. return {"msg": "success", "code": 200, "classes": classes}
  612. except Exception as e:
  613. return {"msg": str(e), "code": 500}
  614. @classes.get("/get_school")
  615. async def get_school(
  616. location_id : Optional[int] = None,
  617. keyword : Optional[str] = None,
  618. location_keyword : Optional[str] = None,
  619. page_num : Optional[int] = None,
  620. page_amount : Optional[int] = None,
  621. category : Optional[str] = None,
  622. access_token: Optional[str] = None
  623. ):
  624. try:
  625. school_list = Schools.all()
  626. if location_id :
  627. school_list = school_list.filter(id = location_id).all()
  628. if keyword :
  629. school_list = school_list.filter(Q(name__icontains=keyword)).all()
  630. if location_keyword :
  631. school_list = school_list.filter(Q(address__icontains=location_keyword)).all()
  632. user_id = None
  633. if access_token:
  634. user_id = await check_token(access_token)
  635. if user_id:
  636. school_list = school_list.filter(Q(create_user_id = user_id)).all()
  637. Q_word = Q()
  638. if category:
  639. for tmp_word in category.split(",") :
  640. Q_word = Q_word | Q(category__icontains=tmp_word)
  641. school_list_tmp = await school_list.all()
  642. for school_obj in school_list_tmp:
  643. class_list = await Class_name.filter(Q(school_id = school_obj.id) & Q_word)
  644. if class_list == []:
  645. school_list = school_list.exclude(id = school_obj.id)
  646. count = await school_list.all().count()
  647. if page_num and page_amount:
  648. school_list = school_list.offset((page_num-1)*page_amount).limit(page_amount)
  649. school_list = await school_list.all().order_by("-update_time")
  650. schools = []
  651. for school_obj in school_list:
  652. try :
  653. school_data = school_obj.show_data()
  654. schools.append(school_data)
  655. except:
  656. schools.append({"msg : data wrong"})
  657. return {"msg": "success", "code": 200, "total_num" : count,"schools": schools}
  658. except Exception as e:
  659. return {"msg": str(e), "code": 500}
  660. @classes.get("/get_group_name")
  661. async def get_school_group(
  662. id : Optional[int] = 0
  663. ):
  664. try:
  665. if id==0:
  666. school_group_list = await Group_name.all()
  667. print(school_group_list)
  668. else:
  669. school_group_list = [await Group_name.get(id=id)]
  670. print(school_group_list)
  671. school_groups = []
  672. for school_obj in school_group_list:
  673. school_data = {
  674. "group_id": school_obj.id,
  675. "group_name": school_obj.group_name,
  676. "describe": school_obj.describe
  677. }
  678. school_groups.append(school_data)
  679. return {"msg": "success", "code": 200, "school_groups": school_groups}
  680. except Exception as e:
  681. return {"msg": str(e), "code": 500}
  682. @classes.post("/update_group_name")
  683. async def update_school_group(
  684. id : int = Form(default=0),
  685. group_name : str = Form(default=''),
  686. describe : str = Form(default=''),
  687. ):
  688. try:
  689. group_name_obj = await Group_name.get(id=id)
  690. if group_name.strip() != '':
  691. group_name_obj.group_name = group_name
  692. if describe.strip() != '':
  693. group_name_obj.describe = describe
  694. await group_name_obj.save()
  695. return {"msg": "success", "code": 200}
  696. except Exception as e:
  697. return {"msg": str(e), "code": 500}
  698. @classes.get("/get_class_name")
  699. async def get_class_name(
  700. location_id : Optional[int] = None ,
  701. class_name_id : Optional[int] = None,
  702. group_id : Optional[int] = None,
  703. group_sort :Optional[str] = None,
  704. exclude_word: Optional[str] = None,
  705. category :Optional[str] = None,
  706. page_num : Optional[int] = None,
  707. page_amount : Optional[int] = None,
  708. recommend : Optional[int] = None,
  709. is_inner : Optional[int] = None,
  710. is_check : Optional[int] = None,
  711. access_token: Optional[str] = None
  712. ):
  713. try:
  714. class_name_list = Class_name.all()
  715. Q_word = Q()
  716. if group_id:
  717. Q_word = Q_word & Q(group_id = group_id)
  718. if group_sort:
  719. Q_word = Q_word & Q(group_sort = group_sort)
  720. if category:
  721. for tmp_word in category.split(",") :
  722. Q_word = Q_word | Q(category__icontains=tmp_word)
  723. if location_id :
  724. Q_word = Q_word & Q(school_id = location_id)
  725. if class_name_id :
  726. Q_word = Q_word & Q(id = class_name_id)
  727. if recommend :
  728. Q_word = Q_word & Q(recommend = recommend)
  729. if is_inner!=None:
  730. Q_word = Q_word & Q(is_inner = is_inner)
  731. if is_check!=None:
  732. Q_word = Q_word & Q(is_check = is_check)
  733. user_id = None
  734. if access_token:
  735. user_id = await check_token(access_token)
  736. if user_id:
  737. Q_word = Q_word & Q(create_user_id = user_id)
  738. class_name_list = class_name_list.filter(Q_word).all()
  739. if exclude_word:
  740. for tmp_word in exclude_word.split(",") :
  741. # print(tmp_word)
  742. class_name_list = class_name_list.exclude(Q(category__icontains=tmp_word)|Q(group_sort__icontains=tmp_word)).all()
  743. count = await class_name_list.all().count()
  744. if page_num and page_amount:
  745. class_name_list = class_name_list.offset((page_num-1)*page_amount).limit(page_amount)
  746. class_name_list = await class_name_list.all().order_by("-id")
  747. classes_name = []
  748. state = {}
  749. special_class_list_name = None
  750. for class_name_obj in class_name_list:
  751. try:
  752. school_obj = await Schools.get(id=class_name_obj.school_id)
  753. school_obj_id = school_obj.id
  754. except:
  755. school_obj_id = 0
  756. try:
  757. special_class_list_name = class_name_obj.special_class_list_name
  758. if special_class_list_name:
  759. state = await check_date_state(class_name_id=class_name_obj.id,special_class_list_name=special_class_list_name)
  760. else:
  761. state = await check_date_state(class_name_id=class_name_obj.id)
  762. class_data = class_name_obj.show_data()
  763. if school_obj_id:
  764. for key, item in school_obj.show_data().items():
  765. class_data[key] = item
  766. class_data["state"]=state["result"]["state"]
  767. except Exception as e:
  768. class_data = {
  769. "msg" : str(e)
  770. }
  771. classes_name.append(class_data)
  772. return {"msg": "success", "code": 200,"total_num" : count,"classes": classes_name}
  773. except Exception as e:
  774. return {"msg": str(e), "code": 500}
  775. @classes.get("/get_session")
  776. async def get_session(
  777. event_id : Optional[int] = None
  778. ):
  779. try:
  780. if not event_id:
  781. return {"msg": "please input event_id", "code": 500}
  782. class_session_list = await Class_detail.filter(class_list_id=event_id).all().order_by("start_time")
  783. classe_sessions = []
  784. for class_session_obj in class_session_list:
  785. class_session_data = {
  786. "session_id": class_session_obj.id,
  787. "class_event_id": class_session_obj.class_list_id,
  788. "start_time": class_session_obj.start_time,
  789. "end_time": class_session_obj.end_time,
  790. "sessions": class_session_obj.sessions,
  791. "content": class_session_obj.content
  792. }
  793. classe_sessions.append(class_session_data)
  794. return {"msg": "success", "code": 200, "classe_sessions": classe_sessions}
  795. except Exception as e:
  796. return {"msg": str(e), "code": 500}
  797. @classes.get("/search_class_like")
  798. async def search_class_like(
  799. keyword: str,
  800. location_id : Optional[int] = None ,
  801. group_id : Optional[int] = None,
  802. group_sort :Optional[str] = None,
  803. exclude_word: Optional[str] = None,
  804. category :Optional[str] = None,
  805. page_num : Optional[int] = None,
  806. page_amount : Optional[int] = None,
  807. recommend : Optional[int] = None,
  808. is_inner : Optional[int] = None,
  809. is_check : Optional[int] = None
  810. ):
  811. try:
  812. Q_word = Q()
  813. if group_id:
  814. Q_word = Q_word & Q(group_id = group_id)
  815. if group_sort:
  816. Q_word = Q_word & Q(group_sort = group_sort)
  817. if category:
  818. for tmp_word in category.split(",") :
  819. Q_word = Q_word | Q(category__icontains=tmp_word)
  820. if location_id :
  821. Q_word = Q_word & Q(school_id = location_id)
  822. if recommend :
  823. Q_word = Q_word & Q(recommend = recommend)
  824. if is_inner!=None:
  825. Q_word = Q_word & Q(is_inner = is_inner)
  826. if is_check!=None:
  827. Q_word = Q_word & Q(is_check = is_check)
  828. class_name_id = []
  829. for class_list in await Class_list.filter(Q(lecturer__icontains=keyword)):
  830. class_name_id.append(class_list.name_id)
  831. for class_list in await One_day_class.filter(Q(teacher__icontains=keyword)):
  832. class_name_id.append(class_list.name_id)
  833. if keyword :
  834. Q_word = Q_word & ( Q(name__icontains=keyword)|
  835. Q(category__icontains=keyword)|
  836. Q(introduction__icontains=keyword)|
  837. Q(organizer__icontains=keyword)|
  838. Q(group_sort__icontains=keyword) |
  839. Q(id__in=class_name_id))
  840. class_name_list = Class_name.filter(Q_word).all()
  841. count = await class_name_list.all().count()
  842. if page_num and page_amount:
  843. class_name_list = class_name_list.offset((page_num-1)*page_amount).limit(page_amount)
  844. if exclude_word:
  845. for tmp_word in exclude_word.split(",") :
  846. # print(tmp_word)
  847. class_name_list = class_name_list.exclude(Q(category__icontains=tmp_word)|Q(group_sort__icontains=tmp_word)).all()
  848. class_name_list = await class_name_list.all().order_by("-id")
  849. classes_name = []
  850. state = {}
  851. special_class_list_name = None
  852. for class_name_obj in class_name_list:
  853. try:
  854. school_obj = await Schools.get(id=class_name_obj.school_id)
  855. school_obj_id = school_obj.id
  856. except:
  857. school_obj_id = 0
  858. try:
  859. special_class_list_name = class_name_obj.special_class_list_name
  860. if special_class_list_name:
  861. state = await check_date_state(class_name_id=class_name_obj.id,special_class_list_name=special_class_list_name)
  862. else:
  863. state = await check_date_state(class_name_id=class_name_obj.id)
  864. class_data = class_name_obj.show_data()
  865. if school_obj_id:
  866. for key, item in school_obj.show_data().items():
  867. class_data[key] = item
  868. class_data["state"]=state["result"]["state"]
  869. except Exception as e:
  870. class_data = {
  871. "msg" : str(e)
  872. }
  873. classes_name.append(class_data)
  874. return {"msg": "success", "code": 200, "total_num" : count,"classes": classes_name}
  875. except Exception as e:
  876. return {"msg": str(e), "code": 500}
  877. @classes.post("/add_favorite_class")
  878. async def add_favorite_class(
  879. class_name_id: int,
  880. user_id = Depends(check_token),
  881. time_stemp: datetime = datetime.now()
  882. ):
  883. try:
  884. if not user_id:
  885. return {"msg": "no access", "code": 500}
  886. new_favorite_class = await Favorite_course.get_or_create(
  887. class_name_id=class_name_id,
  888. user_id=user_id,
  889. defaults={'time_stemp': time_stemp}
  890. )
  891. return {"msg": "success", "code": 200,"is exist": not new_favorite_class[1],"id":new_favorite_class[0].id}
  892. except Exception as e:
  893. return {"msg": str(e), "code": 500}
  894. @classes.get("/get_favorite_class")
  895. async def get_favorite_class(
  896. user_id = Depends(check_token),
  897. no_details : Optional[int] = None
  898. ):
  899. try:
  900. class_list = await Favorite_course.filter(user_id = user_id).all()
  901. favorite_courses = []
  902. for class_obj in class_list:
  903. if no_details:
  904. class_data = {
  905. "id": class_obj.id,
  906. "user_id": class_obj.user_id,
  907. "class_name_id" : class_obj.class_name_id,
  908. "time_stemp":class_obj.time_stemp
  909. }
  910. favorite_courses.append(class_data)
  911. else:
  912. class_data = {
  913. "id": class_obj.id,
  914. "user_id": class_obj.user_id,
  915. "class_name_id" : class_obj.class_name_id,
  916. "time_stemp":class_obj.time_stemp
  917. }
  918. result = await get_class_name(class_name_id = class_obj.class_name_id)
  919. try:
  920. class_detail = result["classes"][0]
  921. for key,item in class_detail.items():
  922. class_data[key] = item
  923. favorite_courses.append(class_data)
  924. except:
  925. class_data["msg"] = "this class doesn't exit"
  926. favorite_courses.append(class_data)
  927. return {"msg": "success", "code": 200, "favorite_courses": favorite_courses}
  928. except Exception as e:
  929. return {"msg": str(e), "code": 500}
  930. @classes.post("/delete_favorite_class")
  931. async def delete_favorite_class(
  932. class_name_id: int,
  933. user_id = Depends(check_token)
  934. ):
  935. try:
  936. await Favorite_course.filter(class_name_id=class_name_id,user_id=user_id).delete()
  937. return {"msg": "success", "code": 200}
  938. except Exception as e:
  939. return {"msg": str(e), "code": 500}
  940. @classes.post("/insert_online_course")
  941. async def insert_online_course(
  942. title : str = Form(default=''),
  943. category : str = Form(default=''),
  944. create_time :str = Form(default=datetime.now()),
  945. content : str = Form(default=''),
  946. video_url :str = Form(default='')
  947. ):
  948. try:
  949. new_online_course = await Online_course.create(
  950. title=title,
  951. create_time=create_time,
  952. category=category,
  953. content=content,
  954. video_url=video_url,
  955. group_id = 8
  956. )
  957. return {"msg": "success", "code": 200, "online_course_obj": new_online_course.id}
  958. except Exception as e:
  959. return {"msg": str(e), "code": 500}
  960. @classes.post("/update_online_course")
  961. async def update_online_course(
  962. id : int = Form(default=0),
  963. title : str = Form(default=''),
  964. category : str = Form(default=''),
  965. create_time :str = Form(default=datetime.now()),
  966. content : str = Form(default=''),
  967. video_url :str = Form(default='')
  968. ):
  969. try:
  970. online_course_obj = await Online_course.get(id=id)
  971. if title.strip() != '':
  972. online_course_obj.title = title
  973. if category.strip() != '':
  974. online_course_obj.category = category
  975. if create_time.strip() != '':
  976. online_course_obj.create_time = create_time
  977. if content.strip() != '':
  978. online_course_obj.content = content
  979. if video_url.strip() != '':
  980. online_course_obj.video_url = video_url
  981. await online_course_obj.save()
  982. return {"msg": "success", "code": 200}
  983. except Exception as e:
  984. return {"msg": str(e), "code": 500}
  985. @classes.get("/get_online_courese")
  986. async def get_online_courese(
  987. online_courese_id : Optional[int] = None,
  988. category:Optional[str] = None,
  989. group_id : Optional[int] = None,
  990. page_num : Optional[int] = None,
  991. page_amount : Optional[int] = None,
  992. org :Optional[str] = None,
  993. no_org:Optional[str] = None,
  994. key_word:Optional[str] = None,
  995. ):
  996. try:
  997. online_courese_list = Online_course.all()
  998. Q_word = Q()
  999. if group_id:
  1000. Q_word = Q_word & Q(group_id = group_id)
  1001. if online_courese_id :
  1002. Q_word = Q_word & Q(id = online_courese_id)
  1003. if org :
  1004. Q_word = Q_word & Q(org = org)
  1005. if no_org:
  1006. no_org_condition = Q(org__isnull=True) | ~Q(org=no_org)
  1007. Q_word = Q_word & no_org_condition
  1008. if category:
  1009. category_conditions = Q()
  1010. for tmp_word in category.split(",") :
  1011. category_conditions |= Q(category__icontains=tmp_word)
  1012. Q_word = Q_word & category_conditions
  1013. #Q_word = Q_word | Q(category__icontains=tmp_word)
  1014. if key_word:
  1015. key_word_condition = Q(title__icontains=key_word) | Q(category__icontains=key_word) | Q(content__icontains=key_word)
  1016. Q_word = Q_word & key_word_condition
  1017. count = await online_courese_list.all().filter(Q_word).count()
  1018. if page_num and page_amount:
  1019. online_courese_list = online_courese_list.offset((page_num-1)*page_amount).limit(page_amount)
  1020. online_courese_list = await online_courese_list.all().filter(Q_word).order_by("id")
  1021. online_coureses = []
  1022. for online_coures_obj in online_courese_list:
  1023. online_coures_data = online_coures_obj.show_data()
  1024. online_coureses.append(online_coures_data)
  1025. return {"msg": "success", "code": 200, "total_num" : count,"online_coures": online_coureses}
  1026. except Exception as e:
  1027. return {"msg": str(e), "code": 500}
  1028. @classes.post("/delete_online_course")
  1029. async def delete_online_course(
  1030. online_course_id : int
  1031. ):
  1032. try:
  1033. await Online_course.filter(id=online_course_id).delete()
  1034. return {"msg": "success", "code": 200}
  1035. except Exception as e:
  1036. return {"msg": str(e), "code": 500}
  1037. @classes.get("/get_group_classes_and_articles")
  1038. async def get_group_classes_and_articles(
  1039. group_id : int,
  1040. page_num : Optional[int] = None,
  1041. page_amount : Optional[int] = None
  1042. ):
  1043. try:
  1044. class_name_list = Class_name.filter(group_id = group_id).all().order_by("-id")
  1045. article_list = Article_list.filter(group_id = group_id).all().order_by("-id")
  1046. class_count = await class_name_list.all().count()
  1047. article_count = await article_list.all().count()
  1048. if page_num and page_amount:
  1049. class_name_list = class_name_list.offset((page_num-1)*page_amount).limit(page_amount)
  1050. article_list = article_list.offset((page_num-1)*page_amount).limit(page_amount)
  1051. class_name_list = await class_name_list.all()
  1052. article_list = await article_list.all()
  1053. article_objs = []
  1054. for article_obj in article_list:
  1055. try :
  1056. article_tmp = {
  1057. "article_id": article_obj.id,
  1058. "title": article_obj.title,
  1059. "school_id" :article_obj.school_id,
  1060. "group_sort" :article_obj.group_sort,
  1061. "group_id" :article_obj.group_id,
  1062. "category": article_obj.category,
  1063. "create_time" : article_obj.create_time,
  1064. "click_time" : article_obj.click_time,
  1065. "depiction" : article_obj.depiction,
  1066. "content" : article_obj.content,
  1067. "files" : article_obj.files,
  1068. "vedio_url" : article_obj.vedio_url,
  1069. "tags" : article_obj.tags,
  1070. "cover_img": article_obj.cover_img
  1071. }
  1072. except:
  1073. article_tmp = {
  1074. "msg" : "fail to get data"
  1075. }
  1076. article_objs.append(article_tmp)
  1077. classes_name = []
  1078. for class_name_obj in class_name_list:
  1079. try:
  1080. school_obj = await Schools.get(id=class_name_obj.school_id)
  1081. school_obj_id = school_obj.id
  1082. except:
  1083. school_obj_id = 0
  1084. try:
  1085. special_class_list_name = class_name_obj.special_class_list_name
  1086. if special_class_list_name:
  1087. state = await check_date_state(class_name_id=class_name_obj.id,special_class_list_name=special_class_list_name)
  1088. else:
  1089. state = await check_date_state(class_name_id=class_name_obj.id)
  1090. class_data = class_name_obj.show_data()
  1091. if school_obj_id:
  1092. for key, item in school_obj.show_data().items():
  1093. class_data[key] = item
  1094. class_data["state"]=state["result"]["state"]
  1095. except Exception as e:
  1096. class_data = {
  1097. "msg" : str(e)
  1098. }
  1099. classes_name.append(class_data)
  1100. return {"msg": "success", "code": 200,"class_num" : class_count,"classes": classes_name,"article_num":article_count,"articles": article_objs}
  1101. except Exception as e:
  1102. return {"msg": str(e), "code": 500}
  1103. @classes.post("/add_attend_record_by_event")
  1104. async def add_attend_record(
  1105. class_id : int = Form(default=0),
  1106. ):
  1107. try:
  1108. if not class_id:
  1109. return {"msg": "Please input right ","code":500}
  1110. try:
  1111. class_detail_obj = await Class_detail.filter(class_list_id = class_id).all()
  1112. if not isinstance(class_detail_obj, list):
  1113. class_detail_obj = [class_detail_obj]
  1114. registration_obj = await Registration.filter(event_id = class_id,is_del = 0,).all()
  1115. if not isinstance(registration_obj, list):
  1116. registration_obj = [registration_obj]
  1117. if not class_detail_obj:
  1118. return {"msg": "no this class_detail_id session","code":500}
  1119. except:
  1120. return {"msg": "get class_detail_id error","code":500}
  1121. for obj in class_detail_obj:
  1122. for obj1 in registration_obj:
  1123. new_record = await Attend_record.get_or_create(
  1124. class_detail_id = obj.id,
  1125. user_id = obj1.user_id,
  1126. is_attend = 0
  1127. )
  1128. return {"msg": "success", "code": 200}
  1129. except Exception as e:
  1130. return {"msg": str(e), "code": 500}
  1131. @classes.post("/add_attend_record")
  1132. async def add_attend_record(
  1133. class_detail_id : int = Form(default=0),
  1134. user_id : int = Form(default=0),
  1135. is_attend : int = Form(default=0)
  1136. ):
  1137. try:
  1138. if not class_detail_id or not user_id:
  1139. return {"msg": "Please input right ","code":500}
  1140. try:
  1141. class_detail_obj = await Class_detail.filter(id = class_detail_id).all()
  1142. if not class_detail_obj:
  1143. return {"msg": "no this class_detail_id","code":500}
  1144. except:
  1145. return {"msg": "get class_detail_id error","code":500}
  1146. msg = ""
  1147. new_record,created = await Attend_record.get_or_create(
  1148. class_detail_id = class_detail_id,
  1149. user_id = user_id,
  1150. defaults = {
  1151. "is_attend" : is_attend
  1152. }
  1153. )
  1154. if not created:
  1155. try:
  1156. new_record.is_attend = is_attend
  1157. await new_record.save()
  1158. msg = "update success"
  1159. except:
  1160. msg = "update fail"
  1161. else:
  1162. msg = "created success"
  1163. await count_point(user_id=user_id)
  1164. return {"msg": msg, "code": 200,"new_record_id":new_record.id}
  1165. except Exception as e:
  1166. return {"msg": str(e), "code": 500}
  1167. @classes.post("/count_point")
  1168. async def count_point(user_id:int = None):
  1169. try:
  1170. if user_id :
  1171. hour = 0.0
  1172. user_attend_record = await Attend_record.filter(user_id = user_id,is_attend = 1)
  1173. for tmp in user_attend_record:
  1174. class_detail = await Class_detail.get(id= tmp.class_detail_id)
  1175. hour += float(class_detail.hour)
  1176. user = await User.get(id = user_id)
  1177. user.points = int(hour/3)
  1178. await user.save()
  1179. return {"msg":"success record point", "code": 200}
  1180. else :
  1181. return {"msg":"no user_id", "code": 500}
  1182. except Exception as e:
  1183. return {"msg": str(e), "code": 500}
  1184. @classes.post("/delete_attend_record")
  1185. async def delete_attend_record(
  1186. id : int = 0
  1187. ):
  1188. try :
  1189. record = await Attend_record.get(id=id)
  1190. await count_point(user_id=record.user_id)
  1191. await Attend_record.filter(id=id).delete()
  1192. return {"msg": "success", "code": 200}
  1193. except Exception as e:
  1194. return {"msg": str(e), "code": 500}
  1195. @classes.get("/update_attend_record")
  1196. async def update_attend_record(
  1197. id : int = 0,
  1198. class_detail_id : Optional[int] = None,
  1199. user_id : Optional[int] = None,
  1200. is_attend : Optional[int] = None
  1201. ):
  1202. if not id :
  1203. return {"msg":"please input id"}
  1204. try :
  1205. tmp = await Attend_record.get(id=id)
  1206. if class_detail_id!=None:
  1207. tmp.class_detail_id = class_detail_id
  1208. if user_id!=None:
  1209. tmp.user_id = user_id
  1210. if is_attend!=None:
  1211. tmp.is_attend = is_attend
  1212. await tmp.save()
  1213. await count_point(user_id=tmp.user_id)
  1214. return {"msg": "success", "code": 200}
  1215. except Exception as e:
  1216. return {"msg": str(e), "code": 500}
  1217. @classes.get("/get_attend_record")
  1218. async def get_attend_record(
  1219. class_event_id : Optional[int] = None,
  1220. class_detail_id : Optional[int] = None,
  1221. user_id : Optional[int] = None,
  1222. is_attend : Optional[int] = None
  1223. ):
  1224. try:
  1225. attend_record_list = Attend_record.all()
  1226. if class_event_id:
  1227. id_list = []
  1228. class_detail_list = await Class_detail.filter(class_list_id = class_event_id)
  1229. for tmp in class_detail_list :
  1230. id_list.append(tmp.id)
  1231. attend_record_list = Attend_record.filter(class_detail_id__in=id_list)
  1232. if class_detail_id:
  1233. attend_record_list = attend_record_list.filter(class_detail_id = class_detail_id)
  1234. if user_id :
  1235. attend_record_list = attend_record_list.filter(user_id = user_id)
  1236. if is_attend :
  1237. attend_record_list = attend_record_list.filter(is_attend = is_attend)
  1238. attend_record_list = await attend_record_list.all()
  1239. attend_records = []
  1240. for obj in attend_record_list:
  1241. class_detail_list = await Class_detail.filter(id = obj.class_detail_id)
  1242. #registration_list = await Registration.filter(event_id = class_detail_list[0].class_list_id,user_id =obj.user_id)
  1243. user_list = await User.filter(id = obj.user_id)
  1244. user_information_list = await User_information.filter(user_id = obj.user_id)
  1245. #if len(registration_list)==0:
  1246. # continue
  1247. data = {
  1248. "id" :obj.id,
  1249. "event_id":class_detail_list[0].class_list_id,
  1250. "class_detail_id" :obj.class_detail_id,
  1251. "user_id" :obj.user_id,
  1252. "is_attend" :obj.is_attend,
  1253. #"reg_confirm" : registration_list[0].reg_confirm,
  1254. #"payment_status": registration_list[0].payment_status,
  1255. #"five_digits": registration_list[0].five_digits,
  1256. "real_name": user_information_list[0].name,
  1257. "phone": user_information_list[0].phone,
  1258. "email": user_list[0].email
  1259. }
  1260. attend_records.append(data)
  1261. return {"msg": "success", "code": 200,"attend_record_list":attend_records}
  1262. except Exception as e:
  1263. return {"msg": str(e), "code": 500}