feat: add components management functionality

This commit is contained in:
Tran Anh Tuan
2026-05-11 10:35:38 +07:00
parent 50564e9b78
commit bf20286f04
15 changed files with 1662 additions and 1 deletions

View File

@@ -0,0 +1,60 @@
package mapper
import (
"wm-backend/internal/models"
db "wm-backend/sqlc_gen"
"encoding/json"
"github.com/jackc/pgx/v5/pgtype"
)
func ToDomainComponent(r db.Component) *models.Component {
return &models.Component{
ID: r.ID,
ComponentTypeID: r.ComponentTypeID,
Name: r.Name,
Description: r.Description.String,
Unit: r.Unit,
TotalQuantity: r.TotalQuantity,
MinQuantity: r.MinQuantity,
Metadata: json.RawMessage(r.Metadata),
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
}
}
func ToModelComponent(r *models.Component) *db.CreateComponentParams {
return &db.CreateComponentParams{
ComponentTypeID: r.ComponentTypeID,
Name: r.Name,
Description: pgtype.Text{
String: r.Description,
Valid: r.Description != "",
},
Unit: r.Unit,
MinQuantity: r.MinQuantity,
Metadata: []byte(r.Metadata),
CreatedAt: r.CreatedAt,
}
}
func ToUpdateModelComponent(r *models.Component) *db.UpdateComponentParams {
var metadata []byte
if len(r.Metadata) > 0 {
metadata = []byte(r.Metadata)
}
return &db.UpdateComponentParams{
ComponentTypeID: r.ComponentTypeID,
Name: r.Name,
Description: pgtype.Text{
String: r.Description,
Valid: r.Description != "",
},
Unit: r.Unit,
MinQuantity: r.MinQuantity,
Metadata: metadata,
UpdatedAt: r.UpdatedAt,
ID: r.ID,
}
}

View File

@@ -0,0 +1,19 @@
package models
import (
"encoding/json"
"time"
)
type Component struct {
ID int64 `json:"id"`
ComponentTypeID int64 `json:"componentTypeId"`
Name string `json:"name"`
Description string `json:"description"`
Unit string `json:"unit"`
TotalQuantity int32 `json:"totalQuantity"`
MinQuantity int32 `json:"minQuantity"`
Metadata json.RawMessage `json:"metadata"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}

View File

@@ -0,0 +1,21 @@
package requests
import "encoding/json"
type CreateComponentRequest struct {
ComponentTypeID int64 `json:"componentTypeId" binding:"required"`
Name string `json:"name" binding:"required"`
Description string `json:"description"`
Unit string `json:"unit" binding:"required"`
MinQuantity int32 `json:"minQuantity" binding:"required"`
Metadata json.RawMessage `json:"metadata"`
}
type UpdateComponentRequest struct {
ComponentTypeID int64 `json:"componentTypeId"`
Name string `json:"name"`
Description string `json:"description"`
Unit string `json:"unit"`
MinQuantity int32 `json:"minQuantity"`
Metadata json.RawMessage `json:"metadata"`
}

View File

@@ -0,0 +1,14 @@
package responses
type CreateComponentResponse struct {
ID int64 `json:"id"`
}
type UpdateComponentResponse struct {
ID int64 `json:"id"`
ComponentTypeID int64 `json:"componentTypeId"`
Name string `json:"name"`
Description string `json:"description"`
Unit string `json:"unit"`
MinQuantity int32 `json:"minQuantity"`
}

View File

@@ -0,0 +1,55 @@
package repositories
import (
"context"
"wm-backend/internal/mapper"
"wm-backend/internal/models"
db "wm-backend/sqlc_gen"
"github.com/rs/zerolog/log"
)
func CreateComponent(ctx context.Context, queries *db.Queries, body models.Component) (models.Component, error) {
result, err := queries.CreateComponent(ctx, *mapper.ToModelComponent(&body))
if err != nil {
return models.Component{}, err
}
return *mapper.ToDomainComponent(result), nil
}
func GetComponentByID(ctx context.Context, queries *db.Queries, id int64) (models.Component, error) {
result, err := queries.GetComponentByID(ctx, id)
if err != nil {
return models.Component{}, err
}
return *mapper.ToDomainComponent(result), nil
}
func ListComponents(ctx context.Context, queries *db.Queries) ([]models.Component, error) {
results, err := queries.ListComponents(ctx)
if err != nil {
return nil, err
}
var items []models.Component
for _, r := range results {
items = append(items, *mapper.ToDomainComponent(r))
}
return items, nil
}
func UpdateComponent(ctx context.Context, queries *db.Queries, body models.Component) (models.Component, error) {
result, err := queries.UpdateComponent(ctx, *mapper.ToUpdateModelComponent(&body))
log.Info().Any("component", result).Err(err).Msg("Updating component")
if err != nil {
return models.Component{}, err
}
return *mapper.ToDomainComponent(result), nil
}
func DeleteComponent(ctx context.Context, queries *db.Queries, id int64) (int64, error) {
rowsAffected, err := queries.DeleteComponent(ctx, id)
if err != nil {
return rowsAffected, err
}
return rowsAffected, nil
}

View File

@@ -82,6 +82,15 @@ func NewRouter() *gin.Engine {
componentType.PUT("/:id", utils.AsyncHandler(services.ComponentTypeUpdate))
componentType.DELETE("/:id", utils.AsyncHandler(services.ComponentTypeDelete))
}
component := v1.Group(constants.API_GROUP_COMPONENT)
{
component.GET("", utils.AsyncHandler(services.ComponentList))
component.GET("/:id", utils.AsyncHandler(services.ComponentGetByID))
component.POST("", utils.AsyncHandler(services.ComponentCreate))
component.PUT("/:id", utils.AsyncHandler(services.ComponentUpdate))
component.DELETE("/:id", utils.AsyncHandler(services.ComponentDelete))
}
}
r.GET(constants.API_PATH_PING, services.PingHandler)

View File

@@ -0,0 +1,201 @@
package services
import (
"net/http"
"strconv"
"time"
"wm-backend/global"
"wm-backend/internal/models"
"wm-backend/internal/models/requests"
"wm-backend/internal/models/responses"
"wm-backend/internal/repositories"
"wm-backend/pkg/helper"
"wm-backend/response"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
)
// ComponentCreate creates a new component.
// It validates the request body and creates the component in the database.
//
// @Summary Create a new component
// @Description Create a new component with the provided details
// @Tags component
// @Accept json
// @Produce json
// @Param body body requests.CreateComponentRequest true "Component request body"
// @Success 201 {object} response.SuccessResponse{data=responses.CreateComponentResponse}
// @Failure 400 {object} response.ErrorResponse
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/components [post]
func ComponentCreate(c *gin.Context) error {
requestBody := requests.CreateComponentRequest{}
if helper.IsShouldBindJSON(c, &requestBody) {
return nil
}
componentModel := &models.Component{
ComponentTypeID: requestBody.ComponentTypeID,
Name: requestBody.Name,
Description: requestBody.Description,
Unit: requestBody.Unit,
MinQuantity: requestBody.MinQuantity,
Metadata: requestBody.Metadata,
CreatedAt: time.Now(),
}
component, err := repositories.CreateComponent(c.Request.Context(), global.Queries, *componentModel)
if err != nil {
response.InternalServerError(c, http.StatusInternalServerError, "Failed to create component")
return nil
}
response.Created(c, "Component created successfully", &responses.CreateComponentResponse{
ID: component.ID,
})
return nil
}
// ComponentGetByID retrieves a single component by its ID.
//
// @Summary Get component by ID
// @Description Retrieve a single component using its unique identifier
// @Tags component
// @Accept json
// @Produce json
// @Param id path int true "Component ID"
// @Success 200 {object} response.SuccessResponse{data=models.Component}
// @Failure 400 {object} response.ErrorResponse
// @Failure 404 {object} response.ErrorResponse
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/components/{id} [get]
func ComponentGetByID(c *gin.Context) error {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequestError(c, http.StatusBadRequest, "Invalid ID")
return nil
}
component, err := repositories.GetComponentByID(c.Request.Context(), global.Queries, id)
if err != nil {
response.NotFoundError(c, http.StatusNotFound, "Component not found")
return nil
}
response.Ok(c, "Success", component)
return nil
}
// ComponentList retrieves all components.
//
// @Summary List all components
// @Description Retrieve a list of all components ordered by creation date
// @Tags component
// @Accept json
// @Produce json
// @Success 200 {object} response.SuccessResponse{data=[]models.Component}
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/components [get]
func ComponentList(c *gin.Context) error {
components, err := repositories.ListComponents(c.Request.Context(), global.Queries)
if err != nil {
response.InternalServerError(c, http.StatusInternalServerError, "Failed to list components")
return nil
}
response.Ok(c, "Success", components)
return nil
}
// ComponentUpdate updates an existing component by its ID.
// It validates the request body, fetches the existing record,
// merges non-empty fields from the request, and updates the component in the database.
//
// @Summary Update component
// @Description Update an existing component by its ID. Only non-empty fields will be updated.
// @Tags component
// @Accept json
// @Produce json
// @Param id path int true "Component ID"
// @Param body body requests.UpdateComponentRequest true "Component request body"
// @Success 200 {object} response.SuccessResponse{data=responses.UpdateComponentResponse}
// @Failure 400 {object} response.ErrorResponse
// @Failure 404 {object} response.ErrorResponse
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/components/{id} [put]
func ComponentUpdate(c *gin.Context) error {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequestError(c, http.StatusBadRequest, "Invalid ID")
return nil
}
requestBody := requests.UpdateComponentRequest{}
if helper.IsShouldBindJSON(c, &requestBody) {
return nil
}
existing, err := repositories.GetComponentByID(c.Request.Context(), global.Queries, id)
if err != nil {
response.NotFoundError(c, http.StatusNotFound, "Component not found")
return nil
}
if requestBody.ComponentTypeID != 0 {
existing.ComponentTypeID = requestBody.ComponentTypeID
}
if requestBody.Name != "" {
existing.Name = requestBody.Name
}
if requestBody.Description != "" {
existing.Description = requestBody.Description
}
if requestBody.Unit != "" {
existing.Unit = requestBody.Unit
}
if requestBody.MinQuantity != 0 {
existing.MinQuantity = requestBody.MinQuantity
}
if len(requestBody.Metadata) > 0 {
existing.Metadata = requestBody.Metadata
}
existing.UpdatedAt = time.Now()
component, err := repositories.UpdateComponent(c.Request.Context(), global.Queries, existing)
if err != nil {
response.InternalServerError(c, http.StatusInternalServerError, "Failed to update component")
return nil
}
response.Ok(c, "Component updated successfully", &responses.UpdateComponentResponse{
ID: component.ID,
ComponentTypeID: component.ComponentTypeID,
Name: component.Name,
Description: component.Description,
Unit: component.Unit,
MinQuantity: component.MinQuantity,
})
return nil
}
// ComponentDelete deletes a component by its ID.
//
// @Summary Delete component
// @Description Delete a component by its unique identifier
// @Tags component
// @Accept json
// @Produce json
// @Param id path int true "Component ID"
// @Success 200 {object} response.SuccessResponse
// @Failure 400 {object} response.ErrorResponse
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/components/{id} [delete]
func ComponentDelete(c *gin.Context) error {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequestError(c, http.StatusBadRequest, "Invalid ID")
return nil
}
rowsAffected, err := repositories.DeleteComponent(c.Request.Context(), global.Queries, id)
if err != nil {
log.Error().Err(err).Msgf("Failed to delete component with ID: %d", id)
response.InternalServerError(c, http.StatusInternalServerError, "Failed to delete component")
return nil
}
if rowsAffected == 0 {
response.NotFoundError(c, http.StatusNotFound, "Component not found")
return nil
}
response.Ok(c, "Delete Success", nil)
return nil
}