mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
feat(BE): finance (payment, initial_balance, injection). fix(BE): kandang capacity
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/finance/payments/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/payments/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/payments/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type PaymentController struct {
|
||||
PaymentService service.PaymentService
|
||||
}
|
||||
|
||||
func NewPaymentController(paymentService service.PaymentService) *PaymentController {
|
||||
return &PaymentController{
|
||||
PaymentService: paymentService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *PaymentController) 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.PaymentService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get payment successfully",
|
||||
Data: dto.ToPaymentListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *PaymentController) 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.PaymentService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create payment successfully",
|
||||
Data: dto.ToPaymentListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *PaymentController) 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.PaymentService.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 payment successfully",
|
||||
Data: dto.ToPaymentListDTO(*result),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
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 PaymentRelationDTO struct {
|
||||
Id uint `json:"id"`
|
||||
PaymentCode string `json:"payment_code"`
|
||||
ReferenceNumber *string `json:"reference_number,omitempty"`
|
||||
TransactionType string `json:"transaction_type"`
|
||||
Party Party `json:"party"`
|
||||
PaymentDate time.Time `json:"payment_date"`
|
||||
PaymentMethod string `json:"payment_method"`
|
||||
Bank bankDTO.BankRelationDTO `json:"bank,omitempty"`
|
||||
ExpenseAmount float64 `json:"expense_amount"`
|
||||
IncomeAmount float64 `json:"income_amount"`
|
||||
Nominal float64 `json:"nominal"`
|
||||
Notes string `json:"notes"`
|
||||
CreatedUser userDTO.UserRelationDTO `json:"created_user,omitempty"`
|
||||
}
|
||||
|
||||
type PaymentListDTO struct {
|
||||
Id uint `json:"id"`
|
||||
PaymentCode string `json:"payment_code"`
|
||||
ReferenceNumber *string `json:"reference_number"`
|
||||
TransactionType string `json:"transaction_type"`
|
||||
Party Party `json:"party"`
|
||||
PaymentDate time.Time `json:"payment_date"`
|
||||
PaymentMethod string `json:"payment_method"`
|
||||
Bank bankDTO.BankRelationDTO `json:"bank"`
|
||||
ExpenseAmount float64 `json:"expense_amount"`
|
||||
IncomeAmount float64 `json:"income_amount"`
|
||||
Nominal float64 `json:"nominal"`
|
||||
Notes string `json:"notes"`
|
||||
CreatedUser userDTO.UserRelationDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Approval approvalDTO.ApprovalRelationDTO `json:"approval"`
|
||||
}
|
||||
|
||||
type PaymentDetailDTO struct {
|
||||
PaymentListDTO
|
||||
}
|
||||
|
||||
type Party struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
AccountNumber string `json:"account_number"`
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToPaymentRelationDTO(e entity.Payment) PaymentRelationDTO {
|
||||
expenseAmount, incomeAmount := paymentAmounts(e.Direction, e.Nominal)
|
||||
|
||||
return PaymentRelationDTO{
|
||||
Id: e.Id,
|
||||
PaymentCode: paymentCodeFromPayment(e),
|
||||
ReferenceNumber: e.ReferenceNumber,
|
||||
TransactionType: transactionTypeFromPayment(e),
|
||||
Party: partyFromPayment(e),
|
||||
PaymentDate: e.PaymentDate,
|
||||
PaymentMethod: e.PaymentMethod,
|
||||
Bank: bankFromPayment(e),
|
||||
ExpenseAmount: expenseAmount,
|
||||
IncomeAmount: incomeAmount,
|
||||
Nominal: e.Nominal,
|
||||
Notes: e.Notes,
|
||||
CreatedUser: userFromPayment(e),
|
||||
}
|
||||
}
|
||||
|
||||
func ToPaymentListDTO(e entity.Payment) PaymentListDTO {
|
||||
expenseAmount, incomeAmount := paymentAmounts(e.Direction, e.Nominal)
|
||||
approval := approvalDTO.ApprovalRelationDTO{}
|
||||
if e.LatestApproval != nil {
|
||||
approval = approvalDTO.ToApprovalDTO(*e.LatestApproval)
|
||||
}
|
||||
|
||||
return PaymentListDTO{
|
||||
Id: e.Id,
|
||||
PaymentCode: paymentCodeFromPayment(e),
|
||||
ReferenceNumber: e.ReferenceNumber,
|
||||
TransactionType: transactionTypeFromPayment(e),
|
||||
Party: partyFromPayment(e),
|
||||
PaymentDate: e.PaymentDate,
|
||||
PaymentMethod: e.PaymentMethod,
|
||||
Bank: bankFromPayment(e),
|
||||
ExpenseAmount: expenseAmount,
|
||||
IncomeAmount: incomeAmount,
|
||||
Nominal: e.Nominal,
|
||||
Notes: e.Notes,
|
||||
CreatedUser: userFromPayment(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
Approval: approval,
|
||||
}
|
||||
}
|
||||
|
||||
func ToPaymentListDTOs(e []entity.Payment) []PaymentListDTO {
|
||||
result := make([]PaymentListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToPaymentListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToPaymentDetailDTO(e entity.Payment) PaymentDetailDTO {
|
||||
return PaymentDetailDTO{
|
||||
PaymentListDTO: ToPaymentListDTO(e),
|
||||
}
|
||||
}
|
||||
|
||||
func partyFromPayment(e entity.Payment) Party {
|
||||
party := Party{
|
||||
Id: e.PartyId,
|
||||
Type: e.PartyType,
|
||||
}
|
||||
|
||||
switch utils.PaymentParty(e.PartyType) {
|
||||
case utils.PaymentPartyCustomer:
|
||||
if e.Customer != nil && e.Customer.Id != 0 {
|
||||
party.Name = e.Customer.Name
|
||||
party.AccountNumber = e.Customer.AccountNumber
|
||||
}
|
||||
case utils.PaymentPartySupplier:
|
||||
if e.Supplier != nil && e.Supplier.Id != 0 {
|
||||
party.Name = e.Supplier.Name
|
||||
if e.Supplier.AccountNumber != nil {
|
||||
party.AccountNumber = *e.Supplier.AccountNumber
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return party
|
||||
}
|
||||
|
||||
func bankFromPayment(e entity.Payment) bankDTO.BankRelationDTO {
|
||||
if e.BankWarehouse.Id == 0 {
|
||||
return bankDTO.BankRelationDTO{}
|
||||
}
|
||||
return bankDTO.ToBankRelationDTO(e.BankWarehouse)
|
||||
}
|
||||
|
||||
func userFromPayment(e entity.Payment) userDTO.UserRelationDTO {
|
||||
if e.CreatedUser.Id == 0 {
|
||||
return userDTO.UserRelationDTO{}
|
||||
}
|
||||
return userDTO.ToUserRelationDTO(e.CreatedUser)
|
||||
}
|
||||
|
||||
func paymentCodeFromPayment(e entity.Payment) string {
|
||||
if e.PaymentCode != "" {
|
||||
return e.PaymentCode
|
||||
}
|
||||
if e.ReferenceNumber != nil {
|
||||
return *e.ReferenceNumber
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func transactionTypeFromPayment(e entity.Payment) string {
|
||||
if e.TransactionType != "" {
|
||||
return e.TransactionType
|
||||
}
|
||||
return e.Direction
|
||||
}
|
||||
|
||||
func paymentAmounts(direction string, nominal float64) (float64, float64) {
|
||||
switch strings.ToUpper(direction) {
|
||||
case "IN":
|
||||
return 0, nominal
|
||||
case "OUT":
|
||||
return nominal, 0
|
||||
default:
|
||||
return 0, 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package payments
|
||||
|
||||
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"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rPayment "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/payments/repositories"
|
||||
sPayment "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/payments/services"
|
||||
utils "gitlab.com/mbugroup/lti-api.git/internal/utils"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type PaymentModule struct{}
|
||||
|
||||
func (PaymentModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
paymentRepo := rPayment.NewPaymentRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
approvalRepo := commonRepo.NewApprovalRepository(db)
|
||||
approvalService := commonSvc.NewApprovalService(approvalRepo)
|
||||
if err := approvalService.RegisterWorkflowSteps(utils.ApprovalWorkflowPayment, utils.PaymentApprovalSteps); err != nil {
|
||||
panic(fmt.Sprintf("failed to register payment approval workflow: %v", err))
|
||||
}
|
||||
|
||||
paymentService := sPayment.NewPaymentService(paymentRepo, approvalService, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
PaymentRoutes(router, userService, paymentService)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
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 PaymentRepository interface {
|
||||
repository.BaseRepository[entity.Payment]
|
||||
BankExists(ctx context.Context, bankId uint) (bool, error)
|
||||
CustomerExists(ctx context.Context, customerId uint) (bool, error)
|
||||
SupplierExists(ctx context.Context, supplierId uint) (bool, error)
|
||||
SupplierCategory(ctx context.Context, supplierId uint) (string, error)
|
||||
NextPaymentSequence(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
||||
type PaymentRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Payment]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPaymentRepository(db *gorm.DB) PaymentRepository {
|
||||
return &PaymentRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Payment](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) BankExists(ctx context.Context, bankId uint) (bool, error) {
|
||||
return repository.Exists[entity.Bank](ctx, r.db, bankId)
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) CustomerExists(ctx context.Context, customerId uint) (bool, error) {
|
||||
return repository.Exists[entity.Customer](ctx, r.db, customerId)
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) SupplierExists(ctx context.Context, supplierId uint) (bool, error) {
|
||||
return repository.Exists[entity.Supplier](ctx, r.db, supplierId)
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) SupplierCategory(ctx context.Context, supplierId uint) (string, error) {
|
||||
var supplier entity.Supplier
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id", "category").
|
||||
First(&supplier, supplierId).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
return supplier.Category, nil
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) 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 payments
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/payments/controllers"
|
||||
payment "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/payments/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func PaymentRoutes(v1 fiber.Router, u user.UserService, s payment.PaymentService) {
|
||||
ctrl := controller.NewPaymentController(s)
|
||||
|
||||
route := v1.Group("/payments")
|
||||
// route.Use(m.Auth(u))
|
||||
|
||||
route.Post("/", ctrl.CreateOne)
|
||||
route.Get("/:id", ctrl.GetOne)
|
||||
route.Patch("/:id", ctrl.UpdateOne)
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
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/payments/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/payments/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 PaymentService 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 paymentService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.PaymentRepository
|
||||
ApprovalSvc commonSvc.ApprovalService
|
||||
approvalWorkflow approvalutils.ApprovalWorkflowKey
|
||||
}
|
||||
|
||||
func NewPaymentService(
|
||||
repo repository.PaymentRepository,
|
||||
approvalSvc commonSvc.ApprovalService,
|
||||
validate *validator.Validate,
|
||||
) PaymentService {
|
||||
return &paymentService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
ApprovalSvc: approvalSvc,
|
||||
approvalWorkflow: utils.ApprovalWorkflowPayment,
|
||||
}
|
||||
}
|
||||
|
||||
func (s paymentService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("CreatedUser").
|
||||
Preload("BankWarehouse").
|
||||
Preload("Customer").
|
||||
Preload("Supplier")
|
||||
}
|
||||
|
||||
func (s paymentService) GetOne(c *fiber.Ctx, id uint) (*entity.Payment, error) {
|
||||
payment, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Payment not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get payment by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
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 payment %d: %+v", id, err)
|
||||
} else {
|
||||
payment.LatestApproval = approval
|
||||
}
|
||||
}
|
||||
return payment, nil
|
||||
}
|
||||
|
||||
func (s *paymentService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Payment, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//! CHECK PARTY TYPE
|
||||
party, err := normalizePartyType(req.PartyType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//! CHECK EXISTS
|
||||
if err := s.ensurePartyExists(c.Context(), party, req.PartyId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ensureBankExists(c.Context(), req.BankId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//? NORMALIZE
|
||||
paymentDate, err := utils.ParseDateString(req.PaymentDate)
|
||||
if err != nil {
|
||||
return nil, utils.BadRequest(err.Error())
|
||||
}
|
||||
method, err := normalizePaymentMethod(req.PaymentMethod)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transactionType, err := s.resolveTransactionType(c.Context(), party, req.PartyId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//? GET CREATED BY
|
||||
actorID, err := m.ActorIDFromContext(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
code, err := s.generatePaymentCode(c.Context(), party)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
createBody := &entity.Payment{
|
||||
PaymentCode: code,
|
||||
ReferenceNumber: req.ReferenceNumber,
|
||||
TransactionType: transactionType,
|
||||
PartyType: party,
|
||||
PartyId: req.PartyId,
|
||||
PaymentDate: paymentDate,
|
||||
PaymentMethod: method,
|
||||
BankId: req.BankId,
|
||||
Direction: directionForParty(party),
|
||||
Nominal: req.Nominal,
|
||||
Notes: req.Notes,
|
||||
CreatedBy: actorID,
|
||||
}
|
||||
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
|
||||
paymentRepoTx := repository.NewPaymentRepository(dbTransaction)
|
||||
if err := paymentRepoTx.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.PaymentStepPengajuan,
|
||||
&action,
|
||||
actorID,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to create payment: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s paymentService) 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)
|
||||
|
||||
if req.PaymentDate != nil {
|
||||
parsedDate, err := utils.ParseDateString(*req.PaymentDate)
|
||||
if err != nil {
|
||||
return nil, utils.BadRequest(err.Error())
|
||||
}
|
||||
updateBody["payment_date"] = parsedDate
|
||||
}
|
||||
if req.Nominal != nil {
|
||||
updateBody["nominal"] = *req.Nominal
|
||||
}
|
||||
if req.ReferenceNumber != nil {
|
||||
updateBody["reference_number"] = *req.ReferenceNumber
|
||||
}
|
||||
if req.PaymentMethod != nil {
|
||||
method, err := normalizePaymentMethod(*req.PaymentMethod)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updateBody["payment_method"] = method
|
||||
}
|
||||
if req.BankId != nil {
|
||||
if err := s.ensureBankExists(c.Context(), req.BankId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updateBody["bank_id"] = *req.BankId
|
||||
}
|
||||
if req.Notes != nil {
|
||||
updateBody["notes"] = *req.Notes
|
||||
}
|
||||
|
||||
if req.PartyType != nil || req.PartyId != nil {
|
||||
existing, err := s.Repository.GetByID(c.Context(), id, nil)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Payment not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get payment by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
partyType := existing.PartyType
|
||||
partyId := existing.PartyId
|
||||
|
||||
if req.PartyType != nil {
|
||||
normalized, err := normalizePartyType(*req.PartyType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
partyType = normalized
|
||||
updateBody["party_type"] = partyType
|
||||
updateBody["direction"] = directionForParty(partyType)
|
||||
}
|
||||
if req.PartyId != nil {
|
||||
partyId = *req.PartyId
|
||||
updateBody["party_id"] = partyId
|
||||
}
|
||||
|
||||
if err := s.ensurePartyExists(c.Context(), partyType, partyId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
transactionType, err := s.resolveTransactionType(c.Context(), partyType, partyId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updateBody["transaction_type"] = transactionType
|
||||
}
|
||||
|
||||
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, "Payment not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update payment: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func normalizePartyType(partyType string) (string, error) {
|
||||
party := strings.ToUpper(strings.TrimSpace(partyType))
|
||||
if !utils.IsValidPaymentParty(party) {
|
||||
return "", utils.BadRequest("`party_type` must be `customer` or `supplier`")
|
||||
}
|
||||
return party, nil
|
||||
}
|
||||
|
||||
func normalizePaymentMethod(method string) (string, error) {
|
||||
normalized := strings.ToUpper(strings.TrimSpace(method))
|
||||
if !utils.IsValidPaymentMethod(normalized) {
|
||||
return "", utils.BadRequest("Invalid payment_method")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func directionForParty(partyType string) string {
|
||||
if utils.PaymentParty(partyType) == utils.PaymentPartyCustomer {
|
||||
return "IN"
|
||||
}
|
||||
return "OUT"
|
||||
}
|
||||
|
||||
func (s paymentService) resolveTransactionType(ctx context.Context, partyType string, partyId uint) (string, error) {
|
||||
switch utils.PaymentParty(partyType) {
|
||||
case utils.PaymentPartyCustomer:
|
||||
return string(utils.TransactionTypePenjualan), nil
|
||||
case utils.PaymentPartySupplier:
|
||||
category, err := s.getSupplierCategory(ctx, partyId)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if isSupplierCategoryBiaya(category) {
|
||||
return string(utils.TransactionTypeBiaya), nil
|
||||
}
|
||||
return string(utils.TransactionTypePembelian), nil
|
||||
default:
|
||||
return "", utils.BadRequest("`party_type` must be `customer` or `supplier`")
|
||||
}
|
||||
}
|
||||
|
||||
func (s paymentService) generatePaymentCode(ctx context.Context, partyType string) (string, error) {
|
||||
prefix := "PAY"
|
||||
switch utils.PaymentParty(partyType) {
|
||||
case utils.PaymentPartyCustomer:
|
||||
prefix = "PAY-IN"
|
||||
case utils.PaymentPartySupplier:
|
||||
prefix = "PAY-OUT"
|
||||
}
|
||||
sequence, err := s.Repository.NextPaymentSequence(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%s-%05d", prefix, sequence), nil
|
||||
}
|
||||
|
||||
func (s paymentService) approvalQueryModifier() func(*gorm.DB) *gorm.DB {
|
||||
return func(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("ActionUser")
|
||||
}
|
||||
}
|
||||
|
||||
func (s paymentService) ensurePartyExists(ctx context.Context, partyType string, partyId uint) error {
|
||||
switch utils.PaymentParty(partyType) {
|
||||
case utils.PaymentPartyCustomer:
|
||||
return commonSvc.EnsureRelations(ctx,
|
||||
commonSvc.RelationCheck{Name: "Customer", ID: &partyId, Exists: s.Repository.CustomerExists},
|
||||
)
|
||||
case utils.PaymentPartySupplier:
|
||||
return commonSvc.EnsureRelations(ctx,
|
||||
commonSvc.RelationCheck{Name: "Supplier", ID: &partyId, Exists: s.Repository.SupplierExists},
|
||||
)
|
||||
default:
|
||||
return utils.BadRequest("`party_type` must be `customer` or `supplier`")
|
||||
}
|
||||
}
|
||||
|
||||
func (s paymentService) ensureBankExists(ctx context.Context, bankId *uint) error {
|
||||
return commonSvc.EnsureRelations(ctx,
|
||||
commonSvc.RelationCheck{Name: "Bank", ID: bankId, Exists: s.Repository.BankExists},
|
||||
)
|
||||
}
|
||||
|
||||
func (s paymentService) getSupplierCategory(ctx context.Context, supplierId uint) (string, error) {
|
||||
category, err := s.Repository.SupplierCategory(ctx, supplierId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", utils.NotFound("Supplier not found")
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return strings.ToUpper(strings.TrimSpace(category)), nil
|
||||
}
|
||||
|
||||
func isSupplierCategoryBiaya(category string) bool {
|
||||
switch strings.ToUpper(strings.TrimSpace(category)) {
|
||||
case string(utils.SupplierCategoryBOP), "BIAYA":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
PartyType string `json:"party_type" validate:"required_strict,min=1,max=50"`
|
||||
PartyId uint `json:"party_id" validate:"required_strict,number,gt=0"`
|
||||
PaymentDate string `json:"payment_date" validate:"required_strict,datetime=2006-01-02"`
|
||||
Nominal float64 `json:"nominal" validate:"required_strict"`
|
||||
ReferenceNumber *string `json:"reference_number,omitempty"`
|
||||
PaymentMethod string `json:"payment_method" validate:"required_strict,max=20"`
|
||||
BankId *uint `json:"bank_id" validate:"omitempty,number,gt=0"`
|
||||
Notes string `json:"notes" validate:"required_strict,max=500"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
PartyType *string `json:"party_type,omitempty" validate:"omitempty,max=50"`
|
||||
PartyId *uint `json:"party_id,omitempty" validate:"omitempty,number,gt=0"`
|
||||
PaymentDate *string `json:"payment_date,omitempty" validate:"omitempty,datetime=2006-01-02"`
|
||||
Nominal *float64 `json:"nominal,omitempty" validate:"omitempty,gt=0"`
|
||||
ReferenceNumber *string `json:"reference_number,omitempty"`
|
||||
PaymentMethod *string `json:"payment_method,omitempty" validate:"omitempty,max=20"`
|
||||
BankId *uint `json:"bank_id,omitempty" validate:"omitempty,number,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"`
|
||||
}
|
||||
Reference in New Issue
Block a user