Skip to content

Commit

Permalink
add transaction_price
Browse files Browse the repository at this point in the history
  • Loading branch information
WSL0809 committed Jun 2, 2024
1 parent 004605d commit 55e41ec
Show file tree
Hide file tree
Showing 9 changed files with 25 additions and 87 deletions.
80 changes: 6 additions & 74 deletions api/get_all_clients.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
from typing import Union, List, Dict, Optional
from typing import Union, List, Optional

from fastapi import Depends, APIRouter, HTTPException, Query
from pydantic import BaseModel
from sqlalchemy import text
from sqlalchemy.orm import Session

from auth import get_current_active_user
from auth_schema import User
from database import get_db
from model import Client
from schema import ClientBase, Baby
from schema import Baby
import re

router = APIRouter()
Expand Down Expand Up @@ -39,9 +36,7 @@ class ClientGet(BaseModel):
assigned_baby_nurse: Union[int, None]
room: Union[str, None]
due_date: Union[str, None]
# class Config:
# from_attributes=True
# orm_mode = True
transaction_price: Union[float, None]


class GetAllClientsResp(BaseModel):
Expand All @@ -59,81 +54,16 @@ def clean_input(input_string):
return cleaned


# def get_clients(db: Session, name: Optional[str], page: int, limit: int):
# # 计算起始记录
#
# offset = (page - 1) * limit
#
# query = db.query(Client)
# if name:
# name = clean_input(name)
# query = query.filter(Client.name.ilike(f"%{name}%"))
#
# # 查询客户数据
# clients = query.offset(offset).limit(limit).all()
#
# clients_data = [ClientGet.from_orm(client) for client in clients]
#
# # 计算总记录数
# total = query.count()
# print(total)
# return total, clients_data


from sqlalchemy import text
from sqlalchemy.orm import Session


# def get_clients(db: Session, name: Optional[str], page: int, limit: int):
# # 基础查询语句,始终包含 GROUP BY
# base_query = """
# SELECT c.id, c.status, c.name, c.tel, c.age, c.scheduled_date, c.check_in_date, c.hospital_for_childbirth,
# c.contact_name, c.contact_tel, c.meal_plan_id, c.recovery_plan_id, c.mode_of_delivery,
# c.assigned_baby_nurse, c.room, c.due_date, json_agg(b.*) as babies
# FROM client c
# LEFT JOIN baby b ON c.id = b.client_id
# """
#
# # 构建 WHERE 子句和完整的查询
# if name:
# where_clause = "WHERE c.name ILIKE :name"
# full_query = f"""
# {base_query}
# {where_clause}
# GROUP BY c.id
# ORDER BY c.id
# OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY
# """
# count_query = f"SELECT COUNT(DISTINCT c.id) FROM client c {where_clause}"
# params = {'name': f'%{name}%', 'offset': (page - 1) * limit, 'limit': limit}
# else:
# full_query = f"""
# {base_query}
# GROUP BY c.id
# ORDER BY c.id
# OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY
# """
# count_query = "SELECT COUNT(DISTINCT c.id) FROM client c"
# params = {'offset': (page - 1) * limit, 'limit': limit}
#
# try:
# # 执行查询
# clients = db.execute(text(full_query), params).mappings().all()
#
# # 计算总数
# total = db.execute(text(count_query), {'name': f'%{name}%'} if name else {}).scalar()
#
# return total, clients
# except Exception as e:
# print(f"Error fetching clients: {e}")
# return 0, []

def get_clients(db: Session, name: Optional[str], page: int, limit: int):
# 使用 COALESCE 函数确保 babies 字段至少为空数组
base_query = """
SELECT c.id, c.status, c.name, c.tel, c.age, c.scheduled_date, c.check_in_date, c.hospital_for_childbirth,
c.contact_name, c.contact_tel, c.meal_plan_id, c.recovery_plan_id, c.mode_of_delivery,
c.assigned_baby_nurse, c.room, c.due_date,
c.assigned_baby_nurse, c.room, c.due_date, c.transaction_price,
COALESCE(json_agg(b.*) FILTER (WHERE b.baby_id IS NOT NULL), '[]') AS babies
FROM client c
LEFT JOIN baby b ON c.id = b.client_id
Expand Down Expand Up @@ -163,6 +93,8 @@ def get_clients(db: Session, name: Optional[str], page: int, limit: int):
except Exception as e:
print(f"Error fetching clients: {e}")
return 0, []


@router.get("/get_clients", response_model=GetAllClientsResp)
def get_clients_by_name(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db),
name: Optional[str] = Query(None), page: int = 1, limit: int = 10):
Expand Down
10 changes: 5 additions & 5 deletions api/get_all_rooms.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
from typing import Optional, Union, Dict
from typing import Union, Dict

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import text
from sqlalchemy.engine import row
from sqlalchemy.orm import Session
from pydantic import BaseModel, Json
from pydantic import BaseModel
from starlette import status

from auth import get_current_active_user
from auth_schema import User
from database import get_db
from model import Room, Client
from model.client import BabyNurse

router = APIRouter()

Expand All @@ -35,6 +32,8 @@ class GetAllRoomsResp(BaseModel):
scheduled_date: Union[str, None]
check_in_date: Union[str, None]
due_date: Union[str, None]
transaction_price: Union[float, None]


@router.get("/get_all_rooms")
def get_all_room_info(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
Expand All @@ -48,6 +47,7 @@ def get_all_room_info(current_user: User = Depends(get_current_active_user), db:
client.scheduled_date AS scheduled_date,
client.check_in_date AS check_in_date,
client.due_date AS due_date,
client.transaction_price AS transaction_price,
baby_nurse.name AS baby_nurse_name,
meal_plan.details AS meal_plan_details,
meal_plan.duration AS meal_plan_duration,
Expand Down
2 changes: 2 additions & 0 deletions api/get_client_by_room_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class ClientResp(BaseModel):
mode_of_delivery: str
assigned_baby_nurse_name: Union[str, None]
room: Union[str, None]
transaction_price: Union[float, None]

@field_validator('babies', mode='before')
def parse_babies(cls, value):
Expand All @@ -57,6 +58,7 @@ def do_get_client_in_room(db: Session, room_number: str):
client.hospital_for_childbirth,
client.contact_name,
client.contact_tel,
client.transaction_price AS transaction_price,
meal_plan.meal_plan_id AS meal_plan_id,
recovery_plan.recovery_plan_id AS recovery_plan_id,
mode_of_delivery,
Expand Down
13 changes: 7 additions & 6 deletions api/insert_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ class InsertClientRecv(BaseModel):
recovery_plan_seller: Union[Dict, None] = {}
due_date: Union[str, None] = None
status: str
transaction_price: Union[float, None]

class Config:
orm_mode = True


def update_client_and_room(db, insert_client_recv: InsertClientRecv):


reserve_recv_dict = dict(insert_client_recv)
reserve_recv_dict["meal_plan_seller"] = json.dumps(insert_client_recv.meal_plan_seller)
reserve_recv_dict["recovery_plan_seller"] = json.dumps(insert_client_recv.recovery_plan_seller)
Expand All @@ -52,8 +52,8 @@ def update_client_and_room(db, insert_client_recv: InsertClientRecv):
try:
create_client_sql = text(
"""
INSERT INTO client (name, tel, age, scheduled_date, check_in_date, hospital_for_childbirth, contact_name, contact_tel, mode_of_delivery, room, meal_plan_id, recovery_plan_id, assigned_baby_nurse, id_number, status, meal_plan_seller, recovery_plan_seller, due_date)
VALUES (:name, :tel, :age, :scheduled_date, :check_in_date, :hospital_for_childbirth, :contact_name, :contact_tel, :mode_of_delivery, :room, :meal_plan_id, :recovery_plan_id, :assigned_baby_nurse, :id_number, :status, :meal_plan_seller, :recovery_plan_seller, :due_date)
INSERT INTO client (name, tel, age, scheduled_date, check_in_date, hospital_for_childbirth, contact_name, contact_tel, mode_of_delivery, room, meal_plan_id, recovery_plan_id, assigned_baby_nurse, id_number, status, meal_plan_seller, recovery_plan_seller, due_date, transaction_price)
VALUES (:name, :tel, :age, :scheduled_date, :check_in_date, :hospital_for_childbirth, :contact_name, :contact_tel, :mode_of_delivery, :room, :meal_plan_id, :recovery_plan_id, :assigned_baby_nurse, :id_number, :status, :meal_plan_seller, :recovery_plan_seller, :due_date, :transaction_price)
"""
)
db.execute(create_client_sql, reserve_recv_dict)
Expand All @@ -66,8 +66,8 @@ def update_client_and_room(db, insert_client_recv: InsertClientRecv):
try:
create_client_sql_without_room = text(
"""
INSERT INTO client (name, tel, age, scheduled_date, check_in_date, hospital_for_childbirth, contact_name, contact_tel, mode_of_delivery, meal_plan_id, recovery_plan_id, assigned_baby_nurse, id_number, status, meal_plan_seller, recovery_plan_seller, due_date)
VALUES (:name, :tel, :age, :scheduled_date, :check_in_date, :hospital_for_childbirth, :contact_name, :contact_tel, :mode_of_delivery, :meal_plan_id, :recovery_plan_id, :assigned_baby_nurse, :id_number, :status, :meal_plan_seller, :recovery_plan_seller, :due_date)
INSERT INTO client (name, tel, age, scheduled_date, check_in_date, hospital_for_childbirth, contact_name, contact_tel, mode_of_delivery, meal_plan_id, recovery_plan_id, assigned_baby_nurse, id_number, status, meal_plan_seller, recovery_plan_seller, due_date, transaction_price)
VALUES (:name, :tel, :age, :scheduled_date, :check_in_date, :hospital_for_childbirth, :contact_name, :contact_tel, :mode_of_delivery, :meal_plan_id, :recovery_plan_id, :assigned_baby_nurse, :id_number, :status, :meal_plan_seller, :recovery_plan_seller, :due_date, :transaction_price)
"""
)
db.execute(create_client_sql_without_room, reserve_recv_dict)
Expand All @@ -77,6 +77,7 @@ def update_client_and_room(db, insert_client_recv: InsertClientRecv):
db.rollback()
raise HTTPException(status_code=400, detail=f"ERROR: {e}")


@router.post("/insert_client")
async def insert_client(insert_client_recv: InsertClientRecv, current_user: User = Depends(get_current_active_user),
db: Session = Depends(get_db)):
Expand Down
6 changes: 4 additions & 2 deletions api/reserve.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class ReserveRecv(BaseModel):
recovery_plan_seller: Union[Dict, None] = {}
due_date: Union[str, None] = None
status: str
transaction_price: Union[float, None]

class Config:
orm_mode = True
Expand All @@ -57,8 +58,8 @@ def update_client_and_room(db, reserve_recv: ReserveRecv):

create_client_sql = text(
"""
INSERT INTO client (name, tel, age, scheduled_date, check_in_date, hospital_for_childbirth, contact_name, contact_tel, mode_of_delivery, room, meal_plan_id, recovery_plan_id, assigned_baby_nurse, id_number, status, meal_plan_seller, recovery_plan_seller, due_date)
VALUES (:name, :tel, :age, :scheduled_date, :check_in_date, :hospital_for_childbirth, :contact_name, :contact_tel, :mode_of_delivery, :room, :meal_plan_id, :recovery_plan_id, :assigned_baby_nurse, :id_number, :status, :meal_plan_seller, :recovery_plan_seller, :due_date)
INSERT INTO client (name, tel, age, scheduled_date, check_in_date, hospital_for_childbirth, contact_name, contact_tel, mode_of_delivery, room, meal_plan_id, recovery_plan_id, assigned_baby_nurse, id_number, status, meal_plan_seller, recovery_plan_seller, due_date, transaction_price)
VALUES (:name, :tel, :age, :scheduled_date, :check_in_date, :hospital_for_childbirth, :contact_name, :contact_tel, :mode_of_delivery, :room, :meal_plan_id, :recovery_plan_id, :assigned_baby_nurse, :id_number, :status, :meal_plan_seller, :recovery_plan_seller, :due_date, :transaction_price)
RETURNING id
"""
)
Expand Down Expand Up @@ -88,6 +89,7 @@ def update_client_and_room(db, reserve_recv: ReserveRecv):
"meal_plan_seller": json.dumps(reserve_recv.meal_plan_seller),
"recovery_plan_seller": json.dumps(reserve_recv.recovery_plan_seller),
"due_date": reserve_recv.due_date,
"transaction_price": reserve_recv.transaction_price
}

try:
Expand Down
Binary file modified crud/.DS_Store
Binary file not shown.
Binary file modified model/.DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions model/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class Client(Base):
recovery_plan_seller = Column(JSONB)
due_date = Column(String(255))
babies = relationship("Baby", back_populates="client")
transaction_price = Column(DECIMAL(10, 2))


class Baby(Base):
Expand Down
Binary file modified schema/.DS_Store
Binary file not shown.

0 comments on commit 55e41ec

Please sign in to comment.