12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592 |
- from fastapi import APIRouter, Form, Depends, HTTPException, File, UploadFile
- from typing import List,Optional
- from fastapi.responses import FileResponse
- from random import randint
- from fastapi.security import OAuth2PasswordRequestForm
- from app.models.models import User,User_information,Favorite_course,Article_list,Class_date,Attend_record,One_day_class,Outter_class_list
- from app.models.models import Class_list,Schools,Class_detail,Class_name,Registration,Group_name,Online_course
- from app.api import deps
- from sqlalchemy.orm import Session
- from typing import Any, Dict
- import secrets
- from fastapi_login.exceptions import InvalidCredentialsException
- from fastapi_login import LoginManager
- from datetime import timedelta,datetime
- from app.config import settings
- from pathlib import Path
- from jose import jwt
- from emails.template import JinjaTemplate
- from tortoise.queryset import Q
- from fastapi.responses import HTMLResponse
- import requests
- import json
- from itertools import chain
- from tortoise import fields
- from datetime import datetime
- classes = APIRouter()
- async def check_token(access_token: str):
- result = await User.filter(token=access_token).first()
-
- if not result:
- print("no access")
- return None
-
- user_id = result.id
- return user_id
- IMAGEDIR = "/var/www/ntcri/assets/"
- IMAGEDIR_short = "assets/"
- async def check_token(access_token: str):
- result = await User.filter(token=access_token).first()
-
- if not result:
- print("no access")
- return None
-
- user_id = result.id
- return user_id
- async def update_location_time(location_id: int):
- if location_id:
- school = await Schools.get(id=location_id)
- school.update_time = datetime.now()
- await school.save()
- return {"msg": "success", "code": 200}
- @classes.post("/insert_school")
- async def insert_school(
- location_name: str = Form(default=''),
- Lng: str = Form(default=''),
- Lat: str = Form(default=''),
- address : str = Form(default=''),
- introduction : str = Form(default=''),
- email : str = Form(default=''),
- phone : str = Form(default=''),
- access_token:str = Form(default=None)
- ):
- try:
- user_id = None
- if access_token:
- user_id = await check_token(access_token)
- new_school = await Schools.create(
- name=location_name,
- longitude=Lng,
- latitude=Lat,
- address = address,
- update_time = datetime.now(),
- introduction = introduction ,
- email= email,
- phone = phone,
- create_user_id = user_id
- )
-
- return {"msg": "success", "code": 200, "location_id": new_school.id}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/insert_class_name")
- async def insert_class_name(
- name: str = Form(default=''),
- location_id: int = Form(default=1),
- category: str = Form(default='詳細 請至觀看課程資訊 查看'),
- introduction: str = Form(default='詳細 請至觀看課程資訊 查看'),
- organizer: str = Form(default='詳細 請至觀看課程資訊 查看'),
- cover_img_file:UploadFile = File(default=''),
- group_id : int = Form(default=1),
- group_sort :str = Form(default='詳細 請至觀看課程資訊 查看'),
- recommend: int = Form(default=0),
- special_class_list_name : str = Form(default=None),
- is_inner : int = Form(default=1),
- is_check : int = Form(default=1),
- access_token:str = Form(default=None)
- ):
- try:
- cover_img = ''
- if cover_img_file != '':
- contents = await cover_img_file.read()
- #save the file
- with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
- f.write(contents)
-
- cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
- user_id = None
- if access_token:
- user_id = await check_token(access_token)
- new_class_name = await Class_name.create(
- name=name,
- school_id=location_id,
- category=category,
- introduction=introduction,
- organizer=organizer,
- cover_img=cover_img,
- group_id=group_id,
- group_sort=group_sort,
- recommend = recommend,
- special_class_list_name = special_class_list_name,
- is_inner = is_inner,
- is_check = is_check,
- create_user_id = user_id
- )
- update_location_time(location_id= location_id)
- return {"msg": "success", "code": 200, "new_class_name_id": new_class_name.id}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/insert_event")
- async def insert_event(
- name_id: int = Form(default=0),
- event: str = Form(default='詳細 請至觀看課程資訊 查看'),
- start_time: datetime = Form(default=datetime.now()),
- end_time: datetime = Form(default=datetime.now()),
- contact: str = Form(default='詳細 請至觀看課程資訊 查看'),
- lecturer: str = Form(default='詳細 請至觀看課程資訊 查看'),
- location: str = Form(default='詳細 請至觀看課程資訊 查看'),
- content: str = Form(default='詳細 請至觀看課程資訊 查看'),
- URL: str = Form(default='詳細 請至觀看課程資訊 查看'),
- people : str = Form(default='詳細 請至觀看課程資訊 查看'),
- fee_method: str = Form(default='詳細 請至觀看課程資訊 查看'),
- registration_way: str = Form(default='詳細 請至觀看課程資訊 查看'),
- registration_start: datetime = Form(default=datetime.now()),
- registration_end: datetime = Form(default=datetime.now()),
- number_limit: int = Form(default=0),
- remark : str = Form(default='詳細 請至觀看課程資訊 查看'),
- ATM_address: str = Form(default=''),
- access_token:str = Form(default=None),
- fee_payment: str = Form(default=''),
- ):
- try:
- user_id = None
- if access_token:
- user_id = await check_token(access_token)
- # 檢查是否有該課程
- class_name_list = await Class_name.filter(id=name_id).all()
- if class_name_list == []:
- return {"msg": "沒有此課程", "code": 200}
-
- new_class = await Class_list.create(
- name_id=name_id,
- event =event,
- start_time=start_time,
- end_time=end_time,
- contact=contact,
- lecturer=lecturer,
- location=location,
- content=content,
- URL=URL,
- people=people,
- fee_method=fee_method,
- registration_way=registration_way,
- remark=remark,
- ATM_address=ATM_address,
- create_user_id = user_id,
- fee_payment = fee_payment
- )
- try:
- await Class_date.create(
- class_list_id = new_class.id,
- registration_start = registration_start,
- registration_end = registration_end,
- number_limit = number_limit,
- amount_left = number_limit
- )
- except:
- pass
- return {"msg": "success", "code": 200, "class_id": new_class.id}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/auto_create_session")
- async def auto_create_session(
- class_event_id : int = Form(default=0),
- week_day_str : str = Form(default="[]"),
- start_week_time : str = Form(default="[]"),
- end_week_time : str = Form(default="[]"),
- ):
- try:
- week_day = eval(week_day_str)
- start_week_time= eval(start_week_time)
- end_week_time= eval(end_week_time)
- #print(week_day)
-
- class_obj = await Class_list.get(id = class_event_id)
- time_stemp = class_obj.start_time
-
- session = 1
-
- session_list = await Class_detail.filter(class_list_id=class_event_id).delete()
-
- while time_stemp <= class_obj.end_time:
- if week_day[time_stemp.weekday()]:
- s_start_time = time_stemp.date().strftime("%Y-%m-%d")+" "+start_week_time[time_stemp.weekday()]
- s_end_time = time_stemp.date().strftime("%Y-%m-%d")+" "+end_week_time[time_stemp.weekday()]
- #time_del = class_obj.end_time.hour - time_stemp.hour
- #time_del_minutes = class_obj.end_time.minute - time_stemp.minute
- #time_end = time_stemp + timedelta(hours=time_del,minutes=time_del_minutes)
- #print(time_end,class_obj.end_time.hour)
-
- day1 = datetime.strptime(s_start_time, '%Y-%m-%d %H:%M:%S')
- day2 = datetime.strptime(s_end_time, '%Y-%m-%d %H:%M:%S')
- time_difference = day2 - day1
- total_minutes = int(time_difference.total_seconds() // 60)
- hour=total_minutes//60 + round((total_minutes%60)/60,1)
- new_session = await Class_detail.create(
- class_list_id=class_event_id,
- #start_time=time_stemp,
- #end_time=time_end,
- start_time=s_start_time,
- end_time=s_end_time,
- hour = hour,
- sessions=session,
- content = ""
- )
- session+=1
- time_stemp = time_stemp + timedelta(days=1)
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/insert_session")
- async def insert_session(
- class_event_id : int = Form(default=0),
- start_time: datetime = Form(default=datetime.now()),
- end_time: datetime = Form(default=datetime.now()),
- content : str = Form(default='')
- ):
- try:
- session_list = await Class_detail.filter(class_list_id=class_event_id).all()
- session = 0
- if session_list != []:
- for session_obj in session_list:
- if session < session_obj.sessions:
- session = session_obj.sessions
- time_difference = end_time - start_time
- total_minutes = int(time_difference.total_seconds() // 60)
- hour=total_minutes//60 + round((total_minutes%60)/60,1)
- print(round((total_minutes%60)/60,1))
- new_session = await Class_detail.create(
- class_list_id=class_event_id,
- start_time=start_time,
- end_time=end_time,
- sessions=session +1,
- content = content,
- hour = hour
- )
-
- return {"msg": "success", "code": 200, "new_session_id": new_session.id}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/update_school")
- async def update_school(
- location_id: int = Form(default=0),
- location_name: str = Form(default=''),
- Lng: str = Form(default=''),
- Lat: str = Form(default=''),
- address : str = Form(default=''),
- introduction : str = Form(default=None),
- email : str = Form(default=None),
- phone : str = Form(default=None)
- ):
- try:
- school = await Schools.get(id=location_id)
- if location_name.strip() != '':
- school.name = location_name
- if Lng != '':
- school.longitude = Lng
-
- if Lat.strip() != '':
- school.latitude = Lat
- if address.strip() != '':
- school.address = address
-
- if introduction:
- school.introduction = introduction
- if email:
- school.email = email
- if phone:
- school.phone = phone
- await school.save()
- update_location_time(location_id= location_id)
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/update_class_name")
- async def update_class_name(
- class_name_id: int = Form(default=0),
- name: str = Form(default=''),
- location_id: int = Form(default=0),
- category: str = Form(default=''),
- introduction: str = Form(default=''),
- organizer: str = Form(default=''),
- cover_img_file:UploadFile = File(default=''),
- group_id : int = Form(default=0),
- group_sort : str = Form(default=''),
- recommend: int = Form(default=None),
- special_class_list_name : str = Form(default=None),
- is_inner : int = Form(default=None),
- is_check : int = Form(default=None)
- ):
- try:
- class_name = await Class_name.get(id=class_name_id)
- if name.strip() != '':
- class_name.name = name
- if location_id != 0:
- class_name.school_id = location_id
- update_location_time(location_id= location_id)
-
- if category.strip() != '':
- class_name.category = category
- if introduction.strip() != '':
- class_name.introduction = introduction
- if organizer.strip() != '':
- class_name.organizer = organizer
- if group_id != 0 :
- class_name.group_id = group_id
- if is_inner is not None:
- class_name.is_inner = is_inner
- if cover_img_file != '':
- contents = await cover_img_file.read()
- with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
- f.write(contents)
-
- class_name.cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
- if group_sort != '':
- class_name.group_sort = group_sort
- if recommend is not None:
- class_name.recommend = recommend
- if is_check is not None:
- class_name.is_check = is_check
- if special_class_list_name:
- class_name.special_class_list_name = special_class_list_name
- await class_name.save()
-
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.post("/update_event")
- async def update_event(
- id: int = Form(default=0),
- name_id: int = Form(default=0),
- event: str = Form(default=''),
- start_time: datetime = Form(default=datetime.now()),
- end_time: datetime = Form(default=datetime.now()),
- contact: str = Form(default=''),
- lecturer: str = Form(default=''),
- location: str = Form(default=''),
- content: str = Form(default=''),
- URL: str = Form(default=''),
- people : str = Form(default=''),
- fee_method: str = Form(default=''),
- registration_way: str = Form(default=''),
- registration_start: datetime = Form(default=datetime.now()),
- registration_end: datetime = Form(default=datetime.now()),
- number_limit: int = Form(default=0),
- remark : str = Form(default=''),
- ATM_address :str = Form(default=''),
- fee_payment : str = Form(default='')
- ):
- try:
- class_obj = await Class_list.get(id=id)
- if name_id != 0:
- class_obj.name_id = name_id
- if event.strip() != '':
- class_obj.event = event
- if start_time:
- class_obj.start_time = start_time
- if end_time:
- class_obj.end_time = end_time
- if lecturer.strip() != '':
- class_obj.lecturer = lecturer
- if location.strip() != '':
- class_obj.location = location
- if contact.strip() != '':
- class_obj.contact = contact
- if content.strip() != '':
- class_obj.content = content
- if URL.strip() != '':
- class_obj.URL = URL
-
- if people.strip() != '':
- class_obj.people = people
- if fee_method.strip() != '':
- class_obj.fee_method = fee_method
- if registration_way.strip() != '':
- class_obj.registration_way = registration_way
- if remark.strip() != '':
- class_obj.remark = remark
- if ATM_address.strip() != '':
- class_obj.ATM_address = ATM_address
- if fee_payment.strip() != '':
- class_obj.fee_payment = fee_payment
-
- try :
- class_date_obj = await Class_date.get(class_list_id=id)
- if registration_start != datetime.now():
- class_date_obj.registration_start = registration_start
- if registration_end != datetime.now():
- class_date_obj.registration_end = registration_end
- if number_limit != 0:
- class_date_obj.number_limit = number_limit
- await class_date_obj.save()
-
- except:
- await Class_date.create(
- class_list_id = id,
- registration_start = registration_start,
- registration_end = registration_end,
- number_limit = number_limit,
- amount_left = number_limit
- )
-
- await class_obj.save()
-
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/update_session")
- async def update_session(
- session_id : int = Form(default=0),
- class_event_id : int = Form(default=0),
- start_time: datetime = Form(default=datetime.now()),
- end_time: datetime = Form(default=datetime.now()),
- sessions: str = Form(default=0),
- content : str = Form(default='')
- ):
- try:
- class_session_obj = await Class_detail.get(id=session_id)
-
- if class_event_id != 0:
- class_session_obj.class_list_id = class_event_id
- if start_time != '':
- class_session_obj.start_time = start_time
- if end_time != '':
- class_session_obj.end_time = end_time
-
- if sessions.strip() != '':
- class_session_obj.sessions = sessions
- if content.strip() != '':
- class_session_obj.content = content
-
- await class_session_obj.save()
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/delete_school")
- async def delete_school(location_id: int):
- if location_id:
- await Schools.filter(id=location_id).delete()
- return {"msg": "success", "code": 200}
- @classes.post("/delete_session")
- async def delete_session(id: int):
- if id:
- await Class_detail.filter(id=id).delete()
- return {"msg": "success", "code": 200}
- @classes.post("/delete_event")
- async def delete(id: int):
- if id:
- await Class_detail.filter(class_list_id=id).delete()
- await Class_list.filter(id=id).delete()
- await Class_date.filter(class_list_id=id).delete()
- return {"msg": "success", "code": 200}
-
- @classes.post("/delete_class_name")
- async def delete(id: int):
- if id:
- class_event_list = await Class_list.filter(name_id=id).all()
- for class_event_obj in class_event_list:
- await Class_detail.filter(class_list_id=class_event_obj.id).delete()
- await Class_date.filter(class_list_id=class_event_obj.id).delete()
- await Class_list.filter(name_id=id).delete()
- await Class_name.filter(id=id).delete()
-
- return {"msg": "success", "code": 200}
- @classes.get("/get_class_state")
- async def check_date_state(
- class_name_id : Optional[int] = None,
- class_event_id : Optional[int] = None,
- special_class_list_name : Optional[str] = None,
- ):
- if class_name_id:
- Q_word = Q(name_id=class_name_id)
- elif class_event_id:
- Q_word = Q(id=class_event_id)
- else:
- return {"msg": 'please input ID', "code": 500}
-
- if special_class_list_name == "one_day_class":
- class_list = await One_day_class.filter(Q_word).all()
- elif special_class_list_name == "outter_class_list":
- class_list = await Outter_class_list.filter(Q_word).all()
- else :
- class_list = await Class_list.filter(Q_word).all()
-
-
- result = {"state": "尚未開放報名(詳情請見官網)"}
- try:
- for class_obj in class_list:
- try:
- if class_obj.start_time.replace(tzinfo=None) <= datetime.now() and class_obj.end_time.replace(tzinfo=None) >= datetime.now():
- result["state"] = "開課中"
- break
- elif class_obj.end_time.replace(tzinfo=None) < datetime.now():
- result["state"] = "課程已結束"
- break
- else:
- pass
- except Exception as e:
- pass
- if special_class_list_name == "one_day_class":
- if class_obj.reg_deadline.replace(tzinfo=None) >= datetime.now() :
- result["state"] = "報名中"
- break
- elif class_obj.reg_deadline.replace(tzinfo=None) < datetime.now():
- result["state"] = "報名截止(人數已滿)"
- break
- else :
- try:
- class_date_obj = await Class_date.get(class_list_id=class_obj.id)
- if class_date_obj.registration_start.replace(tzinfo=None) <= datetime.now() and class_date_obj.registration_end.replace(tzinfo=None) >= datetime.now() :
- if class_date_obj.amount_left == 0:
- result["start_class"] = "報名截止(人數已滿)"
- break
- else:
- result["start_class"] = "報名中"
- break
- elif class_date_obj.registration_end.replace(tzinfo=None) < datetime.now():
- result["start_class"] = "報名截止(人數已滿)"
- break
- except Exception as e:
- pass
-
- return {"msg": "success", "code": 200, "result": result}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.get("/get_event")
- async def search_event(
- class_name_id: Optional[int] = None,
- event_id : Optional[int] = None,
- access_token: Optional[str] = None
- ):
- try:
- try :
- class_name_obj = await Class_name.get(id=class_name_id)
- except:
- return {"msg": "no this class id", "code": 500}
-
- special_class_list_name = class_name_obj.special_class_list_name
- Q_word = Q()
- if class_name_id:
- Q_word = Q_word | Q(name_id = class_name_id)
- elif event_id:
- Q_word = Q_word | Q(id = event_id)
- else :
- return {"msg": "please input class_name_id or event_id", "code": 200}
-
- user_id = None
- if access_token:
- user_id = await check_token(access_token)
- if user_id:
- Q_word = Q_word & Q(create_user_id = user_id)
-
- model_fields =[]
- state = {}
- if special_class_list_name==None:
- class_list = Class_list.filter(Q_word).all().order_by("-start_time")
- # 获取模型类中的所有字段
- model_fields = [attr for attr in dir(Class_list) if isinstance(getattr(Class_list, attr), fields.Field)]
- try:
- state = await check_date_state(class_event_id=class_name_id)
- except:
- state["result"] = {
- "state" : "fail to get data"
- }
- elif special_class_list_name=='one_day_class':
- class_list = One_day_class.filter(Q_word).all().order_by("-start_time")
- # model_fields = [attr for attr in dir(One_day_class) if isinstance(getattr(One_day_class, attr), fields.Field)]
- try:
- state = await check_date_state(class_name_id=class_name_id,special_class_list_name=special_class_list_name)
- except:
- state["result"] = {
- "state" : "fail to get data"
- }
- elif special_class_list_name=='outter_class_list':
- class_list = Outter_class_list.filter(Q_word).all().order_by("-start_time")
- # model_fields = [attr for attr in dir(One_day_class) if isinstance(getattr(One_day_class, attr), fields.Field)]
- try:
- state = await check_date_state(class_name_id=class_name_id,special_class_list_name=special_class_list_name)
- except:
- state["result"] = {
- "state" : "fail to get data"
- }
- else:
- class_list = Class_list.filter(Q_word).all().order_by("-start_time")
- # 获取模型类中的所有字段
- model_fields = [attr for attr in dir(Class_list) if isinstance(getattr(Class_list, attr), fields.Field)]
- try:
- state = await check_date_state(class_event_id=class_name_id)
- except:
- state["result"] = {
- "state" : "fail to get data"
- }
-
-
- class_list = await class_list.all()
- classes = []
- for class_obj in class_list:
- class_name_obj = await Class_name.get(id=class_obj.name_id)
- class_name = class_name_obj.name
- try :
- class_data = class_obj.show_data()
- class_data["class_name"] = class_name
- class_data["state"] = state["result"]["state"]
- try:
- class_date_obj = await Class_date.get(class_list_id=class_obj.id)
- class_data["registration_start"] = class_date_obj.registration_start
- class_data["registration_end"] = class_date_obj.registration_end
- class_data["number_limit"] = class_date_obj.number_limit
- class_data["amount_left"] = class_date_obj.amount_left
- model_fields.append("registration_start","registration_end","number_limit","amount_left")
-
- except:
- pass
- except:
- class_data = {
- "msg" : "fail to get data"
- }
-
- classes.append(class_data)
- return {"msg": "success", "code": 200, "classes": classes}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.get("/get_school")
- async def get_school(
- location_id : Optional[int] = None,
- keyword : Optional[str] = None,
- location_keyword : Optional[str] = None,
- page_num : Optional[int] = None,
- page_amount : Optional[int] = None,
- category : Optional[str] = None,
- access_token: Optional[str] = None
- ):
- try:
- school_list = Schools.all()
- if location_id :
- school_list = school_list.filter(id = location_id).all()
-
- if keyword :
- school_list = school_list.filter(Q(name__icontains=keyword)).all()
- if location_keyword :
- school_list = school_list.filter(Q(address__icontains=location_keyword)).all()
- user_id = None
- if access_token:
- user_id = await check_token(access_token)
- if user_id:
- school_list = school_list.filter(Q(create_user_id = user_id)).all()
- Q_word = Q()
- if category:
- for tmp_word in category.split(",") :
- Q_word = Q_word | Q(category__icontains=tmp_word)
- school_list_tmp = await school_list.all()
- for school_obj in school_list_tmp:
- class_list = await Class_name.filter(Q(school_id = school_obj.id) & Q_word)
- if class_list == []:
- school_list = school_list.exclude(id = school_obj.id)
-
- count = await school_list.all().count()
- if page_num and page_amount:
- school_list = school_list.offset((page_num-1)*page_amount).limit(page_amount)
-
- school_list = await school_list.all().order_by("-update_time")
-
- schools = []
- for school_obj in school_list:
- try :
-
- school_data = school_obj.show_data()
-
- schools.append(school_data)
-
- except:
- schools.append({"msg : data wrong"})
-
- return {"msg": "success", "code": 200, "total_num" : count,"schools": schools}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.get("/get_group_name")
- async def get_school_group(
- id : Optional[int] = 0
- ):
- try:
- if id==0:
- school_group_list = await Group_name.all()
- print(school_group_list)
- else:
- school_group_list = [await Group_name.get(id=id)]
- print(school_group_list)
- school_groups = []
- for school_obj in school_group_list:
- school_data = {
- "group_id": school_obj.id,
- "group_name": school_obj.group_name,
- "describe": school_obj.describe
- }
- school_groups.append(school_data)
- return {"msg": "success", "code": 200, "school_groups": school_groups}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/update_group_name")
- async def update_school_group(
- id : int = Form(default=0),
- group_name : str = Form(default=''),
- describe : str = Form(default=''),
- ):
- try:
- group_name_obj = await Group_name.get(id=id)
- if group_name.strip() != '':
- group_name_obj.group_name = group_name
-
- if describe.strip() != '':
- group_name_obj.describe = describe
-
- await group_name_obj.save()
-
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.get("/get_class_name")
- async def get_class_name(
- location_id : Optional[int] = None ,
- class_name_id : Optional[int] = None,
- group_id : Optional[int] = None,
- group_sort :Optional[str] = None,
- exclude_word: Optional[str] = None,
- category :Optional[str] = None,
- page_num : Optional[int] = None,
- page_amount : Optional[int] = None,
- recommend : Optional[int] = None,
- is_inner : Optional[int] = None,
- is_check : Optional[int] = None,
- access_token: Optional[str] = None
- ):
- try:
- class_name_list = Class_name.all()
-
- Q_word = Q()
-
- if group_id:
- Q_word = Q_word & Q(group_id = group_id)
- if group_sort:
- Q_word = Q_word & Q(group_sort = group_sort)
-
- if category:
- for tmp_word in category.split(",") :
- Q_word = Q_word | Q(category__icontains=tmp_word)
- if location_id :
- Q_word = Q_word & Q(school_id = location_id)
- if class_name_id :
- Q_word = Q_word & Q(id = class_name_id)
- if recommend :
- Q_word = Q_word & Q(recommend = recommend)
- if is_inner!=None:
- Q_word = Q_word & Q(is_inner = is_inner)
- if is_check!=None:
- Q_word = Q_word & Q(is_check = is_check)
-
- user_id = None
- if access_token:
- user_id = await check_token(access_token)
- if user_id:
- Q_word = Q_word & Q(create_user_id = user_id)
- class_name_list = class_name_list.filter(Q_word).all()
- if exclude_word:
- for tmp_word in exclude_word.split(",") :
- # print(tmp_word)
- class_name_list = class_name_list.exclude(Q(category__icontains=tmp_word)|Q(group_sort__icontains=tmp_word)).all()
-
- count = await class_name_list.all().count()
- if page_num and page_amount:
- class_name_list = class_name_list.offset((page_num-1)*page_amount).limit(page_amount)
- class_name_list = await class_name_list.all().order_by("-id")
- classes_name = []
- state = {}
- special_class_list_name = None
-
- for class_name_obj in class_name_list:
- try:
- school_obj = await Schools.get(id=class_name_obj.school_id)
- school_obj_id = school_obj.id
- except:
- school_obj_id = 0
-
- try:
-
- special_class_list_name = class_name_obj.special_class_list_name
- if special_class_list_name:
- state = await check_date_state(class_name_id=class_name_obj.id,special_class_list_name=special_class_list_name)
- else:
- state = await check_date_state(class_name_id=class_name_obj.id)
-
- class_data = class_name_obj.show_data()
- if school_obj_id:
- for key, item in school_obj.show_data().items():
- class_data[key] = item
-
- class_data["state"]=state["result"]["state"]
- except Exception as e:
- class_data = {
- "msg" : str(e)
- }
-
- classes_name.append(class_data)
-
- return {"msg": "success", "code": 200,"total_num" : count,"classes": classes_name}
-
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.get("/get_session")
- async def get_session(
- event_id : Optional[int] = None
- ):
- try:
- if not event_id:
- return {"msg": "please input event_id", "code": 500}
-
- class_session_list = await Class_detail.filter(class_list_id=event_id).all().order_by("start_time")
-
- classe_sessions = []
- for class_session_obj in class_session_list:
- class_session_data = {
- "session_id": class_session_obj.id,
- "class_event_id": class_session_obj.class_list_id,
- "start_time": class_session_obj.start_time,
- "end_time": class_session_obj.end_time,
- "sessions": class_session_obj.sessions,
- "content": class_session_obj.content
- }
- classe_sessions.append(class_session_data)
- return {"msg": "success", "code": 200, "classe_sessions": classe_sessions}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.get("/search_class_like")
- async def search_class_like(
- keyword: str,
- location_id : Optional[int] = None ,
- group_id : Optional[int] = None,
- group_sort :Optional[str] = None,
- exclude_word: Optional[str] = None,
- category :Optional[str] = None,
- page_num : Optional[int] = None,
- page_amount : Optional[int] = None,
- recommend : Optional[int] = None,
- is_inner : Optional[int] = None,
- is_check : Optional[int] = None
- ):
- try:
- Q_word = Q()
- if group_id:
- Q_word = Q_word & Q(group_id = group_id)
- if group_sort:
- Q_word = Q_word & Q(group_sort = group_sort)
-
- if category:
- for tmp_word in category.split(",") :
- Q_word = Q_word | Q(category__icontains=tmp_word)
- if location_id :
- Q_word = Q_word & Q(school_id = location_id)
- if recommend :
- Q_word = Q_word & Q(recommend = recommend)
- if is_inner!=None:
- Q_word = Q_word & Q(is_inner = is_inner)
- if is_check!=None:
- Q_word = Q_word & Q(is_check = is_check)
-
- class_name_id = []
- for class_list in await Class_list.filter(Q(lecturer__icontains=keyword)):
- class_name_id.append(class_list.name_id)
- for class_list in await One_day_class.filter(Q(teacher__icontains=keyword)):
- class_name_id.append(class_list.name_id)
- if keyword :
- Q_word = Q_word & ( Q(name__icontains=keyword)|
- Q(category__icontains=keyword)|
- Q(introduction__icontains=keyword)|
- Q(organizer__icontains=keyword)|
- Q(group_sort__icontains=keyword) |
- Q(id__in=class_name_id))
- class_name_list = Class_name.filter(Q_word).all()
- count = await class_name_list.all().count()
- if page_num and page_amount:
- class_name_list = class_name_list.offset((page_num-1)*page_amount).limit(page_amount)
- if exclude_word:
- for tmp_word in exclude_word.split(",") :
- # print(tmp_word)
- class_name_list = class_name_list.exclude(Q(category__icontains=tmp_word)|Q(group_sort__icontains=tmp_word)).all()
- class_name_list = await class_name_list.all().order_by("-id")
- classes_name = []
- state = {}
- special_class_list_name = None
-
- for class_name_obj in class_name_list:
- try:
- school_obj = await Schools.get(id=class_name_obj.school_id)
- school_obj_id = school_obj.id
- except:
- school_obj_id = 0
-
- try:
-
- special_class_list_name = class_name_obj.special_class_list_name
- if special_class_list_name:
- state = await check_date_state(class_name_id=class_name_obj.id,special_class_list_name=special_class_list_name)
- else:
- state = await check_date_state(class_name_id=class_name_obj.id)
-
- class_data = class_name_obj.show_data()
- if school_obj_id:
- for key, item in school_obj.show_data().items():
- class_data[key] = item
-
- class_data["state"]=state["result"]["state"]
- except Exception as e:
- class_data = {
- "msg" : str(e)
- }
- classes_name.append(class_data)
- return {"msg": "success", "code": 200, "total_num" : count,"classes": classes_name}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/add_favorite_class")
- async def add_favorite_class(
- class_name_id: int,
- user_id = Depends(check_token),
- time_stemp: datetime = datetime.now()
- ):
- try:
- if not user_id:
- return {"msg": "no access", "code": 500}
- new_favorite_class = await Favorite_course.get_or_create(
- class_name_id=class_name_id,
- user_id=user_id,
- defaults={'time_stemp': time_stemp}
- )
- return {"msg": "success", "code": 200,"is exist": not new_favorite_class[1],"id":new_favorite_class[0].id}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.get("/get_favorite_class")
- async def get_favorite_class(
- user_id = Depends(check_token),
- no_details : Optional[int] = None
- ):
- try:
- class_list = await Favorite_course.filter(user_id = user_id).all()
- favorite_courses = []
- for class_obj in class_list:
- if no_details:
- class_data = {
- "id": class_obj.id,
- "user_id": class_obj.user_id,
- "class_name_id" : class_obj.class_name_id,
- "time_stemp":class_obj.time_stemp
- }
- favorite_courses.append(class_data)
- else:
- class_data = {
- "id": class_obj.id,
- "user_id": class_obj.user_id,
- "class_name_id" : class_obj.class_name_id,
- "time_stemp":class_obj.time_stemp
- }
- result = await get_class_name(class_name_id = class_obj.class_name_id)
- try:
- class_detail = result["classes"][0]
- for key,item in class_detail.items():
- class_data[key] = item
- favorite_courses.append(class_data)
- except:
- class_data["msg"] = "this class doesn't exit"
- favorite_courses.append(class_data)
-
- return {"msg": "success", "code": 200, "favorite_courses": favorite_courses}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/delete_favorite_class")
- async def delete_favorite_class(
- class_name_id: int,
- user_id = Depends(check_token)
- ):
- try:
- await Favorite_course.filter(class_name_id=class_name_id,user_id=user_id).delete()
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/insert_online_course")
- async def insert_online_course(
- title : str = Form(default=''),
- category : str = Form(default=''),
- create_time :str = Form(default=datetime.now()),
- content : str = Form(default=''),
- video_url :str = Form(default='')
- ):
- try:
- new_online_course = await Online_course.create(
- title=title,
- create_time=create_time,
- category=category,
- content=content,
- video_url=video_url,
- group_id = 8
- )
-
- return {"msg": "success", "code": 200, "online_course_obj": new_online_course.id}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.post("/update_online_course")
- async def update_online_course(
- id : int = Form(default=0),
- title : str = Form(default=''),
- category : str = Form(default=''),
- create_time :str = Form(default=datetime.now()),
- content : str = Form(default=''),
- video_url :str = Form(default='')
- ):
- try:
- online_course_obj = await Online_course.get(id=id)
- if title.strip() != '':
- online_course_obj.title = title
-
- if category.strip() != '':
- online_course_obj.category = category
- if create_time.strip() != '':
- online_course_obj.create_time = create_time
- if content.strip() != '':
- online_course_obj.content = content
- if video_url.strip() != '':
- online_course_obj.video_url = video_url
-
- await online_course_obj.save()
-
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.get("/get_online_courese")
- async def get_online_courese(
- online_courese_id : Optional[int] = None,
- category:Optional[str] = None,
- group_id : Optional[int] = None,
- page_num : Optional[int] = None,
- page_amount : Optional[int] = None,
- org :Optional[str] = None,
- no_org:Optional[str] = None,
- key_word:Optional[str] = None,
- ):
- try:
- online_courese_list = Online_course.all()
- Q_word = Q()
- if group_id:
- Q_word = Q_word & Q(group_id = group_id)
-
- if online_courese_id :
- Q_word = Q_word & Q(id = online_courese_id)
- if org :
- Q_word = Q_word & Q(org = org)
- if no_org:
- no_org_condition = Q(org__isnull=True) | ~Q(org=no_org)
- Q_word = Q_word & no_org_condition
-
- if category:
- category_conditions = Q()
- for tmp_word in category.split(",") :
- category_conditions |= Q(category__icontains=tmp_word)
- Q_word = Q_word & category_conditions
- #Q_word = Q_word | Q(category__icontains=tmp_word)
- if key_word:
- key_word_condition = Q(title__icontains=key_word) | Q(category__icontains=key_word) | Q(content__icontains=key_word)
- Q_word = Q_word & key_word_condition
- count = await online_courese_list.all().filter(Q_word).count()
-
- if page_num and page_amount:
- online_courese_list = online_courese_list.offset((page_num-1)*page_amount).limit(page_amount)
- online_courese_list = await online_courese_list.all().filter(Q_word).order_by("id")
-
- online_coureses = []
- for online_coures_obj in online_courese_list:
- online_coures_data = online_coures_obj.show_data()
- online_coureses.append(online_coures_data)
- return {"msg": "success", "code": 200, "total_num" : count,"online_coures": online_coureses}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/delete_online_course")
- async def delete_online_course(
- online_course_id : int
- ):
- try:
- await Online_course.filter(id=online_course_id).delete()
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.get("/get_group_classes_and_articles")
- async def get_group_classes_and_articles(
- group_id : int,
- page_num : Optional[int] = None,
- page_amount : Optional[int] = None
- ):
- try:
- class_name_list = Class_name.filter(group_id = group_id).all().order_by("-id")
- article_list = Article_list.filter(group_id = group_id).all().order_by("-id")
- class_count = await class_name_list.all().count()
- article_count = await article_list.all().count()
- if page_num and page_amount:
- class_name_list = class_name_list.offset((page_num-1)*page_amount).limit(page_amount)
- article_list = article_list.offset((page_num-1)*page_amount).limit(page_amount)
-
-
- class_name_list = await class_name_list.all()
- article_list = await article_list.all()
- article_objs = []
-
- for article_obj in article_list:
- try :
- article_tmp = {
- "article_id": article_obj.id,
- "title": article_obj.title,
- "school_id" :article_obj.school_id,
- "group_sort" :article_obj.group_sort,
- "group_id" :article_obj.group_id,
- "category": article_obj.category,
- "create_time" : article_obj.create_time,
- "click_time" : article_obj.click_time,
- "depiction" : article_obj.depiction,
- "content" : article_obj.content,
- "files" : article_obj.files,
- "vedio_url" : article_obj.vedio_url,
- "tags" : article_obj.tags,
- "cover_img": article_obj.cover_img
- }
- except:
- article_tmp = {
- "msg" : "fail to get data"
- }
-
- article_objs.append(article_tmp)
-
- classes_name = []
-
- for class_name_obj in class_name_list:
- try:
- school_obj = await Schools.get(id=class_name_obj.school_id)
- school_obj_id = school_obj.id
- except:
- school_obj_id = 0
-
- try:
-
- special_class_list_name = class_name_obj.special_class_list_name
- if special_class_list_name:
- state = await check_date_state(class_name_id=class_name_obj.id,special_class_list_name=special_class_list_name)
- else:
- state = await check_date_state(class_name_id=class_name_obj.id)
-
- class_data = class_name_obj.show_data()
- if school_obj_id:
- for key, item in school_obj.show_data().items():
- class_data[key] = item
-
- class_data["state"]=state["result"]["state"]
- except Exception as e:
- class_data = {
- "msg" : str(e)
- }
-
- classes_name.append(class_data)
-
- return {"msg": "success", "code": 200,"class_num" : class_count,"classes": classes_name,"article_num":article_count,"articles": article_objs}
-
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.post("/add_attend_record_by_event")
- async def add_attend_record(
- class_id : int = Form(default=0),
- ):
- try:
- if not class_id:
- return {"msg": "Please input right ","code":500}
-
- try:
- class_detail_obj = await Class_detail.filter(class_list_id = class_id).all()
-
- if not isinstance(class_detail_obj, list):
- class_detail_obj = [class_detail_obj]
- registration_obj = await Registration.filter(event_id = class_id,is_del = 0,).all()
-
- if not isinstance(registration_obj, list):
- registration_obj = [registration_obj]
- if not class_detail_obj:
- return {"msg": "no this class_detail_id session","code":500}
- except:
- return {"msg": "get class_detail_id error","code":500}
-
- for obj in class_detail_obj:
- for obj1 in registration_obj:
- new_record = await Attend_record.get_or_create(
- class_detail_id = obj.id,
- user_id = obj1.user_id,
- is_attend = 0
- )
-
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
-
- @classes.post("/add_attend_record")
- async def add_attend_record(
- class_detail_id : int = Form(default=0),
- user_id : int = Form(default=0),
- is_attend : int = Form(default=0)
- ):
- try:
- if not class_detail_id or not user_id:
- return {"msg": "Please input right ","code":500}
-
- try:
- class_detail_obj = await Class_detail.filter(id = class_detail_id).all()
- if not class_detail_obj:
- return {"msg": "no this class_detail_id","code":500}
- except:
- return {"msg": "get class_detail_id error","code":500}
-
- msg = ""
- new_record,created = await Attend_record.get_or_create(
- class_detail_id = class_detail_id,
- user_id = user_id,
- defaults = {
- "is_attend" : is_attend
- }
- )
- if not created:
- try:
- new_record.is_attend = is_attend
- await new_record.save()
- msg = "update success"
- except:
- msg = "update fail"
- else:
- msg = "created success"
- await count_point(user_id=user_id)
- return {"msg": msg, "code": 200,"new_record_id":new_record.id}
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/count_point")
- async def count_point(user_id:int = None):
- try:
- if user_id :
- hour = 0.0
- user_attend_record = await Attend_record.filter(user_id = user_id,is_attend = 1)
- for tmp in user_attend_record:
- class_detail = await Class_detail.get(id= tmp.class_detail_id)
- hour += float(class_detail.hour)
- user = await User.get(id = user_id)
- user.points = int(hour/3)
- await user.save()
- return {"msg":"success record point", "code": 200}
-
- else :
- return {"msg":"no user_id", "code": 500}
-
- except Exception as e:
- return {"msg": str(e), "code": 500}
- @classes.post("/delete_attend_record")
- async def delete_attend_record(
- id : int = 0
- ):
- try :
- record = await Attend_record.get(id=id)
- await count_point(user_id=record.user_id)
- await Attend_record.filter(id=id).delete()
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.get("/update_attend_record")
- async def update_attend_record(
- id : int = 0,
- class_detail_id : Optional[int] = None,
- user_id : Optional[int] = None,
- is_attend : Optional[int] = None
- ):
- if not id :
- return {"msg":"please input id"}
-
- try :
- tmp = await Attend_record.get(id=id)
- if class_detail_id!=None:
- tmp.class_detail_id = class_detail_id
- if user_id!=None:
- tmp.user_id = user_id
- if is_attend!=None:
- tmp.is_attend = is_attend
- await tmp.save()
- await count_point(user_id=tmp.user_id)
- return {"msg": "success", "code": 200}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
- @classes.get("/get_attend_record")
- async def get_attend_record(
- class_event_id : Optional[int] = None,
- class_detail_id : Optional[int] = None,
- user_id : Optional[int] = None,
- is_attend : Optional[int] = None
- ):
- try:
- attend_record_list = Attend_record.all()
- if class_event_id:
- id_list = []
- class_detail_list = await Class_detail.filter(class_list_id = class_event_id)
- for tmp in class_detail_list :
- id_list.append(tmp.id)
- attend_record_list = Attend_record.filter(class_detail_id__in=id_list)
-
- if class_detail_id:
- attend_record_list = attend_record_list.filter(class_detail_id = class_detail_id)
- if user_id :
- attend_record_list = attend_record_list.filter(user_id = user_id)
- if is_attend :
- attend_record_list = attend_record_list.filter(is_attend = is_attend)
- attend_record_list = await attend_record_list.all()
- attend_records = []
- for obj in attend_record_list:
- class_detail_list = await Class_detail.filter(id = obj.class_detail_id)
- #registration_list = await Registration.filter(event_id = class_detail_list[0].class_list_id,user_id =obj.user_id)
- user_list = await User.filter(id = obj.user_id)
- user_information_list = await User_information.filter(user_id = obj.user_id)
- #if len(registration_list)==0:
- # continue
- data = {
- "id" :obj.id,
- "event_id":class_detail_list[0].class_list_id,
- "class_detail_id" :obj.class_detail_id,
- "user_id" :obj.user_id,
- "is_attend" :obj.is_attend,
- #"reg_confirm" : registration_list[0].reg_confirm,
- #"payment_status": registration_list[0].payment_status,
- #"five_digits": registration_list[0].five_digits,
- "real_name": user_information_list[0].name,
- "phone": user_information_list[0].phone,
- "email": user_list[0].email
- }
-
- attend_records.append(data)
- return {"msg": "success", "code": 200,"attend_record_list":attend_records}
- except Exception as e:
- return {"msg": str(e), "code": 500}
-
|