Ver Fonte

Merge branch 'master' of http://git.choozmo.com:3000/zooey/ntcri

Mia Cheng há 1 ano atrás
pai
commit
ab584d5c9e
4 ficheiros alterados com 188 adições e 8 exclusões
  1. 3 1
      app/api/__init__.py
  2. 31 6
      app/api/registration.py
  3. 122 0
      app/api/tgc.py
  4. 32 1
      app/models/models.py

+ 3 - 1
app/api/__init__.py

@@ -6,6 +6,7 @@ from app.api.news import news
 from app.api.guidance import guidance
 from app.api.registration import registration
 from app.api.article import article
+from app.api.tgc import tgc
 
 routers = APIRouter()
 
@@ -14,4 +15,5 @@ routers.include_router(classes, prefix="/api", tags=["課程列表"])
 routers.include_router(news, prefix="/api", tags=["最新消息"])
 routers.include_router(guidance, prefix="/api", tags=["輔導團紀錄"])
 routers.include_router(registration, prefix="/api", tags=["報名課程"])
-routers.include_router(article, prefix="/api", tags=["文章"])
+routers.include_router(article, prefix="/api", tags=["文章"])
+routers.include_router(tgc, prefix="/api", tags=["希望工程"])

+ 31 - 6
app/api/registration.py

@@ -1,3 +1,5 @@
+import json
+
 from fastapi_login import LoginManager
 from fastapi import APIRouter, Form, Depends, HTTPException, File, UploadFile
 from typing import List,Optional,Union
@@ -150,13 +152,23 @@ async def input_information(
     gender : str = Form(default=''),
     phone : str = Form(default=''),
     address : str = Form(default=''),
-    user_id = Depends(check_token)
+    user_id = Depends(check_token),
+    position: str = Form(...),
 ):
     try :
         if not user_id :
             return  {"msg": "no access", "code": 200}
-        
-        
+
+        position_list = json.loads(position)
+        d = {"學員":0,"開課工藝家":0,"其他":0}
+        if 1 in position_list:
+            d["學員"] = 1
+        if 2 in position_list:
+            d["開課工藝家"] = 1
+        if 3 in position_list:
+            d["其他"] = 1
+        print(d)
+
         inform = await User_information.get_or_create(
         user_id=user_id,
             defaults={
@@ -164,7 +176,8 @@ async def input_information(
                 'birthday' :birthday,
                 'gender': gender,
                 'phone': phone,
-                'address': address
+                'address': address,
+                'position': d,
             }
         )
 
@@ -187,7 +200,8 @@ async def update_information(
     gender : str = Form(default=''),
     phone : str = Form(default=''),
     address : str = Form(default=''),
-    user_id = Depends(check_token)
+    user_id = Depends(check_token),
+    position : str = Form(default=''),
 ):
     try :
         if not user_id :
@@ -195,6 +209,14 @@ async def update_information(
         
         infor = await User_information.get(user_id = user_id)
         user = await User.get(id = user_id)
+        position_list = json.loads(position)
+        d = {"學員":0,"開課工藝家":0,"其他":0}
+        if 1 in position_list:
+            d["學員"] = 1
+        if 2 in position_list:
+            d["開課工藝家"] = 1
+        if 3 in position_list:
+            d["其他"] = 1
 
         if name != '':
             infor.name = name
@@ -213,6 +235,8 @@ async def update_information(
 
         if user_name != '':
             user.username = user_name
+        if position != '':
+            infor.position = d
         
         await infor.save()
         await user.save()
@@ -257,13 +281,14 @@ async def get_user_information(
                     user_inform["address"]  = inform.address
                     user_inform["msg"] = "user information exist"
                     user_inform["exist"] = True
+                    user_inform["position"] = inform.position
                     
                 except:
                     user_inform["msg"] = "no user information"
                     user_inform["exist"] = False
 
             user_inform_list.append(user_inform)
-
+        print(user_inform_list)
 
         return {"msg":"success","code":200,"user_inform": user_inform_list}
     except Exception as e:

+ 122 - 0
app/api/tgc.py

@@ -0,0 +1,122 @@
+from fastapi import APIRouter, Form, Depends, HTTPException, File, UploadFile
+from typing import List,Optional,Union
+from fastapi.responses import FileResponse
+from random import randint
+from fastapi.security import OAuth2PasswordRequestForm
+from app.models.models import Tgc_pic,Tgc_report
+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 jose import jwt
+from emails.template import JinjaTemplate
+from tortoise.queryset import Q
+from fastapi.responses import HTMLResponse
+
+tgc = APIRouter()
+
+IMAGEDIR = "/var/www/ntcri/assets/tgc_files/"
+IMAGEDIR_short = "assets/tgc_files/"
+
+
+@tgc.post("/upload_tgc_pic")
+async def create_upload_files(files:Optional[List[UploadFile]] = File(None)):
+    files_url = []
+    if files :
+        for file in files:
+            contents = await file.read()
+
+            #save the file
+            with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
+                f.write(contents)
+                files_url.append(f"{IMAGEDIR_short}{file.filename}")       
+
+    return files_url
+
+@tgc.get("/get_tgc_report")
+async def get_tgc_report(
+    id : Optional[int] = None,
+    keyword : Optional[str] = None,
+    page_num : Optional[int] = None,
+    page_amount : Optional[int] = None
+):
+    try:
+        report_list = Tgc_report.all()
+
+        if id :
+            report_list = report_list.filter(id = id).all()
+
+        if keyword:
+            for word in keyword.split(","):
+                report_list = report_list.filter(title__icontains = word).all()
+
+
+        count = await report_list.all().count()
+
+        if page_num and page_amount:
+            report_list = report_list.offset((page_num-1)*page_amount).limit(page_amount)
+
+        report_list = await report_list.all().order_by("-create_time")
+
+        result = []
+
+        for report_obj in report_list:
+            try :
+                result.append(report_obj.show_data())
+            except Exception as e:
+                result.append({"msg": str(e)})
+
+        return {"msg": "success", "code": 200, "total_num":count,"tgc_report": result }
+    except Exception as e:
+        return {"msg": str(e), "code": 500}
+    
+@tgc.post("/input_tgc_report")
+async def input_tgc_report(
+    title : str = Form(default=''),
+    create_time : str = Form(default=datetime.now()),
+    url : str = Form(default='')
+):
+    try:
+        new_report = await Tgc_report.create(
+            title = title,
+            create_time = create_time,
+            url = url
+        )
+
+        return {"msg": "success", "code": 200, "new_report": new_report.id}
+    except Exception as e:
+        return {"msg": str(e), "code": 500}
+    
+@tgc.get("/get_tgc_img")
+async def get_tgc_img(
+    id : Optional[int] = None,
+    page_num : Optional[int] = None,
+    page_amount : Optional[int] = None
+):
+    try:
+        tgc_pic_list = Tgc_pic.all()
+
+        Q_word=Q()
+        
+        if id :
+            Q_word = Q(id=id)
+
+        tgc_pic_list = tgc_pic_list.filter(Q_word)  
+
+        count = await tgc_pic_list.all().count()
+
+        if page_num and page_amount:
+            tgc_pic_list = tgc_pic_list.offset((page_num-1)*page_amount).limit(page_amount)
+
+        tgc_pic_list= await tgc_pic_list.all()
+        result = []
+
+        for obj in tgc_pic_list:
+            result.append(obj.show_data())
+
+        return {"msg": "success", "code": 200, "tgc_pic": result }
+    except Exception as e:
+        return {"msg": str(e), "code": 500}

+ 32 - 1
app/models/models.py

@@ -6,6 +6,7 @@ from tortoise import fields
 from tortoise.models import Model
 from pydantic import BaseModel
 from datetime import datetime
+
 class User(Model):
     id = fields.IntField(pk=True)
     username = fields.CharField(max_length=30, unique=True, description="帳號")
@@ -14,7 +15,6 @@ class User(Model):
     points = fields.IntField(description="點數")
     is_superuser = fields.IntField(description="超級使用者")
     token = fields.CharField(max_length=200)
-    # position = fields.CharField(max_length=200,description="登入身分")
     is_active = fields.IntField(description="是否已認證")
 
 class UserPydantic(BaseModel):
@@ -143,6 +143,7 @@ class Registration(Model):
     is_del = fields.IntField(description="是否取消(1:yes ,0:no)")
     create_time = fields.DatetimeField(description="創建時間")
 
+
 class News(Model):
     id = fields.IntField(pk=True)
     title = fields.CharField(max_length=200, description="標題")
@@ -217,6 +218,7 @@ class User_information(Model):
     phone = fields.CharField(max_length=45, description="電話")
     address = fields.TextField(description="地址")
     is_default = fields.IntField(description="是否為預設")
+    position = fields.JSONField(max_length=200,description="登入身分")
 
 class Class_date(Model):
     id = fields.IntField(pk=True)
@@ -289,4 +291,33 @@ class User_resume(Model):
             "media": self.media,
             "imgs": self.imgs,
             "introduction": self.introduction
+<<<<<<< HEAD
+=======
+        }
+    
+class Tgc_pic(Model):
+    id = fields.IntField(pk=True)
+    pic_name = fields.TextField(description="照片名稱", null=True)
+    pic_url = fields.TextField(description="照片連結", null=True)
+
+    def show_data(self):
+        return {
+            "id" : self.id,
+            "pic_name": self.pic_name,
+            "pic_url": self.pic_url
+        }
+    
+class Tgc_report(Model):
+    id = fields.IntField(pk=True)
+    title = fields.CharField(max_length=100,description="標題", null=True)
+    create_time = fields.DatetimeField(description="創建時間", null=True)
+    url = fields.TextField(description="連結", null=True)
+
+    def show_data(self):
+        return {
+            "id" : self.id,
+            "title": self.title,
+            "create_time": self.create_time,
+            "url": self.url
+>>>>>>> 01af6c4a39305844d58fd72484a523aadc029b7c
         }