feat: frontend

This commit is contained in:
2025-11-17 21:07:51 -07:00
parent dd0ab39985
commit e1396e2d24
87 changed files with 13616 additions and 148 deletions

BIN
api/__debug_bin2117125024 Executable file

Binary file not shown.

View File

@@ -8,6 +8,7 @@ import (
"log"
"net/http"
"net/url"
"ordr-api/dto"
"os"
"github.com/gin-contrib/sessions"
@@ -81,7 +82,10 @@ func LoginHandler(auth *Authenticator) gin.HandlerFunc {
}
audience_url := "https://" + os.Getenv("AUTH0_DOMAIN") + "/api/v2/"
auth_url := auth.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("audience", audience_url))
ctx.Redirect(http.StatusTemporaryRedirect, auth_url)
var redirect dto.LoginRedirect
redirect.Status = "200 OK"
redirect.Location = auth_url
ctx.JSON(http.StatusOK, redirect)
}
}
@@ -163,7 +167,7 @@ func AuthenticationCallbackHandler(auth *Authenticator) gin.HandlerFunc {
}
// Redirect to logged in page.
ctx.Redirect(http.StatusTemporaryRedirect, "/user")
ctx.Redirect(http.StatusTemporaryRedirect, os.Getenv("LOGGED_IN_REDIRECT"))
}
}

View File

@@ -86,6 +86,9 @@ func HandleRefreshToken(session sessions.Session) bool {
}
refresh_token := session.Get("refresh_token")
if refresh_token == nil {
return false
}
refresh_request_dto := dto.RefreshTokenRequest{
GrantType: "refresh_token",
ClientId: os.Getenv("AUTH0_CLIENT_ID"),
@@ -139,28 +142,23 @@ func IsAuthenticated(auth *auth.Authenticator) gin.HandlerFunc {
return func(context *gin.Context) {
session := sessions.Default(context)
if session.Get("profile") == nil {
context.Redirect(http.StatusSeeOther, "/auth/login")
context.Abort()
return
}
refresh_token := session.Get("refresh_token")
access_token := session.Get("access_token")
if access_token == nil {
context.Redirect(http.StatusSeeOther, "/auth/login")
return
}
log.Printf("%s", refresh_token)
if access_token != nil {
if TokenIsNotExpired(access_token.(string)) {
context.Next()
} else {
if !HandleRefreshToken(session) {
context.Redirect(http.StatusSeeOther, "/auth/login")
return
} else {
}
}
if !HandleRefreshToken(session) {
context.AbortWithStatus(http.StatusUnauthorized)
return
}
context.Next()
}
}
}
}

View File

@@ -17,6 +17,7 @@ func IsAdmin(pool *pgxpool.Pool) gin.HandlerFunc {
if conn_err != nil {
log.Println(conn_err)
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
defer conn.Release()

View File

@@ -27,12 +27,12 @@ func CreateItem(pool *pgxpool.Pool) gin.HandlerFunc {
item_name := ctx.Query("item_name")
in_season := ctx.Query("in_season") == "1"
if item_name == "" {
ctx.String(http.StatusBadRequest, "CreateItem(): ERROR... Item Name not supplied")
ctx.JSON(http.StatusBadRequest, "CreateItem(): ERROR... Item Name not supplied")
}
_, exec_err := conn.Exec(context.Background(), queries.CREATE_ITEM, item_name, in_season)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, "CreateItem(): ERROR... Failed to create item")
ctx.JSON(http.StatusInternalServerError, "CreateItem(): ERROR... Failed to create item")
log.Printf("CreateItem(): ERROR... Failed to create item... %s", exec_err.Error())
return
}
@@ -40,7 +40,7 @@ func CreateItem(pool *pgxpool.Pool) gin.HandlerFunc {
var item_id int
query_err := conn.QueryRow(context.Background(), "SELECT id FROM item WHERE item_name = $1", item_name).Scan(&item_id)
if query_err != nil {
ctx.String(http.StatusInternalServerError, "CreateItem(): ERROR... Failed to get nwely created item id")
ctx.JSON(http.StatusInternalServerError, "CreateItem(): ERROR... Failed to get nwely created item id")
log.Printf("CreateItem(): ERROR... Failed to get newly created item... %s", query_err.Error())
return
}
@@ -48,20 +48,20 @@ func CreateItem(pool *pgxpool.Pool) gin.HandlerFunc {
item_price := ctx.Query("item_price")
if item_price == "" {
ctx.String(http.StatusBadRequest, "CreateItem(): ERROR... item_price not supplied")
ctx.JSON(http.StatusBadRequest, "CreateItem(): ERROR... item_price not supplied")
return
}
item_price_float, convert_err := strconv.ParseFloat(item_price, 64)
if convert_err != nil {
ctx.String(http.StatusBadRequest, "CreateUser(): ERROR... Failed to create item price: item price invalid format")
ctx.JSON(http.StatusBadRequest, "CreateUser(): ERROR... Failed to create item price: item price invalid format")
return
}
_, exec_price_err := conn.Exec(context.Background(), queries.CREATE_ITEM_PRICE, item_id, item_price)
if exec_price_err != nil {
ctx.String(http.StatusInternalServerError, "CreateItem(): ERROR... Failed to insert price...")
ctx.JSON(http.StatusInternalServerError, "CreateItem(): ERROR... Failed to insert price...")
log.Printf("CreateItem(): ERROR... Failed to insert price... %s", exec_price_err.Error())
return
}
@@ -87,42 +87,42 @@ func SetItemPrice(pool *pgxpool.Pool) gin.HandlerFunc {
item_id_string := ctx.Query("item_id")
if item_id_string == "" {
ctx.String(http.StatusBadRequest, "SetItemPrice(): ERROR... item id not provided")
ctx.JSON(http.StatusBadRequest, "SetItemPrice(): ERROR... item id not provided")
return
}
_, exec_date_err := conn.Exec(context.Background(), queries.SET_ITEM_PRICE_VALID_TO_DATE, item_id_string)
if exec_date_err != nil {
ctx.String(http.StatusInternalServerError, "SetItemPrice(): ERROR... Failed to set valid_to date")
ctx.JSON(http.StatusInternalServerError, "SetItemPrice(): ERROR... Failed to set valid_to date")
log.Printf("SetItemPrice(): ERROR... Failed to set valid_to date... %s", exec_date_err.Error())
return
}
item_price_string := ctx.Query("item_price")
if item_price_string == "" {
ctx.String(http.StatusBadRequest, "SetItemPrice(): ERROR... Item Price Not Provided")
ctx.JSON(http.StatusBadRequest, "SetItemPrice(): ERROR... Item Price Not Provided")
return
}
item_price_float, item_price_conv_err := strconv.ParseFloat(item_price_string, 64)
if item_price_conv_err != nil {
ctx.String(http.StatusBadRequest, "SetItemPrice(): ERROR... item price not valid")
ctx.JSON(http.StatusBadRequest, "SetItemPrice(): ERROR... item price not valid")
return
}
_, exec_new_price_err := conn.Exec(context.Background(), queries.CREATE_ITEM_PRICE, item_id_string, item_price_float)
if exec_new_price_err != nil {
ctx.String(http.StatusInternalServerError, "SetItemPrice(): ERROR... failed to create item price")
ctx.JSON(http.StatusInternalServerError, "SetItemPrice(): ERROR... failed to create item price")
log.Printf("SetItemPrice(): ERROR... failed to create item price... %s", exec_new_price_err.Error())
return
}
var item_price_object dto.ItemPriceResponse
query_item_price_err := conn.QueryRow(context.Background(), queries.GET_CURRENT_ITEM_PRICE, item_id_string).Scan(&item_price_object.ItemId, &item_price_object.ItemName, &item_price_object.ItemPrice)
query_item_price_err := conn.QueryRow(context.Background(), queries.GET_CURRENT_ITEM_PRICE, item_id_string).Scan(&item_price_object.ItemId, &item_price_object.ItemName, &item_price_object.ItemPrice, &item_price_object.InSeason)
if query_item_price_err != nil {
ctx.String(http.StatusInternalServerError, "SetItemPrice(): ERROR... Failed to query item price")
log.Println("SetItemPrice(): ERROR... Failed to query item price... %s", query_item_price_err.Error())
ctx.JSON(http.StatusInternalServerError, "SetItemPrice(): ERROR... Failed to query item price")
log.Printf("SetItemPrice(): ERROR... Failed to query item price... %s", query_item_price_err.Error())
return
}
@@ -142,21 +142,22 @@ func GetCurrentItemPrice(pool *pgxpool.Pool) gin.HandlerFunc {
item_id := ctx.Query("item_id")
if item_id == "" {
ctx.String(http.StatusBadRequest, "GetCurrentItemPrice(): ERROR... item id not provided")
ctx.JSON(http.StatusBadRequest, "GetCurrentItemPrice(): ERROR... item id not provided")
return
}
var item_price dto.ItemPriceResponse
query_err := conn.QueryRow(context.Background(), queries.GET_CURRENT_ITEM_PRICE, item_id).Scan(&item_price.ItemId, &item_price.ItemName, &item_price.ItemPrice)
query_err := conn.QueryRow(context.Background(), queries.GET_CURRENT_ITEM_PRICE, item_id).Scan(&item_price.ItemId, &item_price.ItemName, &item_price.ItemPrice, &item_price.InSeason)
if query_err != nil {
if query_err == pgx.ErrNoRows {
ctx.String(http.StatusBadRequest, "GetCurrentItemPrice(): ERROR... no rows match id")
ctx.JSON(http.StatusBadRequest, "GetCurrentItemPrice(): ERROR... no rows match id")
return
}
ctx.String(http.StatusInternalServerError, "GetCurrentItemPrice(): ERROR... failed to query db")
ctx.JSON(http.StatusInternalServerError, "GetCurrentItemPrice(): ERROR... failed to query db")
log.Printf("GetCurrentItemPrice(): ERROR... failed to query db... %s", query_err.Error())
return
}
ctx.JSON(http.StatusOK, item_price)
@@ -179,7 +180,7 @@ func AddItemToOrder(pool *pgxpool.Pool) gin.HandlerFunc {
created_at := ctx.Query("created_at")
if item_id == "" || order_id == "" || quantity == "" {
ctx.String(http.StatusBadRequest, "AddItemToOrder(): ERROR... item_id, order_id, or quantity missing")
ctx.JSON(http.StatusBadRequest, "AddItemToOrder(): ERROR... item_id, order_id, or quantity missing")
return
}
@@ -190,29 +191,29 @@ func AddItemToOrder(pool *pgxpool.Pool) gin.HandlerFunc {
int_item_id, item_id_parse_err := strconv.ParseInt(item_id, 10, 64)
if item_id_parse_err != nil {
ctx.String(http.StatusBadRequest, "AddItemToOrder: ERROR... item id is not an int")
ctx.JSON(http.StatusBadRequest, "AddItemToOrder: ERROR... item id is not an int")
return
}
int_order_id, order_id_parse_err := strconv.ParseInt(order_id, 10, 64)
if order_id_parse_err != nil {
ctx.String(http.StatusBadRequest, "AddItemToOrder: ERROR... order id is not an int")
ctx.JSON(http.StatusBadRequest, "AddItemToOrder: ERROR... order id is not an int")
return
}
int_quantity, quantity_parse_err := strconv.ParseInt(quantity, 10, 64)
if quantity_parse_err != nil {
ctx.String(http.StatusBadRequest, "AddItemToOrder: ERROR... quantity is not an int")
ctx.JSON(http.StatusBadRequest, "AddItemToOrder: ERROR... quantity is not an int")
return
}
_, time_parse_err := time.Parse(time.RFC3339, created_at)
if time_parse_err != nil {
ctx.String(http.StatusBadRequest, "AddItemToOrder(): ERROR... time is bad")
ctx.JSON(http.StatusBadRequest, "AddItemToOrder(): ERROR... time is bad")
return
}
_, exec_err := conn.Exec(context.Background(), queries.ADD_ITEM_TO_ORDER, int_item_id, int_order_id, int_quantity, created_at)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, "AddItemToOrder(): ERROR... failed to insert rows")
ctx.JSON(http.StatusInternalServerError, "AddItemToOrder(): ERROR... failed to insert rows")
log.Printf("AddItemToOrder(): ERROR... Failed to insert rows... %s", exec_err.Error())
return
}
@@ -220,7 +221,7 @@ func AddItemToOrder(pool *pgxpool.Pool) gin.HandlerFunc {
_, update_order_filled_exec_err := conn.Exec(context.Background(), queries.SET_ORDER_FILLED, false, order_id)
if update_order_filled_exec_err != nil {
ctx.String(http.StatusInternalServerError, "AddItemToOrder(): ERROR... failed to set order state")
ctx.JSON(http.StatusInternalServerError, "AddItemToOrder(): ERROR... failed to set order state")
log.Printf("AddItemToOrder(): ERROR... failed to set order state... %s", update_order_filled_exec_err.Error())
return
}
@@ -231,7 +232,7 @@ func AddItemToOrder(pool *pgxpool.Pool) gin.HandlerFunc {
price_scan_err := price_data_row.Scan(&order_item_price.ItemId, &order_item_price.OrderId, &order_item_price.ItemName, &order_item_price.Quantity, &order_item_price.Made, &order_item_price.CreatedAt, &order_item_price.TotalPrice, &order_item_price.UnitPrice)
if price_scan_err != nil {
ctx.String(http.StatusInternalServerError, "AddItemToOrder(): ERROR... Failed to scan price data")
ctx.JSON(http.StatusInternalServerError, "AddItemToOrder(): ERROR... Failed to scan price data")
log.Printf("AddItemToOrder(): ERROR... Failed to scan price data... %s", price_scan_err.Error())
return
}
@@ -253,20 +254,20 @@ func GetOrderItems(pool *pgxpool.Pool) gin.HandlerFunc {
order_id := ctx.Query("order_id")
if order_id == "" {
ctx.String(http.StatusBadRequest, "GetOrderItems(): ERROR: order id not supplied")
ctx.JSON(http.StatusBadRequest, "GetOrderItems(): ERROR: order id not supplied")
return
}
_, parse_err := strconv.ParseInt(order_id, 10, 64)
if parse_err != nil {
ctx.String(http.StatusBadRequest, "GetOrderItem(): ERROR... order id not an integer")
ctx.JSON(http.StatusBadRequest, "GetOrderItem(): ERROR... order id not an integer")
return
}
rows, query_err := conn.Query(context.Background(), queries.GET_ORDER_ITEMS, order_id)
if query_err != nil {
ctx.String(http.StatusInternalServerError, "GetOrderItems(): ERROR... failed to query database.")
ctx.JSON(http.StatusInternalServerError, "GetOrderItems(): ERROR... failed to query database.")
log.Printf("GetOrderItems(): ERROR... Failed to query database... %s", query_err.Error())
return
}
@@ -278,7 +279,7 @@ func GetOrderItems(pool *pgxpool.Pool) gin.HandlerFunc {
var item dto.OrderItemPriceResponse
scan_err := rows.Scan(&item.ItemId, &item.OrderId, &item.ItemName, &item.Quantity, &item.Made, &item.CreatedAt, &item.TotalPrice, &item.UnitPrice)
if scan_err != nil {
ctx.String(http.StatusInternalServerError, "GetOrderItems(): ERROR... Failed to scan data...")
ctx.JSON(http.StatusInternalServerError, "GetOrderItems(): ERROR... Failed to scan data...")
log.Printf("GetOrderItems(): ERROR... failed to scan data... %s", scan_err.Error())
return
}
@@ -303,21 +304,21 @@ func SetItemMade(pool *pgxpool.Pool) gin.HandlerFunc {
var request dto.ItemOrderSetMadeRequest
request_read_err := ctx.ShouldBindJSON(&request)
if request_read_err != nil {
ctx.String(http.StatusBadRequest, "SetItemMade(): ERROR... Error Request in bad format")
ctx.JSON(http.StatusBadRequest, "SetItemMade(): ERROR... Error Request in bad format")
return
}
_, exec_set_made_err := conn.Exec(context.Background(), queries.SET_MADE, request.Made, request.ItemId, request.OrderId)
if exec_set_made_err != nil {
ctx.String(http.StatusInternalServerError, "SetItemMade(): ERROR... Internal server error")
ctx.JSON(http.StatusInternalServerError, "SetItemMade(): ERROR... Internal server error")
log.Printf("SetItemMade(): ERROR... Failed to set item made... %s", exec_set_made_err.Error())
return
}
_, exec_update_order_err := conn.Exec(context.Background(), queries.UPDATE_ORDER_FILLED, request.OrderId)
if exec_update_order_err != nil {
ctx.String(http.StatusInternalServerError, "SetItemMade(): ERROR... Failed to update order")
ctx.JSON(http.StatusInternalServerError, "SetItemMade(): ERROR... Failed to update order")
log.Printf("SetItemMade(): ERROR... Failed to update order... %s", exec_update_order_err.Error())
return
}
@@ -326,10 +327,10 @@ func SetItemMade(pool *pgxpool.Pool) gin.HandlerFunc {
scan_err := conn.QueryRow(context.Background(), queries.GET_ORDER_MADE_DETAILS, request.OrderId).Scan(&order_filled.OrderId, &order_filled.Filled)
if scan_err != nil {
if scan_err == pgx.ErrNoRows {
ctx.String(http.StatusBadRequest, "SetItemMade(): Invalid data")
ctx.JSON(http.StatusBadRequest, "SetItemMade(): Invalid data")
return
}
ctx.String(http.StatusInternalServerError, "SetItemMade(): ERROR... Error querying result")
ctx.JSON(http.StatusInternalServerError, "SetItemMade(): ERROR... Error querying result")
log.Printf("SetItemMade(): ERROR... Error querying result... %s", scan_err.Error())
return
}
@@ -350,21 +351,21 @@ func SetItemQuantity(pool *pgxpool.Pool) gin.HandlerFunc {
var request dto.ItemOrderSetQuantityRequest
request_read_err := ctx.ShouldBindJSON(&request)
if request_read_err != nil {
ctx.String(http.StatusBadRequest, "SetItemQuantity(): ERROR... Error Request in bad format")
ctx.JSON(http.StatusBadRequest, "SetItemQuantity(): ERROR... Error Request in bad format")
return
}
_, exec_set_quantity_err := conn.Exec(context.Background(), queries.SET_QUANTITY, request.Quantity, request.ItemId, request.OrderId)
if exec_set_quantity_err != nil {
ctx.String(http.StatusInternalServerError, "SetItemMade(): ERROR... Internal server error")
ctx.JSON(http.StatusInternalServerError, "SetItemMade(): ERROR... Internal server error")
log.Printf("SetItemQuantity(): ERROR... Failed to set item quantity... %s", exec_set_quantity_err.Error())
return
}
_, exec_update_order_err := conn.Exec(context.Background(), queries.UPDATE_ORDER_FILLED, request.OrderId)
if exec_update_order_err != nil {
ctx.String(http.StatusInternalServerError, "SetItemMade(): ERROR... Failed to update order")
ctx.JSON(http.StatusInternalServerError, "SetItemMade(): ERROR... Failed to update order")
log.Printf("SetItemQuantity(): ERROR... Failed to update order... %s", exec_update_order_err.Error())
return
}
@@ -373,10 +374,10 @@ func SetItemQuantity(pool *pgxpool.Pool) gin.HandlerFunc {
scan_err := conn.QueryRow(context.Background(), queries.GET_ORDER_MADE_DETAILS, request.OrderId).Scan(&order_filled.OrderId, &order_filled.Filled)
if scan_err != nil {
if scan_err == pgx.ErrNoRows {
ctx.String(http.StatusBadRequest, "SetItemQuantity(): Invalid data")
ctx.JSON(http.StatusBadRequest, "SetItemQuantity(): Invalid data")
return
}
ctx.String(http.StatusInternalServerError, "SetItemQuantity(): ERROR... Error querying result")
ctx.JSON(http.StatusInternalServerError, "SetItemQuantity(): ERROR... Error querying result")
log.Printf("SetItemQuantity(): ERROR... Error querying result... %s", scan_err.Error())
return
}
@@ -395,16 +396,25 @@ func DeleteOrderItem(pool *pgxpool.Pool) gin.HandlerFunc {
}
defer conn.Release()
var request dto.DeleteOrderItemRequest
request_read_err := ctx.ShouldBindJSON(&request)
if request_read_err != nil {
ctx.String(http.StatusBadRequest, "DeleteOrderItem(): ERROR... invalid request")
item_id := ctx.Query("item_id")
order_id := ctx.Query("order_id")
if item_id == "" || order_id == "" {
ctx.String(http.StatusBadRequest, "DeleteOrderItem(): Bad Request")
return
}
_, exec_err := conn.Exec(context.Background(), queries.REMOVE_ITEM_FROM_ORDER, request.ItemId, request.OrderId)
item_id_int, item_parse_err := strconv.ParseInt(item_id, 10, 64)
order_id_int, order_parse_err := strconv.ParseInt(order_id, 10, 64)
if item_parse_err != nil || order_parse_err != nil {
ctx.String(http.StatusBadRequest, "DeleteOrderItem(): Bad Request")
return
}
_, exec_err := conn.Exec(context.Background(), queries.REMOVE_ITEM_FROM_ORDER, item_id_int, order_id_int)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, "DeleteOrderItem(): ERROR.. Failed to delete item")
ctx.JSON(http.StatusInternalServerError, "DeleteOrderItem(): ERROR.. Failed to delete item")
log.Printf("DeleteOrderItem(): ERROR... Failed to delte item... %s", exec_err.Error())
return
}
@@ -424,15 +434,100 @@ func DeleteItem(pool *pgxpool.Pool) gin.HandlerFunc {
item_id := ctx.Query("item_id")
item_id_int, parse_err := strconv.ParseInt(item_id, 10, 64)
if parse_err != nil || item_id == "" {
ctx.String(http.StatusBadRequest, "DeleteItem(): Invalid data entry")
ctx.JSON(http.StatusBadRequest, "DeleteItem(): Invalid data entry")
return
}
_, exec_err := conn.Exec(context.Background(), "DELETE FROM item WHERE id = $1", item_id_int)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, "DeleteItem(): Failed to delete item")
ctx.JSON(http.StatusInternalServerError, "DeleteItem(): Failed to delete item")
log.Printf("DeleteItem(): ERROR... Failed to delete item... %s", exec_err.Error())
return
}
}
}
func GetItems(pool *pgxpool.Pool) gin.HandlerFunc {
return func(ctx *gin.Context) {
conn, conn_err := pool.Acquire(ctx)
if conn_err != nil {
log.Printf("DeleteItem(): ERROR: Failed to connect... %s", conn_err.Error())
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
defer conn.Release()
rows, query_err := conn.Query(context.Background(), queries.GET_CURRENT_ITEMS_PRICE)
if query_err != nil {
ctx.JSON(http.StatusInternalServerError, "INTERNAL SERVER ERROR")
log.Printf("GetItems(): ERROR... Failed to query table... %s", query_err.Error())
return
}
var items []dto.ItemPriceResponse
for rows.Next() {
var item dto.ItemPriceResponse
scan_err := rows.Scan(&item.ItemId, &item.ItemName, &item.ItemPrice, &item.InSeason)
if scan_err != nil {
ctx.JSON(http.StatusInternalServerError, "INTERNAL SERVER ERROR")
log.Printf("GetItems(): ERROR... failed to scan info...%s", scan_err.Error())
return
}
items = append(items, item)
}
ctx.JSON(http.StatusOK, items)
}
}
func GetItemHistory(pool *pgxpool.Pool) gin.HandlerFunc {
return func(ctx *gin.Context) {
conn, conn_err := pool.Acquire(ctx)
if conn_err != nil {
log.Printf("DeleteItem(): ERROR: Failed to connect... %s", conn_err.Error())
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
defer conn.Release()
item_id := ctx.Query("item_id")
if item_id == "" {
ctx.String(http.StatusBadRequest, "Bad Request")
return
}
item_id_int, parse_err := strconv.ParseInt(item_id, 10, 64)
if parse_err != nil {
ctx.String(http.StatusBadRequest, "Bad Request")
return
}
rows, query_err := conn.Query(ctx, queries.GET_ITEM_PRICE_HISTORY, item_id_int)
if query_err != nil {
ctx.String(http.StatusInternalServerError, "Internal Server Error")
log.Printf("GetItemHistory(): ERROR... Failed to query table... %s", query_err.Error())
return
}
var item_history_records []dto.ItemHistory
for rows.Next() {
var item_history_record dto.ItemHistory
scan_err := rows.Scan(&item_history_record.ItemId, &item_history_record.ItemName, &item_history_record.ItemPrice, &item_history_record.ValidFrom, &item_history_record.ValidTo)
if scan_err != nil {
ctx.String(http.StatusInternalServerError, "Internal Server Error")
log.Printf("GetItemHistory(): ERROR... Failed to query table... %s", scan_err.Error())
return
}
item_history_records = append(item_history_records, item_history_record)
}
ctx.JSON(http.StatusOK, item_history_records)
}
}

View File

@@ -35,7 +35,7 @@ func CreateOrder(pool *pgxpool.Pool) gin.HandlerFunc {
if user_query_err != nil {
log.Printf("CreateOrder(): ERROR Failed to query user... %s", user_query_err.Error())
ctx.String(http.StatusInternalServerError, "CreateOrder(): ERROR Failed to query user")
ctx.JSON(http.StatusInternalServerError, "CreateOrder(): ERROR Failed to query user")
return
}
@@ -44,7 +44,7 @@ func CreateOrder(pool *pgxpool.Pool) gin.HandlerFunc {
date_placed := ctx.Query("date_placed")
if orderer == "" || date_due == "" {
ctx.String(http.StatusBadRequest, "CreateOrder(): ERROR orderer or date_due not supplied")
ctx.JSON(http.StatusBadRequest, "CreateOrder(): ERROR orderer or date_due not supplied")
return
}
@@ -55,20 +55,20 @@ func CreateOrder(pool *pgxpool.Pool) gin.HandlerFunc {
_, placed_date_err := time.Parse(time.RFC3339, date_placed)
if placed_date_err != nil {
ctx.String(http.StatusBadRequest, "CreateOrder(): Bad time format")
ctx.JSON(http.StatusBadRequest, "CreateOrder(): Bad time format")
return
}
_, due_date_err := time.Parse(time.RFC3339, date_due)
if due_date_err != nil {
ctx.String(http.StatusBadRequest, "CreateOrder(): Bad Time format")
ctx.JSON(http.StatusBadRequest, "CreateOrder(): Bad Time format")
return
}
_, exec_err := conn.Exec(context.Background(), queries.CREATE_ORDER, current_user.Id, orderer, date_due, date_placed)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, "CreateOrder(): Failed to create order")
ctx.JSON(http.StatusInternalServerError, "CreateOrder(): Failed to create order")
log.Printf("CreateOrder(): ERROR... Failed to create order... %s", exec_err.Error())
return
}
@@ -76,7 +76,7 @@ func CreateOrder(pool *pgxpool.Pool) gin.HandlerFunc {
var order dto.OrderResponse
order_query_err := conn.QueryRow(context.Background(), queries.GET_TOTAL_ORDER_FROM_ORDER_INFORMATION, current_user.Id, orderer, date_placed).Scan(&order.Id, &order.UserId, &order.Orderer, &order.DateDue, &order.DatePlaced, &order.AmountPaid, &order.OrderTotal, &order.AmountDue, &order.Filled, &order.Delivered)
if order_query_err != nil {
ctx.String(http.StatusInternalServerError, "CreateOrder(): Failed to create order")
ctx.JSON(http.StatusInternalServerError, "CreateOrder(): Failed to create order")
log.Printf("CreateOrder(): ERROR... failed to query order after creation ... %s", order_query_err.Error())
return
}
@@ -98,7 +98,7 @@ func GetOrderByOrderId(pool *pgxpool.Pool) gin.HandlerFunc {
order_id := ctx.Query("order_id")
_, order_id_parse_err := strconv.ParseInt(order_id, 10, 64)
if order_id == "" || order_id_parse_err != nil {
ctx.String(http.StatusBadRequest, "GetOrderByOrderId(): ERROR... order_id not valid")
ctx.JSON(http.StatusBadRequest, "GetOrderByOrderId(): ERROR... order_id not valid")
return
}
@@ -110,10 +110,10 @@ func GetOrderByOrderId(pool *pgxpool.Pool) gin.HandlerFunc {
if scan_err != nil {
if scan_err == pgx.ErrNoRows {
ctx.String(http.StatusBadRequest, "GetOrderByOrderId(): ERROR... no order matches the query")
ctx.JSON(http.StatusBadRequest, "GetOrderByOrderId(): ERROR... no order matches the query")
return
}
ctx.String(http.StatusInternalServerError, "GetOrderByOrderId(): ERROR... internal server error")
ctx.JSON(http.StatusInternalServerError, "GetOrderByOrderId(): ERROR... internal server error")
log.Printf("GetOrderByOrderId(): ERROR... Failed to scan row... %s", scan_err.Error())
return
}
@@ -135,7 +135,7 @@ func GetOrderTable(pool *pgxpool.Pool) gin.HandlerFunc {
page := ctx.Query("page")
page_int, page_parse_err := strconv.ParseInt(page, 10, 64)
if page == "" || page_parse_err != nil {
ctx.String(http.StatusBadRequest, "GetOrderTable(): Invalid page number")
ctx.JSON(http.StatusBadRequest, "GetOrderTable(): Invalid page number")
return
}
@@ -143,21 +143,21 @@ func GetOrderTable(pool *pgxpool.Pool) gin.HandlerFunc {
bind_err := ctx.ShouldBindJSON(&table_query)
if bind_err != nil {
ctx.String(http.StatusBadRequest, "GetOrderTable(): ERROR... invalid query")
ctx.JSON(http.StatusBadRequest, "GetOrderTable(): ERROR... invalid query")
return
}
filter := ctx.Query("filter")
filter_int, filter_parse_err := strconv.ParseInt(filter, 10, 64)
if filter == "" || filter_parse_err != nil {
ctx.String(http.StatusBadRequest, "GetOrderTable(): Invalid Filter Options")
ctx.JSON(http.StatusBadRequest, "GetOrderTable(): Invalid Filter Options")
return
}
query_string := utils.GetOrderTableQueryString(filter_int)
rows, query_err := conn.Query(context.Background(), query_string, utils.PAGE_SIZE*page_int, utils.PAGE_SIZE, table_query.Orderer, table_query.DateDue, table_query.DatePlaced)
if query_err != nil {
ctx.String(http.StatusInternalServerError, "GetOrdertable(): ERROR... internal server error")
ctx.JSON(http.StatusInternalServerError, "GetOrdertable(): ERROR... internal server error")
log.Printf("GetOrderTable(): ERROR... Failed to query table...\nQUERY: %s\n %s", query_string, query_err.Error())
return
}
@@ -168,7 +168,7 @@ func GetOrderTable(pool *pgxpool.Pool) gin.HandlerFunc {
var order_response dto.OrderResponse
scan_err := rows.Scan(&order_response.Id, &order_response.UserId, &order_response.Orderer, &order_response.DateDue, &order_response.DatePlaced, &order_response.AmountPaid, &order_response.OrderTotal, &order_response.AmountDue, &order_response.Filled, &order_response.Delivered)
if scan_err != nil {
ctx.String(http.StatusInternalServerError, "GetOrdertable(): ERROR... internal server error")
ctx.JSON(http.StatusInternalServerError, "GetOrdertable(): ERROR... internal server error")
log.Printf("GetOrderTable(): ERROR... Failed to scan query... %s", scan_err.Error())
return
}
@@ -193,13 +193,13 @@ func DeleteOrder(pool *pgxpool.Pool) gin.HandlerFunc {
order_id := ctx.Query("order_id")
order_id_int, parse_err := strconv.ParseInt(order_id, 10, 64)
if parse_err != nil {
ctx.String(http.StatusBadRequest, "DeleteOrder(): Invalid input")
ctx.JSON(http.StatusBadRequest, "DeleteOrder(): Invalid input")
return
}
_, exec_err := conn.Exec(context.Background(), "DELETE FROM order_record WHERE id = $1", order_id_int)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, "DeleteOrder(): ERROR... failed to delete order")
ctx.JSON(http.StatusInternalServerError, "DeleteOrder(): ERROR... failed to delete order")
log.Printf("DeleteOrder(): ERROR... Failed to delete order %s", exec_err.Error())
return
}

View File

@@ -12,5 +12,5 @@ func BaseFunction(context *gin.Context) {
}
func PublicEndpoint(context *gin.Context) {
context.String(http.StatusOK, "Public endpoint for you to land at")
context.JSON(http.StatusOK, "Public endpoint for you to land at")
}

View File

@@ -20,7 +20,7 @@ func SetUserName(pool *pgxpool.Pool) gin.HandlerFunc {
defer conn.Release()
if err != nil {
// TODO: Log this error
ctx.String(http.StatusInternalServerError, err.Error())
ctx.JSON(http.StatusInternalServerError, err.Error())
log.Printf("SetUserName(): ERROR... Failed to acquire connection... %s", err.Error())
return
}
@@ -29,7 +29,7 @@ func SetUserName(pool *pgxpool.Pool) gin.HandlerFunc {
user_name := ctx.Query("user_name")
if user_name == "" {
ctx.String(http.StatusBadRequest, "CreateUser(): ERROR: user name not supplied")
ctx.JSON(http.StatusBadRequest, "CreateUser(): ERROR: user name not supplied")
return
}
@@ -46,18 +46,18 @@ func PromoteUser(pool *pgxpool.Pool) gin.HandlerFunc {
conn, conn_err := pool.Acquire(ctx)
defer conn.Release()
if conn_err != nil {
ctx.String(http.StatusInternalServerError, conn_err.Error())
ctx.JSON(http.StatusInternalServerError, conn_err.Error())
}
user_id := ctx.Query("user_id")
if user_id == "" {
ctx.String(http.StatusBadRequest, "PromoteUser(): ERROR Missing user id")
ctx.JSON(http.StatusBadRequest, "PromoteUser(): ERROR Missing user id")
return
}
_, update_err := conn.Exec(context.Background(), queries.USER_SET_IS_ADMIN_QUERY, user_id)
if update_err != nil {
ctx.String(http.StatusInternalServerError, update_err.Error())
ctx.JSON(http.StatusInternalServerError, update_err.Error())
}
}
}
@@ -66,18 +66,18 @@ func DemoteUser(pool *pgxpool.Pool) gin.HandlerFunc {
return func(ctx *gin.Context) {
conn, conn_err := pool.Acquire(ctx)
if conn_err != nil {
ctx.String(http.StatusInternalServerError, conn_err.Error())
ctx.JSON(http.StatusInternalServerError, conn_err.Error())
return
}
defer conn.Release()
user_id := ctx.Query("user_id")
if user_id == "" {
ctx.String(http.StatusBadRequest, "ERROR: User Id Not Supplied")
ctx.JSON(http.StatusBadRequest, "ERROR: User Id Not Supplied")
return
}
_, exec_err := conn.Exec(context.Background(), queries.USER_REVOKE_ADMIN_QUERY, user_id)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, exec_err.Error())
ctx.JSON(http.StatusInternalServerError, exec_err.Error())
}
}
}
@@ -93,7 +93,7 @@ func DeactivateUser(pool *pgxpool.Pool) gin.HandlerFunc {
user_id := ctx.Query("user_id")
if user_id == "" {
ctx.String(http.StatusBadRequest, "DeactivateUser(): User id not supplied")
ctx.JSON(http.StatusBadRequest, "DeactivateUser(): User id not supplied")
return
}
@@ -101,6 +101,25 @@ func DeactivateUser(pool *pgxpool.Pool) gin.HandlerFunc {
}
}
func ActivateUser(pool *pgxpool.Pool) gin.HandlerFunc {
return func(ctx *gin.Context) {
conn, conn_err := pool.Acquire(ctx)
if conn_err != nil {
log.Printf("DeactivateUser(): ERROR: Failed to connect... %s", conn_err.Error())
ctx.AbortWithStatus(http.StatusInternalServerError)
}
defer conn.Release()
user_id := ctx.Query("user_id")
if user_id == "" {
ctx.JSON(http.StatusBadRequest, "DeactivateUser(): User id not supplied")
return
}
conn.Exec(context.Background(), queries.USER_SET_ACTIVE_QUERY, user_id)
}
}
func GetUserTable(pool *pgxpool.Pool) gin.HandlerFunc {
return func(ctx *gin.Context) {
conn, conn_err := pool.Acquire(ctx)
@@ -113,23 +132,23 @@ func GetUserTable(pool *pgxpool.Pool) gin.HandlerFunc {
var request dto.UserRequest
body_read_err := ctx.ShouldBindJSON(&request)
if body_read_err != nil {
ctx.String(http.StatusBadRequest, "GetUserTable(): ERROR... Invalid user query object")
ctx.JSON(http.StatusBadRequest, "GetUserTable(): ERROR... Invalid user query object")
return
}
page := ctx.Query("page")
if page == "" {
ctx.String(http.StatusBadRequest, "GetUserTable(): Missing page")
ctx.JSON(http.StatusBadRequest, "GetUserTable(): Missing page")
return
}
page_int, conv_err := strconv.Atoi(page)
if conv_err != nil {
ctx.String(http.StatusBadRequest, "GetUserTable(): Not an integer")
ctx.JSON(http.StatusBadRequest, "GetUserTable(): Not an integer")
return
}
rows, query_err := conn.Query(context.Background(), queries.USER_GET_TABLE_DATA, page_int*utils.PAGE_SIZE, utils.PAGE_SIZE, request.Name, request.JobPosition)
if query_err != nil {
ctx.String(http.StatusInternalServerError, "GetUserTable(): Failed to query database...")
ctx.JSON(http.StatusInternalServerError, "GetUserTable(): Failed to query database...")
log.Printf("GetUserTable(): ERROR... %s", query_err.Error())
}
defer rows.Close()
@@ -139,7 +158,7 @@ func GetUserTable(pool *pgxpool.Pool) gin.HandlerFunc {
var user dto.UserResponse
scan_err := rows.Scan(&user.Id, &user.Name, &user.JobPosition, &user.Active, &user.Admin)
if scan_err != nil {
ctx.String(http.StatusInternalServerError, "GetUserTable(): ERROR: Failed to scan..")
ctx.JSON(http.StatusInternalServerError, "GetUserTable(): ERROR: Failed to scan..")
log.Printf("GetUserTable(): ERROR... %s", scan_err.Error())
return
}
@@ -168,7 +187,7 @@ func GetCurrentAuthenticatedUser(pool *pgxpool.Pool) gin.HandlerFunc {
query_err := conn.QueryRow(context.Background(), queries.GET_CURRENT_USER_OBJECT, sub_id).Scan(&user.Id, &user.Name, &user.JobPosition, &user.Active, &user.Admin)
if query_err != nil {
ctx.String(http.StatusInternalServerError, "GetCurrentAuthenticatedUser(): ERROR.... Failed to query")
ctx.JSON(http.StatusInternalServerError, "GetCurrentAuthenticatedUser(): ERROR.... Failed to query")
log.Printf("GetCurrentAuthenticatedUser(): ERROR in querying user table... %s", query_err.Error())
return
}
@@ -189,13 +208,13 @@ func CreatePosition(pool *pgxpool.Pool) gin.HandlerFunc {
position_name := ctx.Query("position_name")
if position_name == "" {
ctx.String(http.StatusBadRequest, "CreatePosition(): ERROR... Position name not supplied!")
ctx.JSON(http.StatusBadRequest, "CreatePosition(): ERROR... Position name not supplied!")
return
}
_, exec_err := conn.Exec(context.Background(), queries.CREATE_POSITION, position_name)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, "CreatePosition(): ERROR... exec failed")
ctx.JSON(http.StatusInternalServerError, "CreatePosition(): ERROR... exec failed")
log.Println("CreatePosition(): ERROR... exec failed... %s", exec_err.Error())
return
}
@@ -215,7 +234,7 @@ func SetUserPosition(pool *pgxpool.Pool) gin.HandlerFunc {
user_id := ctx.Query("user_id")
if position_name == "" || user_id == "" {
ctx.String(http.StatusBadRequest, "SetUserPosition(): ERROR... Missing required parameter")
ctx.JSON(http.StatusBadRequest, "SetUserPosition(): ERROR... Missing required parameter")
}
var position_id string
@@ -223,17 +242,17 @@ func SetUserPosition(pool *pgxpool.Pool) gin.HandlerFunc {
query_err := conn.QueryRow(context.Background(), queries.POSITION_GET_POSITION, position_name).Scan(&position_id, &position_name_query)
if query_err != nil {
if query_err == pgx.ErrNoRows {
ctx.String(http.StatusBadRequest, "SetUserPosition(): ERROR... No such position exists.")
ctx.JSON(http.StatusBadRequest, "SetUserPosition(): ERROR... No such position exists.")
return
}
ctx.String(http.StatusInternalServerError, "SetUserPosition(): ERROR... Failed to query")
ctx.JSON(http.StatusInternalServerError, "SetUserPosition(): ERROR... Failed to query")
log.Println("SetUserPosition(): ERROR... Failed to query position table... %s", query_err.Error())
return
}
_, exec_err := conn.Exec(context.Background(), queries.USER_SET_POSITION, position_id, user_id)
if exec_err != nil {
ctx.String(http.StatusInternalServerError, "SetUserPosition(): ERROR... failed to update user object")
ctx.JSON(http.StatusInternalServerError, "SetUserPosition(): ERROR... failed to update user object")
log.Println("SetUserPosition(): ERROR... Failed to update user object... %s", exec_err.Error())
return
}

View File

@@ -0,0 +1,22 @@
package corsmiddleware
import (
"log"
"github.com/gin-gonic/gin"
)
func CORSMiddleware(c *gin.Context) {
log.Printf("%s", c.Request.Method)
c.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}

36
api/docs/docs.go Normal file
View File

@@ -0,0 +1,36 @@
// Package docs Code generated by swaggo/swag. DO NOT EDIT
package docs
import "github.com/swaggo/swag"
const docTemplate = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{escape .Description}}",
"title": "{{.Title}}",
"contact": {},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = &swag.Spec{
Version: "",
Host: "",
BasePath: "",
Schemes: []string{},
Title: "",
Description: "",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
LeftDelim: "{{",
RightDelim: "}}",
}
func init() {
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}

7
api/docs/swagger.json Normal file
View File

@@ -0,0 +1,7 @@
{
"swagger": "2.0",
"info": {
"contact": {}
},
"paths": {}
}

4
api/docs/swagger.yaml Normal file
View File

@@ -0,0 +1,4 @@
info:
contact: {}
paths: {}
swagger: "2.0"

11
api/dto/item_history.go Normal file
View File

@@ -0,0 +1,11 @@
package dto
import "time"
type ItemHistory struct {
ItemId string
ItemName string
ItemPrice string
ValidFrom time.Time
ValidTo time.Time
}

View File

@@ -4,4 +4,5 @@ type ItemPriceResponse struct {
ItemId int
ItemName string
ItemPrice float64
InSeason bool
}

View File

@@ -0,0 +1,6 @@
package dto
type LoginRedirect struct {
Status string
Location string
}

View File

@@ -4,6 +4,7 @@ go 1.25.3
require (
github.com/coreos/go-oidc/v3 v3.16.0
github.com/gin-contrib/cors v1.7.6
github.com/gin-contrib/sessions v1.0.4
github.com/gin-gonic/gin v1.11.0
github.com/golang-jwt/jwt v3.2.2+incompatible
@@ -14,42 +15,89 @@ require (
)
require (
github.com/bytedance/sonic v1.14.0 // indirect
github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/PuerkitoBio/purell v1.2.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.14.2 // indirect
github.com/bytedance/sonic/loader v0.4.0 // indirect
github.com/cilium/ebpf v0.11.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/cosiner/argv v0.1.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
github.com/derekparker/trie v0.0.0-20230829180723-39f4de51ef7d // indirect
github.com/gabriel-vasile/mimetype v1.4.11 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-delve/delve v1.25.2 // indirect
github.com/go-delve/liner v1.2.3-0.20231231155935-4726ab1d7f62 // indirect
github.com/go-jose/go-jose/v4 v4.1.3 // indirect
github.com/go-openapi/jsonpointer v0.22.1 // indirect
github.com/go-openapi/jsonreference v0.21.3 // indirect
github.com/go-openapi/spec v0.22.1 // indirect
github.com/go-openapi/swag v0.25.1 // indirect
github.com/go-openapi/swag/conv v0.25.1 // indirect
github.com/go-openapi/swag/jsonname v0.25.1 // indirect
github.com/go-openapi/swag/jsonutils v0.25.1 // indirect
github.com/go-openapi/swag/loading v0.25.1 // indirect
github.com/go-openapi/swag/stringutils v0.25.1 // indirect
github.com/go-openapi/swag/typeutils v0.25.1 // indirect
github.com/go-openapi/swag/yamlutils v0.25.1 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.27.0 // indirect
github.com/go-playground/validator/v10 v10.28.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect
github.com/google/go-dap v0.12.0 // indirect
github.com/gorilla/context v1.1.2 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
github.com/gorilla/sessions v1.4.0 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mailru/easyjson v0.9.1 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.13 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.54.0 // indirect
github.com/quic-go/quic-go v0.56.0 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/spf13/cobra v1.9.1 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/swaggo/files v1.0.1 // indirect
github.com/swaggo/gin-swagger v1.6.1 // indirect
github.com/swaggo/swag v1.16.6 // indirect
github.com/tkrajina/typescriptify-golang-structs v0.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
go.uber.org/mock v0.5.0 // indirect
golang.org/x/arch v0.20.0 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/mod v0.25.0 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/tools v0.34.0 // indirect
google.golang.org/protobuf v1.36.9 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
github.com/urfave/cli/v2 v2.27.7 // indirect
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342 // indirect
go.starlark.net v0.0.0-20231101134539-556fd59b42f6 // indirect
go.uber.org/mock v0.6.0 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/arch v0.23.0 // indirect
golang.org/x/crypto v0.44.0 // indirect
golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 // indirect
golang.org/x/mod v0.30.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sync v0.18.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 // indirect
golang.org/x/text v0.31.0 // indirect
golang.org/x/tools v0.38.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
sigs.k8s.io/yaml v1.6.0 // indirect
)

View File

@@ -1,24 +1,75 @@
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/PuerkitoBio/purell v1.2.1 h1:QsZ4TjvwiMpat6gBCBxEQI0rcS9ehtkKtSpiUnd9N28=
github.com/PuerkitoBio/purell v1.2.1/go.mod h1:ZwHcC/82TOaovDi//J/804umJFFmbOHPngi8iYYv/Eo=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
github.com/bytedance/sonic v1.14.2 h1:k1twIoe97C1DtYUo+fZQy865IuHia4PR5RPiuGPPIIE=
github.com/bytedance/sonic v1.14.2/go.mod h1:T80iDELeHiHKSc0C9tubFygiuXoGzrkjKzX2quAx980=
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/bytedance/sonic/loader v0.4.0 h1:olZ7lEqcxtZygCK9EKYKADnpQoYkRQxaeY2NYzevs+o=
github.com/bytedance/sonic/loader v0.4.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cilium/ebpf v0.11.0 h1:V8gS/bTCCjX9uUnkUFUpPsksM8n1lXBAvHcpiFk1X2Y=
github.com/cilium/ebpf v0.11.0/go.mod h1:WE7CZAnqOL2RouJ4f1uyNhqr2P4CCvXFIqdRDUgWsVs=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/coreos/go-oidc/v3 v3.16.0 h1:qRQUCFstKpXwmEjDQTIbyY/5jF00+asXzSkmkoa/mow=
github.com/coreos/go-oidc/v3 v3.16.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8=
github.com/cosiner/argv v0.1.0 h1:BVDiEL32lwHukgJKP87btEPenzrrHUjajs/8yzaqcXg=
github.com/cosiner/argv v0.1.0/go.mod h1:EusR6TucWKX+zFgtdUsKT2Cvg45K5rtpCcWz4hK06d8=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo=
github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/derekparker/trie v0.0.0-20230829180723-39f4de51ef7d h1:hUWoLdw5kvo2xCsqlsIBMvWUc1QCSsCYD2J2+Fg6YoU=
github.com/derekparker/trie v0.0.0-20230829180723-39f4de51ef7d/go.mod h1:C7Es+DLenIpPc9J6IYw4jrK0h7S9bKj4DNl8+KxGEXU=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik=
github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/cors v1.7.6 h1:3gQ8GMzs1Ylpf70y8bMw4fVpycXIeX1ZemuSQIsnQQY=
github.com/gin-contrib/cors v1.7.6/go.mod h1:Ulcl+xN4jel9t1Ry8vqph23a60FwH9xVLd+3ykmTjOk=
github.com/gin-contrib/sessions v1.0.4 h1:ha6CNdpYiTOK/hTp05miJLbpTSNfOnFg5Jm2kbcqy8U=
github.com/gin-contrib/sessions v1.0.4/go.mod h1:ccmkrb2z6iU2osiAHZG3x3J4suJK+OU27oqzlWOqQgs=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
github.com/go-delve/delve v1.25.2 h1:EI6EIWGKUEC7OVE5nfG2eQSv5xEgCRxO1+REB7FKCtE=
github.com/go-delve/delve v1.25.2/go.mod h1:sBjdpmDVpQd8nIMFldtqJZkk0RpGXrf8AAp5HeRi0CM=
github.com/go-delve/liner v1.2.3-0.20231231155935-4726ab1d7f62 h1:IGtvsNyIuRjl04XAOFGACozgUD7A82UffYxZt4DWbvA=
github.com/go-delve/liner v1.2.3-0.20231231155935-4726ab1d7f62/go.mod h1:biJCRbqp51wS+I92HMqn5H8/A0PAhxn2vyOT+JqhiGI=
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-openapi/jsonpointer v0.22.1 h1:sHYI1He3b9NqJ4wXLoJDKmUmHkWy/L7rtEo92JUxBNk=
github.com/go-openapi/jsonpointer v0.22.1/go.mod h1:pQT9OsLkfz1yWoMgYFy4x3U5GY5nUlsOn1qSBH5MkCM=
github.com/go-openapi/jsonreference v0.21.3 h1:96Dn+MRPa0nYAR8DR1E03SblB5FJvh7W6krPI0Z7qMc=
github.com/go-openapi/jsonreference v0.21.3/go.mod h1:RqkUP0MrLf37HqxZxrIAtTWW4ZJIK1VzduhXYBEeGc4=
github.com/go-openapi/spec v0.22.1 h1:beZMa5AVQzRspNjvhe5aG1/XyBSMeX1eEOs7dMoXh/k=
github.com/go-openapi/spec v0.22.1/go.mod h1:c7aeIQT175dVowfp7FeCvXXnjN/MrpaONStibD2WtDA=
github.com/go-openapi/swag v0.25.1 h1:6uwVsx+/OuvFVPqfQmOOPsqTcm5/GkBhNwLqIR916n8=
github.com/go-openapi/swag v0.25.1/go.mod h1:bzONdGlT0fkStgGPd3bhZf1MnuPkf2YAys6h+jZipOo=
github.com/go-openapi/swag/conv v0.25.1 h1:+9o8YUg6QuqqBM5X6rYL/p1dpWeZRhoIt9x7CCP+he0=
github.com/go-openapi/swag/conv v0.25.1/go.mod h1:Z1mFEGPfyIKPu0806khI3zF+/EUXde+fdeksUl2NiDs=
github.com/go-openapi/swag/jsonname v0.25.1 h1:Sgx+qbwa4ej6AomWC6pEfXrA6uP2RkaNjA9BR8a1RJU=
github.com/go-openapi/swag/jsonname v0.25.1/go.mod h1:71Tekow6UOLBD3wS7XhdT98g5J5GR13NOTQ9/6Q11Zo=
github.com/go-openapi/swag/jsonutils v0.25.1 h1:AihLHaD0brrkJoMqEZOBNzTLnk81Kg9cWr+SPtxtgl8=
github.com/go-openapi/swag/jsonutils v0.25.1/go.mod h1:JpEkAjxQXpiaHmRO04N1zE4qbUEg3b7Udll7AMGTNOo=
github.com/go-openapi/swag/loading v0.25.1 h1:6OruqzjWoJyanZOim58iG2vj934TysYVptyaoXS24kw=
github.com/go-openapi/swag/loading v0.25.1/go.mod h1:xoIe2EG32NOYYbqxvXgPzne989bWvSNoWoyQVWEZicc=
github.com/go-openapi/swag/stringutils v0.25.1 h1:Xasqgjvk30eUe8VKdmyzKtjkVjeiXx1Iz0zDfMNpPbw=
github.com/go-openapi/swag/stringutils v0.25.1/go.mod h1:JLdSAq5169HaiDUbTvArA2yQxmgn4D6h4A+4HqVvAYg=
github.com/go-openapi/swag/typeutils v0.25.1 h1:rD/9HsEQieewNt6/k+JBwkxuAHktFtH3I3ysiFZqukA=
github.com/go-openapi/swag/typeutils v0.25.1/go.mod h1:9McMC/oCdS4BKwk2shEB7x17P6HmMmA6dQRtAkSnNb8=
github.com/go-openapi/swag/yamlutils v0.25.1 h1:mry5ez8joJwzvMbaTGLhw8pXUnhDK91oSJLDPF1bmGk=
github.com/go-openapi/swag/yamlutils v0.25.1/go.mod h1:cm9ywbzncy3y6uPm/97ysW8+wZ09qsks+9RS8fLWKqg=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@@ -27,6 +78,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
@@ -36,6 +89,8 @@ github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzq
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-dap v0.12.0 h1:rVcjv3SyMIrpaOoTAdFDyHs99CwVOItIJGKLQFQhNeM=
github.com/google/go-dap v0.12.0/go.mod h1:tNjCASCm5cqePi/RVXXWEVqtnNLV1KTWtYOqu6rZNzc=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
@@ -47,6 +102,10 @@ github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kX
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c=
github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -57,14 +116,25 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mailru/easyjson v0.9.1 h1:LbtsOm5WAswyWbvTEOqhypdPeZzHavpZx96/n553mR8=
github.com/mailru/easyjson v0.9.1/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -78,45 +148,138 @@ github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
github.com/quic-go/quic-go v0.56.0 h1:q/TW+OLismmXAehgFLczhCDTYB3bFmua4D9lsNBWxvY=
github.com/quic-go/quic-go v0.56.0/go.mod h1:9gx5KsFQtw2oZ6GZTyh+7YEvOxWCL9WZAepnHxgAo6c=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
github.com/tkrajina/go-reflector v0.5.5/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
github.com/tkrajina/typescriptify-golang-structs v0.2.0 h1:ZedWk82egydDspGTryAatbX0/1NZDQbdiZLoCbOk4f8=
github.com/tkrajina/typescriptify-golang-structs v0.2.0/go.mod h1:sjU00nti/PMEOZb07KljFlR+lJ+RotsC0GBQMv9EKls=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/urfave/cli/v2 v2.27.7 h1:bH59vdhbjLv3LAvIu6gd0usJHgoTTPhCFib8qqOwXYU=
github.com/urfave/cli/v2 v2.27.7/go.mod h1:CyNAG/xg+iAOg0N4MPGZqVmv2rCoP267496AOXUZjA4=
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342 h1:FnBeRrxr7OU4VvAzt5X7s6266i6cSVkkFPS0TuXWbIg=
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.starlark.net v0.0.0-20231101134539-556fd59b42f6 h1:+eC0F/k4aBLC4szgOcjd7bDTEnpxADJyWJE0yowgM3E=
go.starlark.net v0.0.0-20231101134539-556fd59b42f6/go.mod h1:LcLNIzVOMp4oV+uusnpk+VU+SzXaJakUuBjoCSWH5dM=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 h1:Jvc7gsqn21cJHCmAWx0LiimpP18LZmUxkT5Mp7EZ1mI=
golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo=
golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 h1:LvzTn0GQhWuvKH/kVRS3R3bVAsdQWI7hvfLHGgh9+lU=
golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8/go.mod h1:Pi4ztBfryZoJEkyFTI5/Ocsu2jXyDr6iSdgJiYE/uwE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=

View File

@@ -9,6 +9,7 @@ import (
"ordr-api/auth"
"ordr-api/auth/middleware"
"ordr-api/controllers"
"ordr-api/corsmiddleware"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
@@ -34,6 +35,24 @@ func init_db_pool(databaseUrl string) (*pgxpool.Pool, error) {
}
func main() {
r := gin.Default()
// Configure CORS middleware
r.NoRoute(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
log.Printf("%s", c.Request.Method)
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.AbortWithStatus(404)
})
if err := godotenv.Load(); err != nil {
log.Fatalf("Failed to load the env vars: %v", err)
}
@@ -62,35 +81,51 @@ func main() {
user_is_admin := middleware.IsAdmin(pool)
gob.Register(map[string]interface{}{})
router.GET("/", user_authenticated, middleware.GetUserProfile, controllers.BaseFunction)
router.GET("/auth/login", auth.LoginHandler(authenticator))
router.GET("/auth/logout", auth.LogoutHandler)
router.GET("/auth/logout_callback", auth.LogoutCallbackHandler(store))
router.GET("/callback", auth.AuthenticationCallbackHandler(authenticator))
router.GET("/users", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.GetUserTable(pool))
router.GET("/user/current", user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetCurrentAuthenticatedUser(pool))
router.GET("/item/price/current", user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetCurrentItemPrice(pool))
router.GET("/order/items", user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderItems(pool))
router.GET("/order", user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderByOrderId(pool))
router.GET("/order/table", user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderTable(pool))
router.GET("/", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, controllers.BaseFunction)
router.GET("/auth/login", corsmiddleware.CORSMiddleware, auth.LoginHandler(authenticator))
router.GET("/auth/logout", corsmiddleware.CORSMiddleware, auth.LogoutHandler)
router.GET("/auth/logout_callback", corsmiddleware.CORSMiddleware, auth.LogoutCallbackHandler(store))
router.GET("/callback", corsmiddleware.CORSMiddleware, auth.AuthenticationCallbackHandler(authenticator))
router.OPTIONS("./users", corsmiddleware.CORSMiddleware)
router.PUT("/users", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.GetUserTable(pool))
router.GET("/user/current", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetCurrentAuthenticatedUser(pool))
router.GET("/item/price/current", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetCurrentItemPrice(pool))
router.GET("/order/items", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderItems(pool))
router.GET("/order", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderByOrderId(pool))
router.PUT("/order/table", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderTable(pool))
router.OPTIONS("/order/table", corsmiddleware.CORSMiddleware)
router.GET("/items", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetItems(pool))
router.OPTIONS("/item/history", corsmiddleware.CORSMiddleware)
router.GET("/item/history", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.GetItemHistory(pool))
router.POST("/position/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.CreatePosition(pool))
router.POST("/item/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.CreateItem(pool))
router.POST("/order/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.CreateOrder(pool))
router.OPTIONS("/order/create", corsmiddleware.CORSMiddleware)
router.POST("/position/create", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.CreatePosition(pool))
router.POST("/item/create", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.CreateItem(pool))
router.POST("/order/create", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.CreateOrder(pool))
router.PUT("/user/name", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetUserName(pool))
router.PUT("/user/promote", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.PromoteUser(pool))
router.PUT("/user/demote", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DemoteUser(pool))
router.OPTIONS("/user/promote", corsmiddleware.CORSMiddleware)
router.OPTIONS("/user/demote", corsmiddleware.CORSMiddleware)
router.PUT("/user/name", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetUserName(pool))
router.PUT("/user/promote", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.PromoteUser(pool))
router.PUT("/user/demote", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DemoteUser(pool))
router.PUT("/user/position", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.SetUserPosition(pool))
router.PUT("/item/price", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.SetItemPrice(pool))
router.PUT("/order/item", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.AddItemToOrder(pool))
router.PUT("/item/made", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetItemMade(pool))
router.PUT("/item/quantity", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetItemQuantity(pool))
router.PUT("/user/position", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.SetUserPosition(pool))
router.PUT("/item/price", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.SetItemPrice(pool))
router.OPTIONS("/item/price", corsmiddleware.CORSMiddleware)
router.PUT("/order/item", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.AddItemToOrder(pool))
router.OPTIONS("/order/item", corsmiddleware.CORSMiddleware)
router.PUT("/item/made", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetItemMade(pool))
router.OPTIONS("/item/made", corsmiddleware.CORSMiddleware)
router.PUT("/item/quantity", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetItemQuantity(pool))
router.OPTIONS("/item/quantity", corsmiddleware.CORSMiddleware)
router.PUT("/user/activate", corsmiddleware.CORSMiddleware, middleware.IsAuthenticated(authenticator), middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.ActivateUser(pool))
router.OPTIONS("/user/activate", corsmiddleware.CORSMiddleware)
router.DELETE("/user/deactivate", middleware.IsAuthenticated(authenticator), middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DeactivateUser(pool))
router.DELETE("/order/item", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.DeleteOrderItem(pool))
router.DELETE("/order", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.DeleteOrder(pool))
router.DELETE("/item", user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DeleteItem(pool))
router.DELETE("/user/deactivate", corsmiddleware.CORSMiddleware, middleware.IsAuthenticated(authenticator), middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DeactivateUser(pool))
router.OPTIONS("/user/deactivate", corsmiddleware.CORSMiddleware)
router.DELETE("/order/item", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.DeleteOrderItem(pool))
router.DELETE("/order", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.DeleteOrder(pool))
router.DELETE("/item", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DeleteItem(pool))
router.Run("localhost:8080")
}

View File

@@ -19,13 +19,38 @@ const GET_CURRENT_ITEM_PRICE = `
SELECT
i.id,
i.item_name,
iph.price AS unit_price
iph.price AS unit_price,
i.in_season
FROM item i
INNER JOIN item_price_history iph ON iph.item_id = i.id
AND i.id = $1
ORDER BY iph.valid_from DESC
LIMIT 1;
`
const GET_CURRENT_ITEMS_PRICE = `
WITH latest_price_identifiers AS (
SELECT
i.id,
i.item_name,
MAX(iph.valid_from) AS valid_from
FROM item i
INNER JOIN item_price_history iph ON iph.item_id = i.id
GROUP BY (i.id, i.item_name)
)
SELECT
lpi.id,
lpi.item_name,
iph.price,
i.in_season
FROM
latest_price_identifiers lpi
INNER JOIN item_price_history iph
ON lpi.id = iph.item_id
AND lpi.valid_from = iph.valid_from
INNER JOIN item i
ON iph.item_id = i.id;`
const GET_ORDER_ITEM_PRICE = `
SELECT
oi.item_id,
@@ -95,3 +120,17 @@ FROM
WHERE
id = $1;
`
const GET_ITEM_PRICE_HISTORY = `
SELECT
i.id,
i.item_name,
iph.price,
iph.valid_from,
COALESCE(iph.valid_to, now()) as valid_to
FROM
item i
INNER JOIN item_price_history iph
ON i.id = iph.item_id
AND i.id = $1;
`

View File

@@ -20,6 +20,10 @@ const USER_SET_INACTIVE_QUERY string = `
UPDATE ordr_user SET active = FALSE WHERE id = $1;
`
const USER_SET_ACTIVE_QUERY string = `
UPDATE ordr_user SET active = TRUE WHERE id = $1;
`
const USER_GET_TABLE_DATA string = `
SELECT
ordr_user.id,
@@ -29,7 +33,7 @@ SELECT
is_admin
FROM
ordr_user
INNER JOIN ordr_position
LEFT JOIN ordr_position
ON job_position = ordr_position.id
WHERE
user_name LIKE '%' || $3 ||'%'

41
ordr-ui/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

36
ordr-ui/README.md Normal file
View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@@ -0,0 +1,136 @@
import axios from 'axios'
import {CreateItemQuery} from '../queries/CreateItemQuery'
import {ItemPriceResponse} from '../response/ItemPriceResponse'
import {OrderItemPriceResponse} from '../response/OrderItemPriceResponse'
import {SetItemPriceQuery} from '../queries/SetItemPriceQuery'
import {GetCurrentPriceQuery} from '../queries/GetCurrentPriceQuery'
import {AddItemToOrderQuery} from '../queries/AddItemToOrderQuery'
import {GetOrderItemsQuery} from '../queries/GetOrderItemsQuery'
import {SetItemMadeRequest} from '../request/SetItemMadeRequest'
import {OrderFilledResponse} from '../response/OrderFilledResponse'
import {SetItemQuantityRequest} from '../request/SetItemQuantityRequest'
import {DeleteOrderItemRequest} from '../request/DeleteOrderItemRequest'
import { ItemHistoryResponse } from '../response/ItemHistoryResponse'
export const CreateItem = async (query: CreateItemQuery): Promise<ItemPriceResponse> => {
const queryParams = new URLSearchParams({
item_name: query.item_name,
in_season: query.in_season,
item_price: query.item_price
})
const res = await axios.post(process.env.API_URL + `/item/create?${queryParams.toString()}`)
if (res.data.Location) {
window.location.href = res.data.Location
}
return res.data
}
export const SetItemPrice = async (query: SetItemPriceQuery) => {
const queryParams = new URLSearchParams({
item_id: query.item_id,
item_price: query.item_price
})
const res = await axios.put(process.env.NEXT_PUBLIC_API_URL + `/item/price?${queryParams.toString()}`, {}, {withCredentials: true})
if (res.data.Location) {
window.location.href = res.data.Location
}
}
export const GetCurrentPrice = async (query: GetCurrentPriceQuery): Promise<ItemPriceResponse> => {
const queryParams = new URLSearchParams({
item_id: query.item_id
})
const res = await axios.get(process.env.API_URL + `/item/price?${queryParams.toString()}`)
if (res.data.Location) {
window.location.href = res.data.Location
}
return res.data
}
export const AddItemToOrder = async (query: AddItemToOrderQuery): Promise<OrderItemPriceResponse> => {
const queryParams = new URLSearchParams({
item_id: query.item_id,
order_id: query.order_id,
quantity: query.quantity
})
console.log(process.env.NEXT_PUBLIC_API_URL + `/order/item?${queryParams.toString()}`)
const res = await axios.put(process.env.NEXT_PUBLIC_API_URL + `/order/item?${queryParams.toString()}`, {}, {withCredentials: true})
if (res.data?.Location) {
window.location.href = res.data.Location
}
return res.data
}
export const GetOrderItems = async (query: GetOrderItemsQuery): Promise<OrderItemPriceResponse[]> => {
const queryParams = new URLSearchParams({
order_id: query.order_id
})
const res = await axios.get(process.env.NEXT_PUBLIC_API_URL + `/order/items?${queryParams.toString()}`, {withCredentials: true})
if (res.data?.Location) {
window.location.href = res.data.Location
}
return res.data || []
}
export const SetItemMade = async (request: SetItemMadeRequest): Promise<OrderFilledResponse> => {
const res = await axios.put(process.env.NEXT_PUBLIC_API_URL + '/item/made', request, {withCredentials: true})
if (res.data?.Location) {
window.location.href = res.data.Location
}
return res.data
}
export const SetItemQuantity = async (request: SetItemQuantityRequest): Promise<OrderFilledResponse> => {
const res = await axios.put(process.env.NEXT_PUBLIC_API_URL + `/item/quantity`, request, {withCredentials: true})
if (res.data.Location) {
window.location.href = res.data.Location
}
return res.data
}
export const DeleteOrderItem = async (request: DeleteOrderItemRequest) => {
const res = await axios.delete(process.env.API_URL + `/order/item?order_id=${request.order_id}&item_id=${request.item_id}`)
if (res.data.Location) {
window.location.href = res.data.Location
}
}
export const DeleteItem = async (itemId: number) => {
const queryParams = new URLSearchParams({
item_id: itemId.toString()
})
const res = await axios.delete(process.env.API_URL + `/item?${queryParams.toString()}`)
if (res.data.Location) {
window.location.href = res.data.Location
}
}
export const GetItems = async (): Promise<ItemPriceResponse[]> => {
const res = await axios.get(process.env.NEXT_PUBLIC_API_URL + `/items`, {withCredentials: true})
if (res.data.Location) {
window.location.href = res.data.Location
}
return res.data
}
export const GetItemHistory = async (itemId: number): Promise<ItemHistoryResponse[]> => {
const res = await axios.get(process.env.NEXT_PUBLIC_API_URL + `/item/history?item_id=${itemId.toString()}`, {withCredentials: true})
return res.data
}

View File

@@ -0,0 +1,56 @@
import axios from 'axios'
import {OrderResponse} from '../response/OrderResponse'
import {OrderTableQuery} from '../request/GetOrderTableRequest'
axios.interceptors.response.use(response => {
return response;
}, async error => {
if (error.response.status === 401) {
const resp = await axios.get(process.env.NEXT_PUBLIC_API_URL + "/auth/login", {withCredentials: true})
window.location.href = resp.data.Location
}
return error
})
export const CreateOrder = async (orderer: string, dateDue: string): Promise<OrderResponse> => {
const queryParams = new URLSearchParams({
orderer: orderer,
date_due: dateDue,
date_placed: new Date().toISOString()
})
const res = await axios.post(process.env.NEXT_PUBLIC_API_URL + `/order/create?${queryParams.toString()}`, {}, {withCredentials: true})
return res.data as OrderResponse
}
export const GetOrderById = async (orderId: number): Promise<OrderResponse> => {
const queryParams = new URLSearchParams({
order_id: orderId.toString()
})
const res = await axios.get(process.env.API_URL + `/order?${queryParams.toString()}`)
return res.data as OrderResponse
}
export const GetOrderTable = async (page: number, filter: number, searchParams: OrderTableQuery): Promise<OrderResponse[]> => {
const queryParams = new URLSearchParams({
page: page.toString(),
filter: filter.toString()
})
console.log(page)
console.log(filter)
console.log(searchParams)
console.log(queryParams.toString())
const res = await axios.put(process.env.NEXT_PUBLIC_API_URL + `/order/table?${queryParams.toString()}`, searchParams, {withCredentials: true})
if(res.data?.Location) {
window.location.href = res.data.Location
}
return res.data || []
}
export const DeleteOrder = async (orderId: number) => {
const queryParams = new URLSearchParams({
order_id: orderId.toString()
})
await axios.delete(process.env.API_URL + `/order?${queryParams}`)
}

View File

@@ -0,0 +1,81 @@
import axios, { HttpStatusCode } from 'axios'
import { UserResponse } from '../response/UserResponse'
import { UserTable } from '../queries/UserTableQuery'
import { LoginRedirectResponse } from '../response'
// import { cookies } from 'next/headers'
export const GetCurrentUser = async (): Promise<UserResponse | undefined> => {
console.log(process.env.NEXT_PUBLIC_API_URL + "/user/current")
const res = await axios.get(process.env.NEXT_PUBLIC_API_URL + "/user/current", {
maxRedirects: 0,
validateStatus: (status) => {
return status >= 200 && status < 400
}});
if(res.data.Location) {
window.location.href = res.data.Location
}
return res.data;
};
export const GetUserTable = async (page: number): Promise<UserResponse[]> => {
const res = await axios.put(process.env.NEXT_PUBLIC_API_URL + `/users?page=${page.toString()}`, {
name: "",
jobPosition: ""
}, {
withCredentials: true
});
if (res.data.Location)
window.location.href = res.data.Location
return res.data || []
}
export const SetUserName = async (userName: string) => {
const queryParams = new URLSearchParams({
user_name: userName
});
await axios.put(process.env.NEXT_PUBLIC_API_URL + `/user/name?${queryParams.toString()}`)
}
export const PromoteUser = async (userId: number) => {
const queryParams = new URLSearchParams({
user_id: userId.toString()
});
await axios.put(process.env.NEXT_PUBLIC_API_URL + `/user/promote?${queryParams.toString()}`, {}, {withCredentials: true});
}
export const DemoteUser = async (userId: number) => {
const queryParams = new URLSearchParams({
user_id: userId.toString()
})
await axios.put(process.env.NEXT_PUBLIC_API_URL + `/user/demote?${queryParams.toString()}`, {}, {withCredentials: true})
}
export const DeactivateUser = async (userId: number) => {
const queryParams = new URLSearchParams({
user_id: userId.toString()
})
await axios.delete(process.env.NEXT_PUBLIC_API_URL + `/user/deactivate?${queryParams.toString()}`, {withCredentials: true})
}
export const ActivateUser = async (userId: number) => {
const queryParams = new URLSearchParams({
user_id: userId.toString()
})
await axios.put(process.env.NEXT_PUBLIC_API_URL + `/user/activate?${queryParams.toString()}`, {}, {withCredentials: true})
}
export const CreatePosition = async (positionName: string) => {
const queryParams = new URLSearchParams({
position_name: positionName
})
await axios.post(process.env.NEXT_PUBLIC_API_URL + `/position/create?` + queryParams.toString())
}
export const SetUserPosition = async (userId: number, positionName: string) => {
const queryParams = new URLSearchParams({
user_id: userId.toString(),
position: positionName
})
await axios.put(process.env.NEXT_PUBLIC_API_URL + `/user/position?${queryParams.toString}`)
}

View File

@@ -0,0 +1,3 @@
export * from './ItemController'
export * from './OrderController'
export * from './UserController'

View File

@@ -0,0 +1,9 @@
/*
AddItemToOrder
PUT: {{baseURL}}/order/item?item_id=2&order_id=2&quantity=8
*/
export interface AddItemToOrderQuery {
item_id: string;
order_id: string;
quantity: string;
}

View File

@@ -0,0 +1,9 @@
/*
CreateItem
POST: {{baseURL}}/item/create?item_name=4 Berry Pie&in_season=1&item_price=35.00
*/
export interface CreateItemQuery {
item_name: string;
in_season: string;
item_price: string;
}

View File

@@ -0,0 +1,8 @@
/*
CreateOrder
POST: {{baseURL}}/order/create?orderer=john roe&date_due=2026-01-01T23:59:59-07:00
*/
export interface CreateOrder {
orderer: string;
date_due: string;
}

View File

@@ -0,0 +1,7 @@
/*
CreatePosition
POST: {{baseURL}}/position/create?position_name=Manager
*/
export interface CreatePosition {
position_name: string;
}

View File

@@ -0,0 +1,7 @@
/*
DeactivateUser
DELETE: {{baseURL}}/user/deactivate?user_id=4
*/
export interface DeactivateUser {
user_id: string;
}

View File

@@ -0,0 +1,7 @@
/*
DemoteUser
PUT: {{baseURL}}/user/demote?user_id=1
*/
export interface DemoteUser {
user_id: string;
}

View File

@@ -0,0 +1,7 @@
/*
GetCurrentPrice
GET: {{baseURL}}/item/price/current?item_id=1
*/
export interface GetCurrentPriceQuery {
item_id: string;
}

View File

@@ -0,0 +1,7 @@
/*
GetOrderById
GET: http://localhost:8080/order?order_id=8
*/
export interface GetOrderById {
order_id: string;
}

View File

@@ -0,0 +1,7 @@
/*
GetOrderItems
GET: http://localhost:8080/order/items?order_id=1
*/
export interface GetOrderItemsQuery {
order_id: string;
}

View File

@@ -0,0 +1,8 @@
/*
GetOrderTable
GET: http://localhost:8080/order/table?page=0&filter=257
*/
export interface GetOrderTableQuery {
page: string;
filter: string;
}

View File

@@ -0,0 +1,7 @@
/*
PromoteUser
PUT: {{baseURL}}/user/promote?user_id=1
*/
export interface PromoteUser {
user_id: string;
}

View File

@@ -0,0 +1,8 @@
/*
SetItemPrice
PUT: {{baseURL}}/item/price?item_id=1&item_price=36.99
*/
export interface SetItemPriceQuery {
item_id: string;
item_price: string;
}

View File

@@ -0,0 +1,8 @@
/*
SetUserPosition
PUT: {{baseURL}}/user/position?user_id=2&position=Manager
*/
export interface SetUserPosition {
user_id: string;
position: string;
}

View File

@@ -0,0 +1,7 @@
/*
UserName
PUT: {{baseURL}}/user/name?user_name=Ada%20Conway
*/
export interface UserName {
user_name: string;
}

View File

@@ -0,0 +1,7 @@
/*
UserTable
GET: {{baseURL}}/users?page=1
*/
export interface UserTable {
page: string;
}

View File

@@ -0,0 +1,8 @@
/*
DeleteOrderItem
DELETE: {{baseURL}}/order/item
*/
export interface DeleteOrderItemRequest {
item_id: number;
order_id: number;
}

View File

@@ -0,0 +1,9 @@
/*
GetOrderTable
GET: http://localhost:8080/order/table?page=0&filter=257
*/
export interface OrderTableQuery {
orderer: string;
date_due: string;
date_placed: string;
}

View File

@@ -0,0 +1,9 @@
/*
SetItemMade
PUT: {{baseURL}}/item/made
*/
export interface SetItemMadeRequest {
order_id: number;
item_id: number;
made: number;
}

View File

@@ -0,0 +1,5 @@
export interface SetItemQuantityRequest {
order_id: number;
item_id: number;
quantity: number;
}

View File

@@ -0,0 +1,7 @@
/*
UserName
PUT: {{baseURL}}/user/name?user_name=Ada%20Conway
*/
export interface UserName {
name: string;
}

View File

@@ -0,0 +1,7 @@
export type ItemHistoryResponse = {
ItemId : string
ItemName : string
ItemPrice: string
ValidFrom: string
ValidTo : string
}

View File

@@ -0,0 +1,6 @@
export interface ItemPriceResponse {
ItemId: number;
ItemName: string;
ItemPrice: number;
InSeason: boolean
}

View File

@@ -0,0 +1,4 @@
export type LoginRedirectResponse = {
status: string,
location: string
};

View File

@@ -0,0 +1,4 @@
export interface OrderFilledResponse{
OrderId: number;
Filled: boolean;
}

View File

@@ -0,0 +1,10 @@
export interface OrderItemPriceResponse{
ItemId: number;
OrderId: number;
ItemName: string;
Quantity: number;
Made: number;
CreatedAt: Date;
TotalPrice: number;
UnitPrice: number;
}

View File

@@ -0,0 +1,12 @@
export interface OrderResponse{
Id: number;
UserId: number;
Orderer: string;
DateDue: string;
DatePlaced: string;
AmountPaid: number;
OrderTotal: number;
AmountDue: number;
Filled: boolean;
Delivered: boolean;
}

View File

@@ -0,0 +1,7 @@
export interface UserResponse{
Id: number;
Name: string;
JobPosition: string;
Active: boolean;
Admin: boolean;
}

View File

@@ -0,0 +1,7 @@
export type {ItemPriceResponse} from './ItemPriceResponse'
export type {OrderFilledResponse} from './OrderFilledResponse'
export type {OrderItemPriceResponse} from './OrderItemPriceResponse'
export type {OrderResponse} from './OrderResponse'
export type {UserResponse} from './UserResponse'
export type { LoginRedirectResponse} from './LoginRedirectResponse'
export type {ItemHistoryResponse} from './ItemHistoryResponse'

View File

@@ -0,0 +1,92 @@
import { Mutex } from "async-mutex"
import { useState } from "react"
import useAsyncEffect from "use-async-effect"
import { GetItemHistory } from "../client/controllers"
import { ItemHistoryResponse } from "../client/response"
import styled from "styled-components"
type ItemHistoryTableProps = {
itemId: number
}
const ItemHistoryTableStyle = styled.table`
width: 100%
`
const ItemHistoryTableHead = styled.thead`
background-color: #34067eff
`
const ItemHistoryTableItem = styled.td`
align: center
`
const ItemHistoryTH = styled.th`
align: center
`
const ItemHistoryTableBody = styled.tbody`
> :nth-child(even) {
background-color: #410041ff;
}
> :hover {
background-color: #707070ff;
}
`
const ItemHistoryTableRow = styled.tr`
`
const itemHistoryMutex = new Mutex()
export const ItemHistoryTable = ({itemId}: ItemHistoryTableProps) => {
const [itemPriceHistory, setItemPriceHistory] = useState<ItemHistoryResponse[]>([])
useAsyncEffect(async () => {
if(itemPriceHistory.length === 0) {
const release = await itemHistoryMutex.acquire()
setItemPriceHistory(await GetItemHistory(itemId))
await release()
}
}, [])
console.log(itemPriceHistory)
return (
<ItemHistoryTableStyle>
<ItemHistoryTableHead>
<tr>
<ItemHistoryTH>
item
</ItemHistoryTH>
<ItemHistoryTH>
price
</ItemHistoryTH>
<ItemHistoryTH>
valid from
</ItemHistoryTH>
<ItemHistoryTH>
valid to
</ItemHistoryTH>
</tr>
</ItemHistoryTableHead>
<ItemHistoryTableBody>
{itemPriceHistory.map((iph) => (
<ItemHistoryTableRow key = {iph.ItemId + new Date(iph.ValidFrom).getMilliseconds()}>
<ItemHistoryTableItem>
{iph.ItemName}
</ItemHistoryTableItem>
<ItemHistoryTableItem>
{Math.trunc(parseInt(iph.ItemPrice) * 100) / 100}
</ItemHistoryTableItem>
<ItemHistoryTableItem>
{new Date(iph.ValidFrom).toLocaleDateString()}
</ItemHistoryTableItem>
<ItemHistoryTableItem>
{new Date(iph.ValidTo).toLocaleDateString()}
</ItemHistoryTableItem>
</ItemHistoryTableRow>
))}
</ItemHistoryTableBody>
</ItemHistoryTableStyle>
)
}

View File

@@ -0,0 +1,27 @@
import useAsyncEffect from "use-async-effect"
import { useItemStore } from "../providers/ItemsProvider"
import { Mutex } from "async-mutex"
import { ItemTableListRow } from "./ItemTableListRow"
const itemApiMutex = new Mutex()
export const ItemTableList = () => {
const itemStore = useItemStore((state) => state)
useAsyncEffect( async () => {
if(itemStore.items.length === 0) {
const release = await itemApiMutex.acquire()
await itemStore.sync()
await release()
}
}, [])
return (
<ul>
{itemStore.items.map((i) => (
<ItemTableListRow item={i} key={i.ItemId}/>
))}
</ul>
)
}

View File

@@ -0,0 +1,102 @@
import { useState } from "react"
import styled from "styled-components"
import { ItemPriceResponse } from "../client/response"
import { ItemHistoryTable } from "./ItemHistoryTable"
import useAsyncEffect from "use-async-effect"
import { useItemStore } from "../providers/ItemsProvider"
import { Mutex } from "async-mutex"
type ItemTableListRowProps = {
item: ItemPriceResponse
}
const ItemRowContainer = styled.div`
margin-bottom: 10px;
padding-top: 5px;
padding-bottom: 5px;
width: 100%;
`
const ItemFieldContainer = styled.div`
display: inline-block;
padding-left: 5px;
padding-right: 5px;
`
const ItemOverviewContainer = styled.div`
display: inline-block;
background-color: #410041ff;
width: 100%;
&:hover {
background-color: #920592ff;
cursor: pointer;
}
`
const ItemDetailsContainer = styled.div`
display: inline-block;
background-color: #6e296eff;
width: 100%;
&:hover {
background-color: #da51daff;
color: #000;
cursor: pointer;
}
`
const itemTableListRowMutex = new Mutex()
export const ItemTableListRow = ({item}: ItemTableListRowProps) => {
const [shouldShowDetails, setShouldShowDetails] = useState<boolean>(false)
const itemStore = useItemStore((state) => state)
const [newItemPrice, setNewItemPrice] = useState<number>(item.ItemPrice)
const [shouldPushNewItemPrice, setShouldPushNewItemPrice] = useState<boolean>(false)
useAsyncEffect(async () => {
if(shouldPushNewItemPrice)
{
const release = await itemTableListRowMutex.acquire()
setShouldPushNewItemPrice(false)
await itemStore.setItemPrice(item.ItemId, newItemPrice)
await release()
}
}, [shouldPushNewItemPrice])
return (
<li>
<ItemRowContainer>
<ItemOverviewContainer onClick={() => {
setShouldShowDetails(!shouldShowDetails)
}}>
<ItemFieldContainer>
item: {item.ItemName}
</ItemFieldContainer>
<ItemFieldContainer>
price: {Math.trunc(item.ItemPrice * 100) / 100}
</ItemFieldContainer>
</ItemOverviewContainer>
{shouldShowDetails && (
<>
<ItemDetailsContainer>
<h1 className="text-xl">Set Item Price</h1>
<label>Price</label>
<br />
<input placeholder="price" defaultValue={(Math.trunc(item.ItemPrice * 100) / 100).toString()} onChange={(e) => {
const newPrice = parseInt(e.currentTarget.value)
if(!Number.isNaN(newPrice))
setNewItemPrice(newPrice)
}}/>
<br />
<button className="border p-2 mt-2" onClick={() => {setShouldPushNewItemPrice(true)}}>Set Price</button>
</ItemDetailsContainer>
<ItemHistoryTable itemId={item.ItemId} />
</>
)}
</ItemRowContainer>
</li>
)
}

View File

@@ -0,0 +1,13 @@
import Link from "next/link"
export const NavBar = () => {
return (
<nav>
<div className="flex items-center justify-center">
<Link className=" pl-7 pr-7 pt-3 pb-3 hover:bg-purple-950" href="/orders/0/0">Orders</Link>
<Link className=" pl-7 pr-7 pt-3 pb-3 hover:bg-purple-950" href="/users/0">Users</Link>
<Link className=" pl-7 pr-7 pt-3 pb-3 hover:bg-purple-950" href="/items">Items</Link>
</div>
</nav>
)
}

View File

@@ -0,0 +1,143 @@
import { useItemStore } from "../providers/ItemsProvider"
import { useState } from "react"
import useAsyncEffect from "use-async-effect"
import styled from "styled-components"
import { Mutex } from "async-mutex"
type OrderItemTableProps = {
orderId: number
}
const OrderItemTableStyle = styled.table`
width: 100%
`
const OrderItemTableHead = styled.thead`
background-color: #34067eff
`
const OrderItemTableItem = styled.td`
align: center
`
const OrderItemTH = styled.th`
align: center
`
const OrderItemTableBody = styled.tbody`
> :nth-child(even) {
background-color: #410041ff;
}
> :hover {
background-color: #707070ff;
}
`
const OrderItemTableRow = styled.tr`
`
const orderItemMutex = new Mutex()
export const OrderItemTable = ({orderId}: OrderItemTableProps) => {
const itemStore = useItemStore((state) => state)
const [orderItems, setOrderItems] = useState(itemStore.orderItems.filter((oi) => oi.OrderId === orderId))
const [itemName, setItemName] = useState("")
const [itemQuantity, setItemQuantity] = useState(0)
const [shouldPostData, setShouldPostData] = useState(false)
useAsyncEffect(async () => {
if (orderItems.length === 0) {
const release = await orderItemMutex.acquire()
setOrderItems(await itemStore.getOrderItems(orderId))
await release()
}
if (itemStore.items.length === 0) {
const release = await orderItemMutex.acquire()
await itemStore.sync()
await release()
}
}, [])
useAsyncEffect(async () => {
if(shouldPostData) {
const items = itemStore.items.filter((i) => i.ItemName.toUpperCase().includes(itemName.toUpperCase()))
if(items.length > 0) {
const release = await orderItemMutex.acquire()
setOrderItems( [...orderItems, await itemStore.addItemToOrder(items[0].ItemId, orderId, itemQuantity)])
await release()
}
setShouldPostData(false)
}
}, [shouldPostData])
return (
<>
<OrderItemTableStyle>
<OrderItemTableHead>
<tr>
<OrderItemTH>
item
</OrderItemTH>
<OrderItemTH>
needed
</OrderItemTH>
<OrderItemTH>
made
</OrderItemTH>
<OrderItemTH>
total
</OrderItemTH>
<OrderItemTH>
unit
</OrderItemTH>
</tr>
</OrderItemTableHead>
<OrderItemTableBody>
{orderItems.map((oi) => (
<OrderItemTableRow key = {oi.ItemId}>
<OrderItemTableItem>
{oi.ItemName}
</OrderItemTableItem>
<OrderItemTableItem>
<input className="w-10" defaultValue={oi.Quantity} onChange={async (e) => {
if(!Number.isNaN(parseInt(e.currentTarget.value))) {
await itemStore.setItemQuantity(oi.OrderId, oi.ItemId, parseInt(e.currentTarget.value))
}
}} />
</OrderItemTableItem>
<OrderItemTableItem>
<input className="w-10" defaultValue={oi.Made} onChange={async (e) => {
if(!Number.isNaN(parseInt(e.currentTarget.value))) {
await itemStore.setItemMade(oi.OrderId, oi.ItemId, parseInt(e.currentTarget.value))
}
}} />
</OrderItemTableItem>
<OrderItemTableItem>
${Math.trunc(oi.TotalPrice * 100) / 100}
</OrderItemTableItem>
<OrderItemTableItem>
${Math.trunc(oi.UnitPrice * 100) / 100}
</OrderItemTableItem>
</OrderItemTableRow>
))}
</OrderItemTableBody>
</OrderItemTableStyle>
<h1 className="text-xl font-bold">Add Item To Order</h1>
<div className="inline-block">
<input className="inline-block w-40" onChange={(e) => {
setItemName(e.currentTarget.value)
}} placeholder="item name"/>
<input className="inline-block w-40" onChange={(e) => {
setItemQuantity(parseInt(e.currentTarget.value))
}} placeholder="needed" />
</div>
<br />
<button className="border border-white p-1 mt-3" onClick={() => {
setShouldPostData(true)
}}>Add Item</button>
</>
)
}

View File

@@ -0,0 +1,44 @@
'for client'
import { useOrderStore } from "../providers/OrderProvider"
import { useShallow } from "zustand/shallow"
import useAsyncEffect from "use-async-effect"
import { OrderTableRow } from "./OrderTableRow"
import { Mutex } from "async-mutex"
import styled from "styled-components"
type OrderTableProps = {
page: number,
filter: number,
orderer: string,
dateDue: string,
datePlaced: string
}
const OrderList = styled.ul`
`
const mutex = new Mutex()
export const OrderTableList = ({page, filter, orderer, dateDue, datePlaced}: OrderTableProps) => {
const orderStore = useOrderStore(useShallow((state) => ({
...state
})))
useAsyncEffect(async () => {
const release = await mutex.acquire()
await orderStore.sync(page, filter, {
orderer: orderer,
date_due: dateDue,
date_placed: datePlaced
})
release()
}, [page, filter, orderer, dateDue, datePlaced])
return (
<OrderList>
{orderStore.orders.map((o) => (
<OrderTableRow key={o.Id} orderId={o.Id} orderer={o.Orderer} dateDue={o.DateDue} datePlaced={o.DatePlaced} amountPaid={o.AmountPaid} orderTotal={o.OrderTotal} amountDue={o.AmountDue} filled={o.Filled} delivered={o.Delivered} />
))}
</OrderList>
)
}

View File

@@ -0,0 +1,91 @@
import { useState } from "react"
import styled from "styled-components"
import { OrderItemTable } from "./OrderItemTable"
type OrderTableRowProps = {
orderId: number
orderer: string
dateDue: string
datePlaced: string
amountPaid: number
orderTotal: number
amountDue: number
filled: boolean
delivered: boolean
}
const OrderRowContainer = styled.div`
margin-bottom: 10px;
padding-top: 5px;
padding-bottom: 5px;
width: 100%;
`
const OrderFieldContainer = styled.div`
display: inline-block;
padding-left: 5px;
padding-right: 5px;
`
const OrderOverviewContainer = styled.div`
display: inline-block;
background-color: #410041ff;
width: 100%;
&:hover {
background-color: #920592ff;
cursor: pointer;
}
`
const OrderDetailsContainer = styled.div`
display: inline-block;
background-color: #6e296eff;
width: 100%;
&:hover {
background-color: #da51daff;
color: #000;
cursor: pointer;
}
`
export const OrderTableRow = ({orderId, orderer, dateDue, datePlaced, amountPaid, orderTotal, amountDue, filled, delivered}: OrderTableRowProps) => {
const dateDueDate = new Date(dateDue)
const datePlacedDate = new Date(datePlaced)
const [shouldShowDetails, setShouldShowDetails] = useState<boolean>(false)
return (
<li>
<OrderRowContainer>
<OrderOverviewContainer onClick={() => {
setShouldShowDetails(!shouldShowDetails)
}}>
<OrderFieldContainer>
orderer: {orderer}
</OrderFieldContainer>
<OrderFieldContainer>
due: {dateDueDate.toLocaleDateString()}
</OrderFieldContainer>
</OrderOverviewContainer>
{shouldShowDetails && (
<>
<OrderDetailsContainer>
<OrderFieldContainer>
placed: {datePlacedDate.toLocaleDateString()}
</OrderFieldContainer>
<OrderFieldContainer>
balance: {(Math.trunc(amountDue * 100) / 100).toString()}
</OrderFieldContainer>
<OrderFieldContainer>
{filled ? delivered ? "delivered" : "undelivered" : "unfilled"}
</OrderFieldContainer>
</OrderDetailsContainer>
<OrderItemTable orderId={orderId} />
</>
)}
</OrderRowContainer>
</li>
)
}

View File

@@ -0,0 +1,89 @@
'use client'
import { useShallow } from "zustand/shallow"
import { useUserStore } from "../providers/UsersProvider"
import useAsyncEffect from "use-async-effect"
import styled from "styled-components"
import { useRef, useState } from "react"
type UserTableProps = {
page: number
}
const UserTableStyle = styled.table`
width: 100%
`
const UserTableHead = styled.thead`
background-color: #34067eff
`
const UserTH = styled.th`
align: center
`
const UserTableItem = styled.td`
align: center
`
const UserTableBody = styled.tbody`
> :nth-child(even) {
background-color: #410041ff;
}
> :hover {
background-color: #707070ff;
}
`
const UserTableRow = styled.tr`
`
export const UserTable = ({page}: UserTableProps) => {
const userStore = useUserStore(useShallow((state) => ({
...state
})))
console.log(page)
const [callLock, setCallLock] = useState<boolean>(false)
const callLockRef = useRef(callLock)
useAsyncEffect(async () => {
if(!callLockRef.current) {
callLockRef.current = true
setCallLock(true)
await userStore.sync(page)
callLockRef.current = false
setCallLock(false)
}
}, [page])
console.log(userStore.tableUsers)
return (
<UserTableStyle>
<UserTableHead>
<UserTH>id</UserTH>
<UserTH>name</UserTH>
<UserTH>position</UserTH>
<UserTH>active</UserTH>
<UserTH>admin</UserTH>
</UserTableHead>
<UserTableBody>
{userStore.tableUsers.map((u) => (
<UserTableRow key={u.Id}>
<UserTableItem>{u.Id}</UserTableItem>
<UserTableItem>{u.Name}</UserTableItem>
<UserTableItem>{u.JobPosition}</UserTableItem>
<UserTableItem><input type="checkbox" defaultValue={u.Active ? "yes" : "no"} onChange={async (e) => {
if(u.Active)
await userStore.deactivateUser(u.Id)
else
await userStore.activateUser(u.Id)
}}/></UserTableItem>
<UserTableItem><input type="checkbox" value={u.Admin ? "yes" : "no"} onChange={async (e) => {
if(u.Admin)
await userStore.demoteUser(u.Id)
else
await userStore.promoteUser(u.Id)
}}/></UserTableItem>
</UserTableRow>))}
</UserTableBody>
</UserTableStyle>
)
}

BIN
ordr-ui/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

26
ordr-ui/app/globals.css Normal file
View File

@@ -0,0 +1,26 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}

View File

@@ -0,0 +1,11 @@
'use client'
import { ItemTableList } from "../components/ItemTableList"
const Items = () => {
return (
<ItemTableList />
)
}
export default Items

36
ordr-ui/app/layout.tsx Normal file
View File

@@ -0,0 +1,36 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { NavBar } from "./components/NavBar";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<NavBar />
{children}
</body>
</html>
);
}

View File

@@ -0,0 +1,89 @@
'use client'
import {useParams} from 'next/navigation'
import { useState } from 'react'
import { OrderTableList } from '@/app/components/OrderTableList'
import useAsyncEffect from 'use-async-effect'
import DatePicker from 'react-datepicker'
import "react-datepicker/dist/react-datepicker.css"
import { useOrderStore } from '@/app/providers/OrderProvider'
const OrderTable = () => {
const {page, filter} = useParams()
console.log(filter)
const [tempOrderer, setTempOrderer] = useState("")
const [tempDateDue, setTempDateDue] = useState("")
const [tempDatePlaced, setTempDatePlaced] = useState("")
const [orderer, setOrderer] = useState("")
const [dateDue, setDateDue] = useState("")
const [datePlaced, setDatePlaced] = useState("")
const orderStore = useOrderStore((state) => state)
const [shouldPushUpdates, setShouldPushUpdates] = useState(false)
const [shouldPushNewOrder, setShouldPushNewOrder] = useState(false)
const [newOrderOrderer, setNewOrderOrderer] = useState("")
const [newOrderDue, setNewOrderDue] = useState<Date | null>(null)
useAsyncEffect(async () => {
if(shouldPushUpdates) {
setOrderer(tempOrderer)
setDateDue(tempDateDue)
setDatePlaced(tempDatePlaced)
setShouldPushUpdates(false)
}
}, [shouldPushUpdates])
useAsyncEffect(async () => {
if(shouldPushNewOrder) {
if(newOrderDue)
orderStore.createOrder(newOrderOrderer, newOrderDue.toISOString())
setShouldPushNewOrder(false)
}
}, [shouldPushNewOrder])
return (
<>
<h1 className="text-xl font-bold mt-5">Search</h1>
<input type='text' placeholder="orderer" onChange={(e) => {
console.log(e.currentTarget.value)
setTempOrderer(e.currentTarget.value)
}} />
<input type='text' placeholder="date due" onChange={(e) => {
setTempDateDue(e.currentTarget.value)
}} />
<input type='text' placeholder="date placed" onChange={(e) => {
setTempDatePlaced(e.currentTarget.value)
}} />
<br />
<button className="border border-white p-1 mt-3 mb-5" onClick={() => {
setShouldPushUpdates(true)
}}>Search</button>
<hr className="mb-5"/>
<OrderTableList page={parseInt(page as string)} filter={parseInt(filter as string)} orderer={orderer} dateDue={dateDue} datePlaced={datePlaced}/>
<h1 className="text-xl font-bold">Create new order</h1>
<div className="inline-block w-100">
<input className="inline-block w-20" placeholder="orderer" onChange={(e) => {
setNewOrderOrderer(e.currentTarget.value)
}}/>
<DatePicker
selected={newOrderDue}
onChange={(date: Date | null) => setNewOrderDue(date)}
dateFormat="MM/dd/yyyy" // Example format
placeholderText="Due date"
/>
<br />
<button onClick={() => {
setShouldPushNewOrder(true)
}}>Create</button>
</div>
</>
)
}
export default OrderTable

32
ordr-ui/app/page.tsx Normal file
View File

@@ -0,0 +1,32 @@
'use client'
import Image from "next/image";
import { useAsyncEffect } from 'use-async-effect'
import { useShallow } from 'zustand/react/shallow'
import { UserResponse } from './client/response'
import { useCurrentAuthenticatedUserStore, UserActions } from './providers'
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function Home() {
const authenticatedUserStore: UserResponse & UserActions = useCurrentAuthenticatedUserStore(useShallow((state) => ({
...state
})))
useAsyncEffect(async () => {
if(authenticatedUserStore.Id === -1) {
await authenticatedUserStore.sync()
}
})
const router = useRouter()
useEffect(() => {
router.push('/orders/0/0')
}, [router])
return (
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
</main>
</div>
);
}

View File

@@ -0,0 +1,27 @@
import { create } from 'zustand'
import { UserResponse } from '../client/response'
import { GetCurrentUser, SetUserName } from '../client/controllers'
export type UserActions = {
sync: () => Promise<UserResponse | undefined>
updateName: (name: string) => Promise<void>
}
export const useCurrentAuthenticatedUserStore = create<UserResponse & UserActions>((set) => ({
Id: -1,
Name: '',
JobPosition: '',
Active: false,
Admin: false,
sync: async () => {
const authUser = await GetCurrentUser()
set((state) => ({
...authUser,
...state
}))
return authUser
},
updateName: async (name: string) => {
await SetUserName(name)
}
}))

View File

@@ -0,0 +1,188 @@
import { create } from 'zustand'
import { ItemPriceResponse, OrderItemPriceResponse, OrderFilledResponse } from '../client/response'
import * as ItemController from '../client/controllers/ItemController'
import { CreateItemQuery } from '../client/queries/CreateItemQuery'
import { SetItemPriceQuery } from '../client/queries/SetItemPriceQuery'
import { blob } from 'stream/consumers'
export type ItemData = {
items: ItemPriceResponse[],
orderItems: OrderItemPriceResponse[]
}
export type ItemActions = {
sync: () => Promise<void>
createItem: (itemName: string, inSeason: boolean, itemPrice: number) => Promise<ItemPriceResponse>
setItemPrice: (itemId: number, price: number) => Promise<void>
getCurrentPrice: (itemId: number) => Promise<ItemPriceResponse>
addItemToOrder: (itemId: number, orderId: number, quantity: number) => Promise<OrderItemPriceResponse>
getOrderItems: (orderId: number) => Promise<OrderItemPriceResponse[]>
setItemMade: (orderId: number, itemId: number, made: number) => Promise<OrderFilledResponse>
setItemQuantity: (orderId: number, itemId: number, quantity: number) => Promise<OrderFilledResponse>
deleteOrderItem: (orderId: number, itemId: number) => Promise<void>
deleteItem: (itemId: number) => Promise<void>
}
export const useItemStore = create<ItemData & ItemActions>((set, get) => ({
items: [],
orderItems: [],
sync: async (): Promise<void> => {
const itemPrices = await ItemController.GetItems()
set((state) => ({
...state,
items: itemPrices
}))
},
createItem: async (itemName: string, inSeason: boolean, itemPrice: number): Promise<ItemPriceResponse> => {
const itemQuery: CreateItemQuery = {
item_name: itemName,
in_season: inSeason ? "1" : "0",
item_price: itemPrice.toString()
}
const itemResponse = await ItemController.CreateItem(itemQuery)
set((state) => ({
...state,
items: [...state.items, itemResponse]
}))
return itemResponse
},
setItemPrice: async (itemId: number, price: number): Promise<void> => {
const itemPriceQuery: SetItemPriceQuery = {
item_id: itemId.toString(),
item_price: price.toString()
}
await ItemController.SetItemPrice(itemPriceQuery)
set((state) => {
const item = state.items.filter((i) => i.ItemId === itemId)[0]
let itemsWithoutItem = state.items.filter((i) => i.ItemId !== itemId)
item.ItemPrice = price
if(!Array.isArray(itemsWithoutItem))
itemsWithoutItem = [itemsWithoutItem]
return {
...state,
items: [...itemsWithoutItem, item].sort((a,b) => {
if(a.InSeason && !b.InSeason)
return 1
if(!a.InSeason && b.InSeason)
return -1
return a.ItemId - b.ItemId
})
}
})
},
getCurrentPrice: async (itemId: number): Promise<ItemPriceResponse> => {
const store = get()
const priceObjectArray = store.items.filter((i: ItemPriceResponse) => i.ItemId === itemId)
if(priceObjectArray.length > 0) {
return priceObjectArray[0]
}
const resp = await ItemController.GetCurrentPrice({item_id: itemId.toString()})
set((state) => ({
...state,
items: [...state.items, resp]
}))
return resp
},
addItemToOrder: async (itemId: number, orderId: number, quantity: number): Promise<OrderItemPriceResponse> => {
const resp = await ItemController.AddItemToOrder({item_id: itemId.toString(), order_id: orderId.toString(), quantity: quantity.toString()})
set((state) => ({
...state,
orderItems: [...state.orderItems, resp]
}))
return resp
},
getOrderItems: async (orderId: number): Promise<OrderItemPriceResponse[]> => {
const state = get()
const fetchedOrderItems = state.orderItems
const orderOrderItems = fetchedOrderItems.filter((i) => i.OrderId === orderId)
if(orderOrderItems.length > 0) {
return orderOrderItems
}
const resp = await ItemController.GetOrderItems({order_id: orderId.toString()})
set((state) => ({
orderItems: [...state.orderItems, ...resp]
}))
return resp
},
setItemMade: async (orderId: number, itemId: number, made: number): Promise<OrderFilledResponse> => {
const order_filled: OrderFilledResponse = await ItemController.SetItemMade({
order_id: orderId,
item_id: itemId,
made: made
})
set((state) => {
// TODO: Update order filled once order store is made
const orderItem = state.orderItems.filter((oi) => oi.ItemId === itemId && oi.OrderId === orderId)[0]
const orderItemsWithoutOrderItem = state.orderItems.filter((oi) => oi.ItemId !== itemId || oi.OrderId !== orderId)
orderItem.Made = made
return {
...state,
orderItems: [...orderItemsWithoutOrderItem, orderItem]
}
})
return order_filled
},
setItemQuantity: async (orderId: number, itemId: number, quantity: number): Promise<OrderFilledResponse> => {
const order_filled: OrderFilledResponse = await ItemController.SetItemQuantity({
order_id: orderId,
item_id: itemId,
quantity: quantity
})
set((state) => {
// TODO: Update order filled once order store is made
const orderItem = state.orderItems.filter((oi) => oi.ItemId === itemId && oi.OrderId === orderId)[0]
const orderItemsWithoutOrderItem = state.orderItems.filter((oi) => oi.ItemId !== itemId || oi.OrderId !== orderId)
orderItem.Quantity = quantity
return {
...state,
orderItems: [...orderItemsWithoutOrderItem, orderItem]
}
})
return order_filled
},
deleteOrderItem: async (orderId: number, itemId: number): Promise<void> => {
await ItemController.DeleteOrderItem({order_id: orderId, item_id: itemId})
set((state) => ({
...state,
orderItems: [...(state.orderItems.filter((i) => i.OrderId !== orderId || i.ItemId !== itemId))]
}))
},
deleteItem: async (itemId: number): Promise<void> => {
await ItemController.DeleteItem(itemId)
set((state) => {
const itemsWithoutItem = state.items.filter((i) => i.ItemId !== itemId)
const orderItemsWithoutItem = state.orderItems.filter((i) => i.ItemId !== itemId)
return {
...state,
items: itemsWithoutItem,
orderItems: orderItemsWithoutItem
}
})
}
}))

View File

@@ -0,0 +1,43 @@
import { create } from 'zustand'
import { OrderResponse } from '../client/response'
import { OrderTableQuery } from '../client/request/GetOrderTableRequest'
import * as OrderController from '../client/controllers/OrderController'
type OrderData = {
orders: OrderResponse[]
}
type OrderActions = {
sync: (page: number, filter: number, searchParams: OrderTableQuery) => Promise<OrderResponse[]>
createOrder: (orderer: string, dateDue: string) => Promise<OrderResponse>
getOrderById: (orderId: number) => Promise<OrderResponse>
deleteOrder: (orderId: number) => Promise<void>
}
export const useOrderStore = create<OrderData & OrderActions>((set, get) => ({
orders: [],
sync: async (page: number, filter: number, searchParams: OrderTableQuery): Promise<OrderResponse[]> => {
const resp = await OrderController.GetOrderTable(page, filter, searchParams)
set((state) => ({
...state,
orders: resp
}))
return resp
},
createOrder: async (orderer: string, dateDue: string): Promise<OrderResponse> => {
const resp = await OrderController.CreateOrder(orderer, dateDue)
console.log(resp)
set((state) => ({
...state,
orders: [...state.orders, resp]
}))
console.log(get().orders)
return resp
},
getOrderById: async (orderId: number): Promise<OrderResponse> => {
return await OrderController.GetOrderById(orderId)
},
deleteOrder: async (orderId): Promise<void> => {
await OrderController.DeleteOrder(orderId)
}
}))

View File

@@ -0,0 +1,113 @@
import { create } from 'zustand'
import { UserResponse } from '../client/response'
import { GetUserTable, SetUserPosition, PromoteUser, DemoteUser, DeactivateUser, CreatePosition, ActivateUser } from '../client/controllers'
type UserData = {
tableUsers: UserResponse[]
}
type UsersActions = {
sync: (page: number) => Promise<UserResponse[]>
setUserPosition: (userId: number, positionName: string) => Promise<void>
promoteUser: (userId: number) => Promise<void>
demoteUser: (userId: number) => Promise<void>
deactivateUser: (userId: number) => Promise<void>
activateUser: (userId: number) => Promise<void>
createPosition: (positionName: string) => Promise<void>
}
export const useUserStore = create<UserData & UsersActions>((set) => ({
sync: async (page: number): Promise<UserResponse[]> => {
const users_in_page = await GetUserTable(page)
set((state) => ({
... state,
tableUsers: users_in_page,
}))
return users_in_page
},
tableUsers: [] as UserResponse[],
setUserPosition: async (userId, positionName): Promise<void> => {
await SetUserPosition(userId, positionName)
set((state) => {
const match_user = state.tableUsers.filter((u) => u.Id === userId)[0]
match_user.JobPosition = positionName
return {
... state,
tableUsers: [...state.tableUsers, match_user]
}
})
},
promoteUser: async (userId: number): Promise<void> => {
await PromoteUser(userId)
set((state) => {
const users = state.tableUsers.filter((u) => u.Id === userId)
if(users.length > 0)
{
const user = users[0]
const tableUsersWithoutUser = state.tableUsers.filter((u) => u.Id !== userId)
user.Admin = true
return {
...state,
tableUsers: [...tableUsersWithoutUser, user]
}
}
return state
})
},
demoteUser: async (userId: number): Promise<void> => {
await DemoteUser(userId)
set((state) => {
const users = state.tableUsers.filter((u) => u.Id === userId)
if(users.length > 0)
{
const user = users[0]
const tableUsersWithoutUser = state.tableUsers.filter((u) => u.Id !== userId)
user.Admin = false
return {
...state,
tableUsers: [...tableUsersWithoutUser, user]
}
}
return state
})
},
deactivateUser: async (userId: number): Promise<void> => {
await DeactivateUser(userId)
set((state) => {
const users = state.tableUsers.filter((u) => u.Id === userId)
if(users.length > 0)
{
const user = users[0]
const tableUsersWithoutUser = state.tableUsers.filter((u) => u.Id !== userId)
user.Active = false
return {
...state,
tableUsers: [...tableUsersWithoutUser, user]
}
}
return state
})
},
activateUser: async (userId: number): Promise<void> => {
await ActivateUser(userId)
set((state) => {
const users = state.tableUsers.filter((u) => u.Id === userId)
if(users.length > 0)
{
const user = users[0]
const tableUsersWithoutUser = state.tableUsers.filter((u) => u.Id !== userId)
user.Active = true
return {
...state,
tableUsers: [...tableUsersWithoutUser, user]
}
}
return state
})
},
createPosition: async (positionName: string): Promise<void> => {
await CreatePosition(positionName)
}
}))

View File

@@ -0,0 +1 @@
export * from './AuthenticationProvider'

View File

@@ -0,0 +1,15 @@
'use client'
import { useParams } from 'next/navigation'
import { UserTable } from '@/app/components/UserTable'
const Users = () => {
const {page} = useParams()
return (
<>
<UserTable page={parseInt(page as string)} />
</>
)
}
export default Users

18
ordr-ui/eslint.config.mjs Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

7
ordr-ui/next.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

6589
ordr-ui/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
ordr-ui/package.json Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "ordr-ui",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@uidotdev/usehooks": "^2.4.1",
"async-mutex": "^0.5.0",
"axios": "^1.13.2",
"date-fns": "^4.1.0",
"dotenv": "^17.2.3",
"next": "16.0.2",
"react": "19.2.0",
"react-date-picker": "^12.0.1",
"react-datepicker": "^8.9.0",
"react-dom": "19.2.0",
"styled-components": "^6.1.19",
"tailwind": "^4.0.0",
"use-async-effect": "^2.2.7",
"zustand": "^5.0.8"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.0.2",
"tailwindcss": "^4",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

1
ordr-ui/public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
ordr-ui/public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
ordr-ui/public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

37
ordr-ui/tsconfig.json Normal file
View File

@@ -0,0 +1,37 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
},
{
"name": "@styled/typescript-styled-plugin"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}

4532
ordr-ui/yarn.lock Normal file

File diff suppressed because it is too large Load Diff