feat(BE): finance (payment, initial_balance, injection). fix(BE): kandang capacity

This commit is contained in:
Hafizh A. Y
2025-12-27 14:30:03 +07:00
parent e33b23a2aa
commit 1c875a916b
46 changed files with 3068 additions and 23 deletions
@@ -0,0 +1,92 @@
package controller
import (
"strconv"
"gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/dto"
service "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/services"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/validations"
"gitlab.com/mbugroup/lti-api.git/internal/response"
"github.com/gofiber/fiber/v2"
)
type InjectionController struct {
InjectionService service.InjectionService
}
func NewInjectionController(injectionService service.InjectionService) *InjectionController {
return &InjectionController{
InjectionService: injectionService,
}
}
func (u *InjectionController) GetOne(c *fiber.Ctx) error {
param := c.Params("id")
id, err := strconv.Atoi(param)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
}
result, err := u.InjectionService.GetOne(c, uint(id))
if err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.Success{
Code: fiber.StatusOK,
Status: "success",
Message: "Get injection successfully",
Data: dto.ToInjectionListDTO(*result),
})
}
func (u *InjectionController) CreateOne(c *fiber.Ctx) error {
req := new(validation.Create)
if err := c.BodyParser(req); err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
}
result, err := u.InjectionService.CreateOne(c, req)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).
JSON(response.Success{
Code: fiber.StatusCreated,
Status: "success",
Message: "Balance injection created successfully",
Data: dto.ToInjectionListDTO(*result),
})
}
func (u *InjectionController) UpdateOne(c *fiber.Ctx) error {
req := new(validation.Update)
param := c.Params("id")
id, err := strconv.Atoi(param)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
}
if err := c.BodyParser(req); err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
}
result, err := u.InjectionService.UpdateOne(c, req, uint(id))
if err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.Success{
Code: fiber.StatusOK,
Status: "success",
Message: "Update injection successfully",
Data: dto.ToInjectionListDTO(*result),
})
}
@@ -0,0 +1,102 @@
package dto
import (
"strings"
"time"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
approvalDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/approvals/dto"
bankDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/dto"
userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
"gitlab.com/mbugroup/lti-api.git/internal/utils"
)
// === DTO Structs ===
type InjectionRelationDTO struct {
Id uint `json:"id"`
TransactionType string `json:"transaction_type"`
Bank bankDTO.BankRelationDTO `json:"bank,omitempty"`
AdjustmentDate string `json:"adjustment_date"`
Direction string `json:"direction"`
Nominal float64 `json:"nominal"`
Notes string `json:"notes"`
}
type InjectionListDTO struct {
InjectionRelationDTO
CreatedBy uint `json:"created_by"`
CreatedByUser userDTO.UserRelationDTO `json:"created_by_user,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Approval approvalDTO.ApprovalRelationDTO `json:"approval"`
}
type InjectionDetailDTO struct {
InjectionListDTO
}
// === Mapper Functions ===
func ToInjectionRelationDTO(e entity.Payment) InjectionRelationDTO {
return InjectionRelationDTO{
Id: e.Id,
TransactionType: transactionTypeLabel(e.TransactionType),
Bank: bankFromInjection(e),
AdjustmentDate: utils.FormatDate(e.PaymentDate),
Direction: e.Direction,
Nominal: e.Nominal,
Notes: e.Notes,
}
}
func ToInjectionListDTO(e entity.Payment) InjectionListDTO {
approval := approvalDTO.ApprovalRelationDTO{}
if e.LatestApproval != nil {
approval = approvalDTO.ToApprovalDTO(*e.LatestApproval)
}
return InjectionListDTO{
InjectionRelationDTO: ToInjectionRelationDTO(e),
CreatedBy: e.CreatedBy,
CreatedByUser: userFromInjection(e),
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
Approval: approval,
}
}
func ToInjectionListDTOs(e []entity.Payment) []InjectionListDTO {
result := make([]InjectionListDTO, len(e))
for i, r := range e {
result[i] = ToInjectionListDTO(r)
}
return result
}
func ToInjectionDetailDTO(e entity.Payment) InjectionDetailDTO {
return InjectionDetailDTO{
InjectionListDTO: ToInjectionListDTO(e),
}
}
func bankFromInjection(e entity.Payment) bankDTO.BankRelationDTO {
if e.BankWarehouse.Id == 0 {
return bankDTO.BankRelationDTO{}
}
return bankDTO.ToBankRelationDTO(e.BankWarehouse)
}
func userFromInjection(e entity.Payment) userDTO.UserRelationDTO {
if e.CreatedUser.Id == 0 {
return userDTO.UserRelationDTO{}
}
return userDTO.ToUserRelationDTO(e.CreatedUser)
}
func transactionTypeLabel(transactionType string) string {
if strings.EqualFold(transactionType, string(utils.TransactionTypeInjection)) {
return "Injection"
}
return transactionType
}
@@ -0,0 +1,36 @@
package injections
import (
"fmt"
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v2"
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
"gitlab.com/mbugroup/lti-api.git/internal/utils"
"gorm.io/gorm"
rInjection "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/repositories"
sInjection "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/services"
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
)
type InjectionModule struct{}
func (InjectionModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
injectionRepo := rInjection.NewInjectionRepository(db)
userRepo := rUser.NewUserRepository(db)
approvalRepo := commonRepo.NewApprovalRepository(db)
approvalService := commonSvc.NewApprovalService(approvalRepo)
if err := approvalService.RegisterWorkflowSteps(utils.ApprovalWorkflowInjection, utils.InjectionApprovalSteps); err != nil {
panic(fmt.Sprintf("failed to register injection approval workflow: %v", err))
}
injectionService := sInjection.NewInjectionService(injectionRepo, approvalService, validate)
userService := sUser.NewUserService(userRepo, validate)
InjectionRoutes(router, userService, injectionService)
}
@@ -0,0 +1,41 @@
package repository
import (
"context"
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
"gorm.io/gorm"
)
type InjectionRepository interface {
repository.BaseRepository[entity.Payment]
BankExists(ctx context.Context, bankId uint) (bool, error)
NextPaymentSequence(ctx context.Context) (int64, error)
}
type InjectionRepositoryImpl struct {
*repository.BaseRepositoryImpl[entity.Payment]
db *gorm.DB
}
func NewInjectionRepository(db *gorm.DB) InjectionRepository {
return &InjectionRepositoryImpl{
BaseRepositoryImpl: repository.NewBaseRepository[entity.Payment](db),
db: db,
}
}
func (r *InjectionRepositoryImpl) BankExists(ctx context.Context, bankId uint) (bool, error) {
return repository.Exists[entity.Bank](ctx, r.db, bankId)
}
func (r *InjectionRepositoryImpl) NextPaymentSequence(ctx context.Context) (int64, error) {
var next int64
if err := r.db.WithContext(ctx).
Raw("SELECT nextval('payments_code_seq')").
Scan(&next).Error; err != nil {
return 0, err
}
return next, nil
}
@@ -0,0 +1,21 @@
package injections
import (
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/controllers"
injection "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/services"
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
"github.com/gofiber/fiber/v2"
)
func InjectionRoutes(v1 fiber.Router, u user.UserService, s injection.InjectionService) {
ctrl := controller.NewInjectionController(s)
route := v1.Group("/injections")
// route.Use(m.Auth(u))
route.Post("/", ctrl.CreateOne)
route.Get("/:id", ctrl.GetOne)
route.Patch("/:id", ctrl.UpdateOne)
}
@@ -0,0 +1,230 @@
package service
import (
"context"
"errors"
"fmt"
"strings"
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/repositories"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/injections/validations"
"gitlab.com/mbugroup/lti-api.git/internal/utils"
approvalutils "gitlab.com/mbugroup/lti-api.git/internal/utils/approvals"
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v2"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
type InjectionService interface {
GetOne(ctx *fiber.Ctx, id uint) (*entity.Payment, error)
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Payment, error)
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Payment, error)
}
type injectionService struct {
Log *logrus.Logger
Validate *validator.Validate
Repository repository.InjectionRepository
ApprovalSvc commonSvc.ApprovalService
approvalWorkflow approvalutils.ApprovalWorkflowKey
}
func NewInjectionService(
repo repository.InjectionRepository,
approvalSvc commonSvc.ApprovalService,
validate *validator.Validate,
) InjectionService {
return &injectionService{
Log: utils.Log,
Validate: validate,
Repository: repo,
ApprovalSvc: approvalSvc,
approvalWorkflow: utils.ApprovalWorkflowInjection,
}
}
func (s injectionService) withRelations(db *gorm.DB) *gorm.DB {
return db.Preload("CreatedUser").
Preload("BankWarehouse")
}
func (s injectionService) GetOne(c *fiber.Ctx, id uint) (*entity.Payment, error) {
injection, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Injection not found")
}
if err != nil {
s.Log.Errorf("Failed get injection by id: %+v", err)
return nil, err
}
if !isInjectionTransaction(injection.TransactionType) {
return nil, fiber.NewError(fiber.StatusNotFound, "Injection not found")
}
if s.ApprovalSvc != nil {
approval, err := s.ApprovalSvc.LatestByTarget(c.Context(), s.approvalWorkflow, id, s.approvalQueryModifier())
if err != nil {
s.Log.Warnf("Unable to load latest approval for injection %d: %+v", id, err)
} else {
injection.LatestApproval = approval
}
}
return injection, nil
}
func (s *injectionService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Payment, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
if err := s.ensureBankExists(c.Context(), req.BankId); err != nil {
return nil, err
}
adjustmentDate, err := utils.ParseDateString(req.AdjustmentDate)
if err != nil {
return nil, utils.BadRequest(err.Error())
}
actorID, err := m.ActorIDFromContext(c)
if err != nil {
return nil, err
}
code, err := s.generateInjectionCode(c.Context())
if err != nil {
return nil, err
}
createBody := &entity.Payment{
PaymentCode: code,
TransactionType: string(utils.TransactionTypeInjection),
PartyType: string(utils.PaymentPartyCustomer),
PartyId: 0,
PaymentDate: adjustmentDate,
PaymentMethod: string(utils.PaymentMethodSaldo),
BankId: req.BankId,
Direction: "IN",
Nominal: req.Nominal,
Notes: req.Notes,
CreatedBy: actorID,
}
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
injectionRepoTx := repository.NewInjectionRepository(dbTransaction)
if err := injectionRepoTx.CreateOne(c.Context(), createBody, nil); err != nil {
return err
}
if s.ApprovalSvc != nil {
action := entity.ApprovalActionCreated
approvalSvcTx := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(dbTransaction))
_, err := approvalSvcTx.CreateApproval(
c.Context(),
s.approvalWorkflow,
createBody.Id,
utils.InjectionStepPengajuan,
&action,
actorID,
nil,
)
if err != nil {
return err
}
}
return nil
})
if err != nil {
s.Log.Errorf("Failed to create injection: %+v", err)
return nil, err
}
return s.GetOne(c, createBody.Id)
}
func (s injectionService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Payment, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
updateBody := make(map[string]any)
requiresVerification := req.BankId != nil || req.AdjustmentDate != nil || req.Nominal != nil || req.Notes != nil
if requiresVerification {
current, err := s.Repository.GetByID(c.Context(), id, nil)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Injection not found")
}
if err != nil {
s.Log.Errorf("Failed get injection by id: %+v", err)
return nil, err
}
if !isInjectionTransaction(current.TransactionType) {
return nil, fiber.NewError(fiber.StatusNotFound, "Injection not found")
}
}
if req.BankId != nil {
if err := s.ensureBankExists(c.Context(), req.BankId); err != nil {
return nil, err
}
updateBody["bank_id"] = *req.BankId
}
if req.AdjustmentDate != nil {
parsedDate, err := utils.ParseDateString(*req.AdjustmentDate)
if err != nil {
return nil, utils.BadRequest(err.Error())
}
updateBody["payment_date"] = parsedDate
}
if req.Nominal != nil {
updateBody["nominal"] = *req.Nominal
}
if req.Notes != nil {
updateBody["notes"] = *req.Notes
}
if len(updateBody) == 0 {
return s.GetOne(c, id)
}
if err := s.Repository.PatchOne(c.Context(), id, updateBody, nil); err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Injection not found")
}
s.Log.Errorf("Failed to update injection: %+v", err)
return nil, err
}
return s.GetOne(c, id)
}
func isInjectionTransaction(transactionType string) bool {
return strings.EqualFold(transactionType, string(utils.TransactionTypeInjection))
}
func (s injectionService) generateInjectionCode(ctx context.Context) (string, error) {
sequence, err := s.Repository.NextPaymentSequence(ctx)
if err != nil {
return "", err
}
return fmt.Sprintf("INJ-%05d", sequence), nil
}
func (s injectionService) approvalQueryModifier() func(*gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
return db.Preload("ActionUser")
}
}
func (s injectionService) ensureBankExists(ctx context.Context, bankId *uint) error {
return commonSvc.EnsureRelations(ctx,
commonSvc.RelationCheck{Name: "Bank", ID: bankId, Exists: s.Repository.BankExists},
)
}
@@ -0,0 +1,21 @@
package validation
type Create struct {
BankId *uint `json:"bank_id" validate:"required_strict,number,gt=0"`
AdjustmentDate string `json:"adjustment_date" validate:"required_strict"`
Nominal float64 `json:"nominal" validate:"required_strict,gt=0"`
Notes string `json:"notes" validate:"required_strict,max=500"`
}
type Update struct {
BankId *uint `json:"bank_id,omitempty" validate:"omitempty,number,gt=0"`
AdjustmentDate *string `json:"adjustment_date,omitempty" validate:"omitempty"`
Nominal *float64 `json:"nominal,omitempty" validate:"omitempty,gt=0"`
Notes *string `json:"notes,omitempty" validate:"omitempty,max=500"`
}
type Query struct {
Page int `query:"page" validate:"omitempty,number,min=1,gt=0"`
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100,gt=0"`
Search string `query:"search" validate:"omitempty,max=50"`
}