mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-06-09 15:07:49 +00:00
Merge branch 'production' into feat/transfer-laying
This commit is contained in:
@@ -45,7 +45,8 @@ func (ExpenseModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *
|
||||
panic(fmt.Sprintf("failed to register expense approval workflow: %v", err))
|
||||
}
|
||||
|
||||
expenseService := sExpense.NewExpenseService(expenseRepo, supplierRepo, nonstockRepo, approvalSvc, realizationRepo, projectFlockKandangRepo, documentSvc, validate)
|
||||
fifoPaymentSvc := commonSvc.NewFifoPaymentService(db, utils.Log)
|
||||
expenseService := sExpense.NewExpenseService(expenseRepo, supplierRepo, nonstockRepo, approvalSvc, realizationRepo, projectFlockKandangRepo, documentSvc, fifoPaymentSvc, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
ExpenseRoutes(router, userService, expenseService)
|
||||
|
||||
@@ -54,9 +54,10 @@ type expenseService struct {
|
||||
RealizationRepository repository.ExpenseRealizationRepository
|
||||
ProjectFlockKandangRepo projectFlockKandangRepo.ProjectFlockKandangRepository
|
||||
DocumentSvc commonSvc.DocumentService
|
||||
FifoPaymentSvc commonSvc.FifoPaymentService
|
||||
}
|
||||
|
||||
func NewExpenseService(repo repository.ExpenseRepository, supplierRepo supplierRepo.SupplierRepository, nonstockRepo nonstockRepo.NonstockRepository, approvalSvc commonSvc.ApprovalService, realizationRepo repository.ExpenseRealizationRepository, projectFlockKandangRepo projectFlockKandangRepo.ProjectFlockKandangRepository, documentSvc commonSvc.DocumentService, validate *validator.Validate) ExpenseService {
|
||||
func NewExpenseService(repo repository.ExpenseRepository, supplierRepo supplierRepo.SupplierRepository, nonstockRepo nonstockRepo.NonstockRepository, approvalSvc commonSvc.ApprovalService, realizationRepo repository.ExpenseRealizationRepository, projectFlockKandangRepo projectFlockKandangRepo.ProjectFlockKandangRepository, documentSvc commonSvc.DocumentService, fifoPaymentSvc commonSvc.FifoPaymentService, validate *validator.Validate) ExpenseService {
|
||||
return &expenseService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
@@ -67,6 +68,23 @@ func NewExpenseService(repo repository.ExpenseRepository, supplierRepo supplierR
|
||||
RealizationRepository: realizationRepo,
|
||||
ProjectFlockKandangRepo: projectFlockKandangRepo,
|
||||
DocumentSvc: documentSvc,
|
||||
FifoPaymentSvc: fifoPaymentSvc,
|
||||
}
|
||||
}
|
||||
|
||||
// reallocateAfterRealization called after expense realization changes that may
|
||||
// affect supplier debt: recompute grand_total + reallocate FIFO.
|
||||
func (s *expenseService) reallocateAfterRealization(ctx context.Context, expenseID uint, supplierID uint64) {
|
||||
if s.FifoPaymentSvc == nil {
|
||||
return
|
||||
}
|
||||
if err := s.FifoPaymentSvc.RecomputeGrandTotal(ctx, nil, commonSvc.ParentKindExpense, expenseID); err != nil {
|
||||
s.Log.Warnf("Failed to recompute grand_total for expense %d: %+v", expenseID, err)
|
||||
}
|
||||
if supplierID > 0 {
|
||||
if err := s.FifoPaymentSvc.ReallocateForParty(ctx, nil, string(utils.PaymentPartySupplier), uint(supplierID)); err != nil {
|
||||
s.Log.Warnf("Failed to reallocate payments for supplier %d: %+v", supplierID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1078,6 +1096,9 @@ func (s *expenseService) CreateRealization(c *fiber.Ctx, expenseID uint, req *va
|
||||
}
|
||||
invalidateFromDate := commonSvc.MinNonZeroDateOnlyUTC(expense.TransactionDate, realizationDate, expense.RealizationDate)
|
||||
s.invalidateDepreciationSnapshotsByExpense(c.Context(), nil, expenseID, invalidateFromDate, nil)
|
||||
|
||||
s.reallocateAfterRealization(c.Context(), expenseID, expense.SupplierId)
|
||||
|
||||
return responseDTO, nil
|
||||
}
|
||||
|
||||
@@ -1522,6 +1543,9 @@ func (s *expenseService) UpdateRealization(c *fiber.Ctx, expenseID uint, req *va
|
||||
return nil, err
|
||||
}
|
||||
s.invalidateDepreciationSnapshotsByExpense(c.Context(), nil, expenseID, invalidateFromDate, nil)
|
||||
|
||||
s.reallocateAfterRealization(c.Context(), expenseID, expense.SupplierId)
|
||||
|
||||
return responseDTO, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,9 @@ func (PaymentModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *
|
||||
panic(fmt.Sprintf("failed to register payment approval workflow: %v", err))
|
||||
}
|
||||
|
||||
paymentService := sPayment.NewPaymentService(paymentRepo, approvalService, validate)
|
||||
fifoPaymentService := commonSvc.NewFifoPaymentService(db, nil)
|
||||
|
||||
paymentService := sPayment.NewPaymentService(paymentRepo, approvalService, fifoPaymentService, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
PaymentRoutes(router, userService, paymentService)
|
||||
|
||||
@@ -32,12 +32,14 @@ type paymentService struct {
|
||||
Validate *validator.Validate
|
||||
Repository repository.PaymentRepository
|
||||
ApprovalSvc commonSvc.ApprovalService
|
||||
FifoPaymentSvc commonSvc.FifoPaymentService
|
||||
approvalWorkflow approvalutils.ApprovalWorkflowKey
|
||||
}
|
||||
|
||||
func NewPaymentService(
|
||||
repo repository.PaymentRepository,
|
||||
approvalSvc commonSvc.ApprovalService,
|
||||
fifoPaymentSvc commonSvc.FifoPaymentService,
|
||||
validate *validator.Validate,
|
||||
) PaymentService {
|
||||
return &paymentService{
|
||||
@@ -45,6 +47,7 @@ func NewPaymentService(
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
ApprovalSvc: approvalSvc,
|
||||
FifoPaymentSvc: fifoPaymentSvc,
|
||||
approvalWorkflow: utils.ApprovalWorkflowPayment,
|
||||
}
|
||||
}
|
||||
@@ -159,6 +162,12 @@ func (s *paymentService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entit
|
||||
}
|
||||
}
|
||||
|
||||
if s.FifoPaymentSvc != nil {
|
||||
if err := s.FifoPaymentSvc.ReallocateForParty(c.Context(), dbTransaction, createBody.PartyType, createBody.PartyId); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -251,7 +260,46 @@ func (s paymentService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint)
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
if err := s.Repository.PatchOne(c.Context(), id, updateBody, nil); err != nil {
|
||||
// Snapshot party lama untuk reallocate kalau party baru berbeda.
|
||||
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 for update: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
oldPartyType := existing.PartyType
|
||||
oldPartyID := existing.PartyId
|
||||
|
||||
newPartyType := oldPartyType
|
||||
newPartyID := oldPartyID
|
||||
if v, ok := updateBody["party_type"].(string); ok {
|
||||
newPartyType = v
|
||||
}
|
||||
if v, ok := updateBody["party_id"].(uint); ok {
|
||||
newPartyID = v
|
||||
}
|
||||
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
paymentRepoTx := repository.NewPaymentRepository(tx)
|
||||
if err := paymentRepoTx.PatchOne(c.Context(), id, updateBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.FifoPaymentSvc != nil {
|
||||
if err := s.FifoPaymentSvc.ReallocateForParty(c.Context(), tx, newPartyType, newPartyID); err != nil {
|
||||
return err
|
||||
}
|
||||
if oldPartyType != newPartyType || oldPartyID != newPartyID {
|
||||
if err := s.FifoPaymentSvc.ReallocateForParty(c.Context(), tx, oldPartyType, oldPartyID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Payment not found")
|
||||
}
|
||||
|
||||
@@ -35,7 +35,8 @@ func (TransactionModule) RegisterRoutes(router fiber.Router, db *gorm.DB, valida
|
||||
panic(fmt.Sprintf("failed to register injection approval workflow: %v", err))
|
||||
}
|
||||
|
||||
transactionService := sTransaction.NewTransactionService(transactionRepo, approvalService, validate)
|
||||
fifoPaymentService := commonSvc.NewFifoPaymentService(db, utils.Log)
|
||||
transactionService := sTransaction.NewTransactionService(transactionRepo, approvalService, fifoPaymentService, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
TransactionRoutes(router, userService, transactionService)
|
||||
|
||||
@@ -30,19 +30,22 @@ type transactionService struct {
|
||||
Validate *validator.Validate
|
||||
Repository repository.TransactionRepository
|
||||
ApprovalSvc commonSvc.ApprovalService
|
||||
FifoPaymentSvc commonSvc.FifoPaymentService
|
||||
approvalWorkflows map[string]approvalutils.ApprovalWorkflowKey
|
||||
}
|
||||
|
||||
func NewTransactionService(
|
||||
repo repository.TransactionRepository,
|
||||
approvalSvc commonSvc.ApprovalService,
|
||||
fifoPaymentSvc commonSvc.FifoPaymentService,
|
||||
validate *validator.Validate,
|
||||
) TransactionService {
|
||||
return &transactionService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
ApprovalSvc: approvalSvc,
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
ApprovalSvc: approvalSvc,
|
||||
FifoPaymentSvc: fifoPaymentSvc,
|
||||
approvalWorkflows: map[string]approvalutils.ApprovalWorkflowKey{
|
||||
string(utils.TransactionTypeSaldoAwal): utils.ApprovalWorkflowInitial,
|
||||
string(utils.TransactionTypeInjection): utils.ApprovalWorkflowInjection,
|
||||
@@ -182,6 +185,19 @@ func (s transactionService) GetOne(c *fiber.Ctx, id uint) (*entity.Payment, erro
|
||||
}
|
||||
|
||||
func (s transactionService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
// Snapshot party SEBELUM delete supaya bisa re-FIFO setelah trigger DB
|
||||
// (`trg_soft_delete_fk_payments`) CASCADE hard-DELETE allocations.
|
||||
existing, err := s.Repository.GetByID(c.Context(), id, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Transaction not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to load transaction before delete: %+v", err)
|
||||
return err
|
||||
}
|
||||
partyType := existing.PartyType
|
||||
partyID := existing.PartyId
|
||||
|
||||
if err := s.Repository.DeleteOne(c.Context(), id); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Transaction not found")
|
||||
@@ -189,6 +205,14 @@ func (s transactionService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
s.Log.Errorf("Failed to delete transaction: %+v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Re-FIFO setelah delete agar payment lain yang masih punya unallocated nominal
|
||||
// otomatis reflow ke MDP/purchase_item/expense_realization yang kekurangan paid.
|
||||
if s.FifoPaymentSvc != nil && partyID > 0 {
|
||||
if err := s.FifoPaymentSvc.ReallocateForParty(c.Context(), nil, partyType, partyID); err != nil {
|
||||
s.Log.Warnf("Failed to reallocate payments after delete (party=%s id=%d): %+v", partyType, partyID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,7 @@ func (TransferModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
expenseRealizationRepo,
|
||||
projectFlockKandangRepo,
|
||||
documentSvc,
|
||||
commonSvc.NewFifoPaymentService(db, utils.Log),
|
||||
validate,
|
||||
)
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ func (MarketingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
stockLogRepo := rShared.NewStockLogRepository(db)
|
||||
|
||||
fifoStockV2Service := commonSvc.NewFifoStockV2Service(db, utils.Log)
|
||||
fifoPaymentService := commonSvc.NewFifoPaymentService(db, utils.Log)
|
||||
|
||||
approvalRepo := commonRepo.NewApprovalRepository(db)
|
||||
approvalSvc := commonSvc.NewApprovalService(approvalRepo)
|
||||
@@ -47,7 +48,7 @@ func (MarketingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
projectFlockKandangRepo := rProjectFlockKandang.NewProjectFlockKandangRepository(db)
|
||||
|
||||
salesOrdersService := service.NewSalesOrdersService(marketingRepo, customerRepo, productWarehouseRepo, userRepo, approvalSvc, fifoStockV2Service, warehouseRepo, projectFlockKandangRepo, validate)
|
||||
deliveryOrdersService := service.NewDeliveryOrdersService(marketingRepo, marketingProductRepo, marketingDeliveryProductRepo, stockLogRepo, productWarehouseRepo, projectFlockPopulationRepo, approvalSvc, fifoStockV2Service, validate)
|
||||
deliveryOrdersService := service.NewDeliveryOrdersService(marketingRepo, marketingProductRepo, marketingDeliveryProductRepo, stockLogRepo, productWarehouseRepo, projectFlockPopulationRepo, approvalSvc, fifoStockV2Service, fifoPaymentService, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
RegisterRoutes(router, userService, salesOrdersService, deliveryOrdersService)
|
||||
|
||||
@@ -48,6 +48,7 @@ type deliveryOrdersService struct {
|
||||
ProjectFlockPopulationRepo rProjectFlock.ProjectFlockPopulationRepository
|
||||
ApprovalSvc commonSvc.ApprovalService
|
||||
FifoStockV2Svc commonSvc.FifoStockV2Service
|
||||
FifoPaymentSvc commonSvc.FifoPaymentService
|
||||
}
|
||||
|
||||
func NewDeliveryOrdersService(
|
||||
@@ -59,6 +60,7 @@ func NewDeliveryOrdersService(
|
||||
projectFlockPopulationRepo rProjectFlock.ProjectFlockPopulationRepository,
|
||||
approvalSvc commonSvc.ApprovalService,
|
||||
fifoStockV2Svc commonSvc.FifoStockV2Service,
|
||||
fifoPaymentSvc commonSvc.FifoPaymentService,
|
||||
validate *validator.Validate,
|
||||
) DeliveryOrdersService {
|
||||
return &deliveryOrdersService{
|
||||
@@ -71,6 +73,22 @@ func NewDeliveryOrdersService(
|
||||
ProjectFlockPopulationRepo: projectFlockPopulationRepo,
|
||||
ApprovalSvc: approvalSvc,
|
||||
FifoStockV2Svc: fifoStockV2Svc,
|
||||
FifoPaymentSvc: fifoPaymentSvc,
|
||||
}
|
||||
}
|
||||
|
||||
// reallocateAfterDelivery refresh marketing.grand_total + reallocate FIFO untuk customer.
|
||||
func (s *deliveryOrdersService) reallocateAfterDelivery(ctx context.Context, marketingID uint, customerID uint) {
|
||||
if s.FifoPaymentSvc == nil {
|
||||
return
|
||||
}
|
||||
if err := s.FifoPaymentSvc.RecomputeGrandTotal(ctx, nil, commonSvc.ParentKindMarketing, marketingID); err != nil {
|
||||
utils.Log.Warnf("Failed to recompute grand_total for marketing %d: %+v", marketingID, err)
|
||||
}
|
||||
if customerID > 0 {
|
||||
if err := s.FifoPaymentSvc.ReallocateForParty(ctx, nil, string(utils.PaymentPartyCustomer), customerID); err != nil {
|
||||
utils.Log.Warnf("Failed to reallocate payments for customer %d: %+v", customerID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -418,6 +436,7 @@ func (s *deliveryOrdersService) CreateOne(c *fiber.Ctx, req *validation.Delivery
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Delivery order already exists for this marketing")
|
||||
}
|
||||
|
||||
var capturedCustomerID uint
|
||||
err = s.MarketingRepo.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
|
||||
marketingProductRepositoryTx := marketingRepo.NewMarketingProductRepository(dbTransaction)
|
||||
marketingDeliveryProductRepositoryTx := marketingRepo.NewMarketingDeliveryProductRepository(dbTransaction)
|
||||
@@ -428,6 +447,7 @@ func (s *deliveryOrdersService) CreateOne(c *fiber.Ctx, req *validation.Delivery
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch marketing")
|
||||
}
|
||||
capturedCustomerID = marketing.CustomerId
|
||||
|
||||
allMarketingProducts, err := marketingProductRepositoryTx.GetByMarketingID(c.Context(), req.MarketingId)
|
||||
if err != nil {
|
||||
@@ -519,6 +539,8 @@ func (s *deliveryOrdersService) CreateOne(c *fiber.Ctx, req *validation.Delivery
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to create delivery order")
|
||||
}
|
||||
|
||||
s.reallocateAfterDelivery(c.Context(), req.MarketingId, capturedCustomerID)
|
||||
|
||||
return s.getMarketingWithDeliveries(c, req.MarketingId)
|
||||
}
|
||||
|
||||
@@ -547,6 +569,7 @@ func (s deliveryOrdersService) UpdateOne(c *fiber.Ctx, req *validation.DeliveryO
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check approval status")
|
||||
}
|
||||
|
||||
var capturedCustomerID uint
|
||||
err = s.MarketingRepo.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
|
||||
marketingProductRepositoryTx := marketingRepo.NewMarketingProductRepository(dbTransaction)
|
||||
marketingDeliveryProductRepositoryTx := marketingRepo.NewMarketingDeliveryProductRepository(dbTransaction)
|
||||
@@ -557,6 +580,7 @@ func (s deliveryOrdersService) UpdateOne(c *fiber.Ctx, req *validation.DeliveryO
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch marketing")
|
||||
}
|
||||
capturedCustomerID = marketing.CustomerId
|
||||
|
||||
allMarketingProducts, err := marketingProductRepositoryTx.GetByMarketingID(c.Context(), id)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -662,6 +686,8 @@ func (s deliveryOrdersService) UpdateOne(c *fiber.Ctx, req *validation.DeliveryO
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to update delivery order")
|
||||
}
|
||||
|
||||
s.reallocateAfterDelivery(c.Context(), id, capturedCustomerID)
|
||||
|
||||
return s.getMarketingWithDeliveries(c, id)
|
||||
}
|
||||
|
||||
|
||||
@@ -61,6 +61,7 @@ func (PurchaseModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
expenseRealizationRepo,
|
||||
projectFlockKandangRepository,
|
||||
documentSvc,
|
||||
commonSvc.NewFifoPaymentService(db, utils.Log),
|
||||
validate,
|
||||
)
|
||||
expenseBridge := service.NewExpenseBridge(
|
||||
@@ -72,6 +73,7 @@ func (PurchaseModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
)
|
||||
|
||||
fifoStockV2Service := commonSvc.NewFifoStockV2Service(db, utils.Log)
|
||||
fifoPaymentService := commonSvc.NewFifoPaymentService(db, utils.Log)
|
||||
|
||||
purchaseService := service.NewPurchaseService(
|
||||
validate,
|
||||
@@ -84,6 +86,7 @@ func (PurchaseModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
approvalService,
|
||||
expenseBridge,
|
||||
fifoStockV2Service,
|
||||
fifoPaymentService,
|
||||
documentSvc,
|
||||
)
|
||||
|
||||
|
||||
@@ -64,6 +64,7 @@ type purchaseService struct {
|
||||
ApprovalSvc commonSvc.ApprovalService
|
||||
ExpenseBridge PurchaseExpenseBridge
|
||||
FifoStockV2Svc commonSvc.FifoStockV2Service
|
||||
FifoPaymentSvc commonSvc.FifoPaymentService
|
||||
DocumentSvc commonSvc.DocumentService
|
||||
approvalWorkflow approvalutils.ApprovalWorkflowKey
|
||||
}
|
||||
@@ -91,6 +92,7 @@ func NewPurchaseService(
|
||||
approvalSvc commonSvc.ApprovalService,
|
||||
expenseBridge PurchaseExpenseBridge,
|
||||
fifoStockV2Svc commonSvc.FifoStockV2Service,
|
||||
fifoPaymentSvc commonSvc.FifoPaymentService,
|
||||
documentSvc commonSvc.DocumentService,
|
||||
) PurchaseService {
|
||||
return &purchaseService{
|
||||
@@ -105,6 +107,7 @@ func NewPurchaseService(
|
||||
ApprovalSvc: approvalSvc,
|
||||
ExpenseBridge: expenseBridge,
|
||||
FifoStockV2Svc: fifoStockV2Svc,
|
||||
FifoPaymentSvc: fifoPaymentSvc,
|
||||
DocumentSvc: documentSvc,
|
||||
approvalWorkflow: utils.ApprovalWorkflowPurchase,
|
||||
}
|
||||
@@ -1406,6 +1409,16 @@ func (s *purchaseService) ReceiveProducts(c *fiber.Ctx, id uint, req *validation
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Refresh purchase.grand_total + reallocate payment FIFO untuk supplier (new debt baru emerges).
|
||||
if s.FifoPaymentSvc != nil && receivingAction == entity.ApprovalActionApproved {
|
||||
if err := s.FifoPaymentSvc.RecomputeGrandTotal(c.Context(), nil, commonSvc.ParentKindPurchase, purchase.Id); err != nil {
|
||||
s.Log.Warnf("Failed to recompute grand_total for purchase %d: %+v", purchase.Id, err)
|
||||
}
|
||||
if err := s.FifoPaymentSvc.ReallocateForParty(c.Context(), nil, string(utils.PaymentPartySupplier), uint(purchase.SupplierId)); err != nil {
|
||||
s.Log.Warnf("Failed to reallocate payments for supplier %d: %+v", purchase.SupplierId, err)
|
||||
}
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -831,37 +831,28 @@ func (s *repportService) GetMarketing(c *fiber.Ctx, params *validation.Marketing
|
||||
customerGroups[customerID] = append(customerGroups[customerID], dp)
|
||||
}
|
||||
|
||||
// Aging untuk setiap MDP berdasarkan payment_allocations: LUNAS pakai last_payment_date,
|
||||
// else pakai today.
|
||||
agingMap := make(map[int]int)
|
||||
for customerID := range customerGroups {
|
||||
transactions, err := s.CustomerPaymentRepo.GetCustomerPaymentTransactions(c.Context(), &customerID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
initialBalance, err := s.CustomerPaymentRepo.GetInitialBalanceByCustomer(c.Context(), customerID)
|
||||
if err != nil {
|
||||
initialBalance = 0
|
||||
}
|
||||
|
||||
runningBalance := initialBalance
|
||||
for i, tx := range transactions {
|
||||
if tx.TransactionType == "SALES" {
|
||||
previousBalance := runningBalance
|
||||
runningBalance -= tx.TotalPrice
|
||||
currentBalance := runningBalance
|
||||
|
||||
_, paymentDate := s.determineSalesStatusAndPaymentDate(transactions, i, previousBalance, currentBalance)
|
||||
|
||||
if paymentDate != nil {
|
||||
agingDays := int(paymentDate.Sub(tx.TransDate).Hours() / 24)
|
||||
agingMap[int(tx.TransactionID)] = agingDays
|
||||
} else {
|
||||
agingDays := int(time.Since(tx.TransDate).Hours() / 24)
|
||||
agingMap[int(tx.TransactionID)] = agingDays
|
||||
}
|
||||
} else if tx.TransactionType == "PAYMENT" {
|
||||
runningBalance += tx.PaymentAmount
|
||||
allMdpIDsForAging := make([]uint, 0)
|
||||
for _, dp := range deliveryProducts {
|
||||
allMdpIDsForAging = append(allMdpIDsForAging, dp.Id)
|
||||
}
|
||||
mdpAllocSummaryForMarketing, err := s.fetchMdpAllocationSummary(c.Context(), allMdpIDsForAging)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
for _, dp := range deliveryProducts {
|
||||
summary := mdpAllocSummaryForMarketing[dp.Id]
|
||||
soDate := dp.MarketingProduct.Marketing.SoDate
|
||||
if customerPaymentStatusFromAllocation(dp.TotalPrice, summary.PaidAmount) == "LUNAS" && !summary.LastPaymentDate.IsZero() {
|
||||
days := int(summary.LastPaymentDate.Sub(soDate).Hours() / 24)
|
||||
if days < 0 {
|
||||
days = 0
|
||||
}
|
||||
agingMap[int(dp.Id)] = days
|
||||
} else {
|
||||
agingMap[int(dp.Id)] = int(time.Since(soDate).Hours() / 24)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1250,28 +1241,39 @@ func (s *repportService) processCustomerPayment(ctx context.Context, customerID
|
||||
return dto.CustomerPaymentReportItem{}, err
|
||||
}
|
||||
|
||||
// Batch fetch payment allocation summaries untuk semua SALES rows (per MDP).
|
||||
mdpIDs := make([]uint, 0)
|
||||
for _, tx := range transactions {
|
||||
if tx.TransactionType == "SALES" && tx.TransactionID > 0 {
|
||||
mdpIDs = append(mdpIDs, uint(tx.TransactionID))
|
||||
}
|
||||
}
|
||||
mdpAllocSummary, err := s.fetchMdpAllocationSummary(ctx, mdpIDs)
|
||||
if err != nil {
|
||||
return dto.CustomerPaymentReportItem{}, err
|
||||
}
|
||||
|
||||
rows := make([]dto.CustomerPaymentReportRow, 0, len(transactions))
|
||||
runningBalance := initialBalance
|
||||
|
||||
for i, tx := range transactions {
|
||||
|
||||
previousBalance := runningBalance
|
||||
for _, tx := range transactions {
|
||||
|
||||
row := dto.ToCustomerPaymentReportRow(tx)
|
||||
|
||||
if tx.TransactionType == "SALES" {
|
||||
runningBalance -= tx.TotalPrice
|
||||
status, paymentDate := s.determineSalesStatusAndPaymentDate(transactions, i, previousBalance, runningBalance)
|
||||
row.Status = status
|
||||
summary := mdpAllocSummary[uint(tx.TransactionID)]
|
||||
row.Status = customerPaymentStatusFromAllocation(tx.TotalPrice, summary.PaidAmount)
|
||||
|
||||
if status == "LUNAS" {
|
||||
if paymentDate != nil {
|
||||
days := int(paymentDate.Sub(tx.TransDate).Hours() / 24)
|
||||
row.AgingDay = &days
|
||||
} else {
|
||||
days := 0
|
||||
row.AgingDay = &days
|
||||
if row.Status == "LUNAS" && !summary.LastPaymentDate.IsZero() {
|
||||
days := int(summary.LastPaymentDate.Sub(tx.TransDate).Hours() / 24)
|
||||
if days < 0 {
|
||||
days = 0
|
||||
}
|
||||
row.AgingDay = &days
|
||||
} else if row.Status == "LUNAS" {
|
||||
zero := 0
|
||||
row.AgingDay = &zero
|
||||
} else {
|
||||
days := int(time.Since(tx.TransDate).Hours() / 24)
|
||||
row.AgingDay = &days
|
||||
@@ -1343,91 +1345,19 @@ func (s *repportService) processCustomerPayment(ctx context.Context, customerID
|
||||
return dto.ToCustomerPaymentReportItem(*customer, initialBalance, rows, summary), nil
|
||||
}
|
||||
|
||||
func (s *repportService) determineSalesStatusAndPaymentDate(transactions []repportRepo.CustomerPaymentTransaction, currentIndex int, previousBalance, currentBalance float64) (string, *time.Time) {
|
||||
currentSales := transactions[currentIndex]
|
||||
|
||||
if previousBalance >= currentSales.TotalPrice {
|
||||
type paymentAllocation struct {
|
||||
date time.Time
|
||||
amount float64
|
||||
consumed float64
|
||||
}
|
||||
allocations := []paymentAllocation{}
|
||||
runningBalance := 0.0
|
||||
|
||||
for i := 0; i < currentIndex; i++ {
|
||||
if transactions[i].TransactionType == "PAYMENT" {
|
||||
allocations = append(allocations, paymentAllocation{
|
||||
date: transactions[i].TransDate,
|
||||
amount: transactions[i].PaymentAmount,
|
||||
consumed: 0,
|
||||
})
|
||||
runningBalance += transactions[i].PaymentAmount
|
||||
} else if transactions[i].TransactionType == "SALES" {
|
||||
salesAmount := transactions[i].TotalPrice
|
||||
remainingToConsume := salesAmount
|
||||
|
||||
for j := range allocations {
|
||||
if remainingToConsume <= 0 {
|
||||
break
|
||||
}
|
||||
available := allocations[j].amount - allocations[j].consumed
|
||||
if available > 0 {
|
||||
consume := available
|
||||
if consume > remainingToConsume {
|
||||
consume = remainingToConsume
|
||||
}
|
||||
allocations[j].consumed += consume
|
||||
remainingToConsume -= consume
|
||||
}
|
||||
}
|
||||
runningBalance -= salesAmount
|
||||
}
|
||||
}
|
||||
|
||||
amountNeeded := currentSales.TotalPrice
|
||||
for _, alloc := range allocations {
|
||||
available := alloc.amount - alloc.consumed
|
||||
if available > 0 {
|
||||
if amountNeeded <= available {
|
||||
return "LUNAS", &alloc.date
|
||||
} else {
|
||||
amountNeeded -= available
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(allocations) > 0 {
|
||||
return "LUNAS", &allocations[0].date
|
||||
}
|
||||
return "LUNAS", nil
|
||||
// customerPaymentStatusFromAllocation menentukan status per-MDP berdasarkan
|
||||
// SUM(payment_allocations.amount) vs MDP total_price.
|
||||
func customerPaymentStatusFromAllocation(totalPrice, paidAmount float64) string {
|
||||
if totalPrice <= fifoAllocationEpsilon {
|
||||
return "LUNAS"
|
||||
}
|
||||
|
||||
hasPartialPaymentFromBalance := previousBalance > 0 && previousBalance < currentSales.TotalPrice
|
||||
|
||||
futureBalance := currentBalance
|
||||
hasPayment := false
|
||||
var paymentDateThatMadeItLunas *time.Time
|
||||
|
||||
for i := currentIndex + 1; i < len(transactions); i++ {
|
||||
if transactions[i].TransactionType == "PAYMENT" {
|
||||
futureBalance += transactions[i].PaymentAmount
|
||||
hasPayment = true
|
||||
|
||||
if futureBalance >= 0 {
|
||||
paymentDateThatMadeItLunas = &transactions[i].TransDate
|
||||
return "LUNAS", paymentDateThatMadeItLunas
|
||||
}
|
||||
} else if transactions[i].TransactionType == "SALES" {
|
||||
futureBalance -= transactions[i].TotalPrice
|
||||
}
|
||||
if paidAmount+fifoAllocationEpsilon >= totalPrice {
|
||||
return "LUNAS"
|
||||
}
|
||||
|
||||
if hasPayment || hasPartialPaymentFromBalance {
|
||||
return "DIBAYAR SEBAGIAN", nil
|
||||
if paidAmount > fifoAllocationEpsilon {
|
||||
return "DIBAYAR SEBAGIAN"
|
||||
}
|
||||
|
||||
return "BELUM LUNAS", nil
|
||||
return "BELUM LUNAS"
|
||||
}
|
||||
|
||||
func mapRecordingToProductionResultDTO(record entity.Recording) dto.ProductionResultDTO {
|
||||
@@ -1951,15 +1881,34 @@ func (s *repportService) GetDebtSupplier(c *fiber.Ctx, params *validation.DebtSu
|
||||
DeltaBalance float64
|
||||
CountTotals bool
|
||||
}
|
||||
type debtSupplierAllocation struct {
|
||||
RowIndex int
|
||||
SortTime time.Time
|
||||
Amount float64
|
||||
CalcAging func(endDate time.Time) int
|
||||
|
||||
// Batch fetch payment allocation summaries (per purchase + per expense) untuk semua supplier.
|
||||
// FIFO matching dilakukan saat payment di-create/update; report tinggal baca dari DB.
|
||||
allPurchaseIDs := make([]uint, 0)
|
||||
allExpenseIDs := make([]uint64, 0)
|
||||
for _, sid := range supplierIDs {
|
||||
for _, p := range purchasesBySupplier[sid] {
|
||||
allPurchaseIDs = append(allPurchaseIDs, p.Id)
|
||||
}
|
||||
for _, e := range expensesBySupplier[sid] {
|
||||
allExpenseIDs = append(allExpenseIDs, e.Id)
|
||||
}
|
||||
}
|
||||
type paymentAllocation struct {
|
||||
Date time.Time
|
||||
Amount float64
|
||||
purchaseAllocSummary, err := s.fetchPurchaseAllocationSummary(c.Context(), allPurchaseIDs)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
expenseAllocSummary, err := s.fetchExpenseAllocationSummary(c.Context(), allExpenseIDs)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// rowRef tracks which combinedRows index belongs to which purchase/expense untuk update status di-akhir.
|
||||
type rowRef struct {
|
||||
Index int
|
||||
Kind string // "PURCHASE" / "EXPENSE"
|
||||
Purchase entity.Purchase
|
||||
Expense entity.Expense
|
||||
}
|
||||
|
||||
for _, supplierID := range supplierIDs {
|
||||
@@ -1974,7 +1923,7 @@ func (s *repportService) GetDebtSupplier(c *fiber.Ctx, params *validation.DebtSu
|
||||
total := dto.DebtSupplierTotalDTO{}
|
||||
|
||||
combinedRows := make([]debtSupplierRowItem, 0, len(items)+len(paymentItems))
|
||||
purchaseAllocations := make([]debtSupplierAllocation, 0, len(items))
|
||||
rowRefs := make([]rowRef, 0, len(items)+len(expensesBySupplier[supplierID]))
|
||||
for _, purchase := range items {
|
||||
row := buildDebtSupplierRow(purchase, now, location)
|
||||
sortTime := resolveDebtSupplierSortTime(purchase, params.FilterBy, location)
|
||||
@@ -1986,13 +1935,7 @@ func (s *repportService) GetDebtSupplier(c *fiber.Ctx, params *validation.DebtSu
|
||||
DeltaBalance: -row.TotalPrice,
|
||||
CountTotals: true,
|
||||
})
|
||||
capturedPurchase := purchase
|
||||
purchaseAllocations = append(purchaseAllocations, debtSupplierAllocation{
|
||||
RowIndex: rowIndex,
|
||||
SortTime: sortTime,
|
||||
Amount: row.TotalPrice,
|
||||
CalcAging: func(endDate time.Time) int { return calculateDebtSupplierAging(capturedPurchase, endDate, location) },
|
||||
})
|
||||
rowRefs = append(rowRefs, rowRef{Index: rowIndex, Kind: "PURCHASE", Purchase: purchase})
|
||||
}
|
||||
|
||||
for _, exp := range expensesBySupplier[supplierID] {
|
||||
@@ -2006,25 +1949,7 @@ func (s *repportService) GetDebtSupplier(c *fiber.Ctx, params *validation.DebtSu
|
||||
DeltaBalance: -row.TotalPrice,
|
||||
CountTotals: true,
|
||||
})
|
||||
capturedExp := exp
|
||||
purchaseAllocations = append(purchaseAllocations, debtSupplierAllocation{
|
||||
RowIndex: rowIndex,
|
||||
SortTime: sortTime,
|
||||
Amount: row.TotalPrice,
|
||||
CalcAging: func(endDate time.Time) int { return calculateExpenseAging(capturedExp, endDate, location) },
|
||||
})
|
||||
}
|
||||
|
||||
paymentAllocations := make([]paymentAllocation, 0, len(paymentItems)+1)
|
||||
initialAllocation := initialBalanceTotals[supplierID] + initialPaymentTotals[supplierID] - initialPurchaseTotals[supplierID]
|
||||
paymentCarry := 0.0
|
||||
if initialAllocation > 0 && len(purchaseAllocations) > 0 {
|
||||
paymentAllocations = append(paymentAllocations, paymentAllocation{
|
||||
Date: purchaseAllocations[0].SortTime,
|
||||
Amount: initialAllocation,
|
||||
})
|
||||
} else if initialAllocation < 0 {
|
||||
paymentCarry = -initialAllocation
|
||||
rowRefs = append(rowRefs, rowRef{Index: rowIndex, Kind: "EXPENSE", Expense: exp})
|
||||
}
|
||||
|
||||
for _, payment := range paymentItems {
|
||||
@@ -2037,51 +1962,29 @@ func (s *repportService) GetDebtSupplier(c *fiber.Ctx, params *validation.DebtSu
|
||||
DeltaBalance: payment.Nominal,
|
||||
CountTotals: false,
|
||||
})
|
||||
paymentAllocations = append(paymentAllocations, paymentAllocation{
|
||||
Date: sortTime,
|
||||
Amount: payment.Nominal,
|
||||
})
|
||||
}
|
||||
|
||||
if len(purchaseAllocations) > 0 && len(paymentAllocations) > 0 {
|
||||
sort.SliceStable(purchaseAllocations, func(i, j int) bool {
|
||||
return purchaseAllocations[i].SortTime.Before(purchaseAllocations[j].SortTime)
|
||||
})
|
||||
sort.SliceStable(paymentAllocations, func(i, j int) bool {
|
||||
return paymentAllocations[i].Date.Before(paymentAllocations[j].Date)
|
||||
})
|
||||
remaining := make([]float64, len(purchaseAllocations))
|
||||
for i := range purchaseAllocations {
|
||||
remaining[i] = purchaseAllocations[i].Amount
|
||||
// Determine Status & Aging dari payment_allocations DB.
|
||||
for _, ref := range rowRefs {
|
||||
rowTotal := combinedRows[ref.Index].Row.TotalPrice
|
||||
if rowTotal <= fifoAllocationEpsilon {
|
||||
continue
|
||||
}
|
||||
purchaseIndex := 0
|
||||
for _, pay := range paymentAllocations {
|
||||
amount := pay.Amount
|
||||
if amount <= 0 {
|
||||
continue
|
||||
}
|
||||
if paymentCarry > 0 {
|
||||
used := math.Min(amount, paymentCarry)
|
||||
paymentCarry -= used
|
||||
amount -= used
|
||||
}
|
||||
for amount > 0 && purchaseIndex < len(remaining) {
|
||||
if remaining[purchaseIndex] <= 0 {
|
||||
purchaseIndex++
|
||||
continue
|
||||
}
|
||||
used := math.Min(amount, remaining[purchaseIndex])
|
||||
remaining[purchaseIndex] -= used
|
||||
amount -= used
|
||||
if remaining[purchaseIndex] <= 0.000001 {
|
||||
allocation := purchaseAllocations[purchaseIndex]
|
||||
combinedRows[allocation.RowIndex].Row.Status = "Lunas"
|
||||
combinedRows[allocation.RowIndex].Row.Aging = allocation.CalcAging(pay.Date)
|
||||
purchaseIndex++
|
||||
}
|
||||
}
|
||||
if purchaseIndex >= len(remaining) {
|
||||
break
|
||||
var summary paymentAllocationSummary
|
||||
if ref.Kind == "PURCHASE" {
|
||||
summary = purchaseAllocSummary[ref.Purchase.Id]
|
||||
} else {
|
||||
summary = expenseAllocSummary[ref.Expense.Id]
|
||||
}
|
||||
if summary.PaidAmount+fifoAllocationEpsilon < rowTotal {
|
||||
continue
|
||||
}
|
||||
combinedRows[ref.Index].Row.Status = "Lunas"
|
||||
if !summary.LastPaymentDate.IsZero() {
|
||||
if ref.Kind == "PURCHASE" {
|
||||
combinedRows[ref.Index].Row.Aging = calculateDebtSupplierAging(ref.Purchase, summary.LastPaymentDate.In(location), location)
|
||||
} else {
|
||||
combinedRows[ref.Index].Row.Aging = calculateExpenseAging(ref.Expense, summary.LastPaymentDate.In(location), location)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2257,6 +2160,115 @@ func buildDebtSupplierPaymentRow(payment entity.Payment, loc *time.Location) dto
|
||||
}
|
||||
}
|
||||
|
||||
// fifoAllocationEpsilon untuk float comparison saat membandingkan paid vs total.
|
||||
const fifoAllocationEpsilon = 0.001
|
||||
|
||||
// paymentAllocationSummary aggregates per-document paid amount + latest payment date
|
||||
// from payment_allocations table, sebagai pengganti FIFO greedy in-memory.
|
||||
type paymentAllocationSummary struct {
|
||||
PaidAmount float64
|
||||
LastPaymentDate time.Time
|
||||
}
|
||||
|
||||
// fetchPurchaseAllocationSummary returns map[purchase_id]{paid_amount, last_payment_date}.
|
||||
// paid_amount = SUM(payment_allocations.amount) untuk semua items dalam purchase.
|
||||
// last_payment_date = MAX(payments.payment_date) untuk allocation tersebut.
|
||||
func (s *repportService) fetchPurchaseAllocationSummary(ctx context.Context, purchaseIDs []uint) (map[uint]paymentAllocationSummary, error) {
|
||||
out := make(map[uint]paymentAllocationSummary)
|
||||
if len(purchaseIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
type row struct {
|
||||
PurchaseID uint
|
||||
Total float64
|
||||
LastPayment *time.Time
|
||||
}
|
||||
var rows []row
|
||||
if err := s.db.WithContext(ctx).
|
||||
Table("payment_allocations pa").
|
||||
Joins("JOIN purchase_items pi ON pi.id = pa.purchase_item_id").
|
||||
Joins("JOIN payments p ON p.id = pa.payment_id").
|
||||
Select("pi.purchase_id AS purchase_id, SUM(pa.amount) AS total, MAX(p.payment_date) AS last_payment").
|
||||
Where("pi.purchase_id IN ?", purchaseIDs).
|
||||
Group("pi.purchase_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
summary := paymentAllocationSummary{PaidAmount: r.Total}
|
||||
if r.LastPayment != nil {
|
||||
summary.LastPaymentDate = *r.LastPayment
|
||||
}
|
||||
out[r.PurchaseID] = summary
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// fetchExpenseAllocationSummary returns map[expense_id]{paid_amount, last_payment_date}.
|
||||
// Allocation di expense_realization_id → JOIN expense_nonstocks → expenses.id.
|
||||
func (s *repportService) fetchExpenseAllocationSummary(ctx context.Context, expenseIDs []uint64) (map[uint64]paymentAllocationSummary, error) {
|
||||
out := make(map[uint64]paymentAllocationSummary)
|
||||
if len(expenseIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
type row struct {
|
||||
ExpenseID uint64
|
||||
Total float64
|
||||
LastPayment *time.Time
|
||||
}
|
||||
var rows []row
|
||||
if err := s.db.WithContext(ctx).
|
||||
Table("payment_allocations pa").
|
||||
Joins("JOIN expense_realizations er ON er.id = pa.expense_realization_id").
|
||||
Joins("JOIN expense_nonstocks en ON en.id = er.expense_nonstock_id").
|
||||
Joins("JOIN payments p ON p.id = pa.payment_id").
|
||||
Select("en.expense_id AS expense_id, SUM(pa.amount) AS total, MAX(p.payment_date) AS last_payment").
|
||||
Where("en.expense_id IN ?", expenseIDs).
|
||||
Group("en.expense_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
summary := paymentAllocationSummary{PaidAmount: r.Total}
|
||||
if r.LastPayment != nil {
|
||||
summary.LastPaymentDate = *r.LastPayment
|
||||
}
|
||||
out[r.ExpenseID] = summary
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// fetchMdpAllocationSummary returns map[mdp_id]{paid_amount, last_payment_date}.
|
||||
func (s *repportService) fetchMdpAllocationSummary(ctx context.Context, mdpIDs []uint) (map[uint]paymentAllocationSummary, error) {
|
||||
out := make(map[uint]paymentAllocationSummary)
|
||||
if len(mdpIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
type row struct {
|
||||
MdpID uint
|
||||
Total float64
|
||||
LastPayment *time.Time
|
||||
}
|
||||
var rows []row
|
||||
if err := s.db.WithContext(ctx).
|
||||
Table("payment_allocations pa").
|
||||
Joins("JOIN payments p ON p.id = pa.payment_id").
|
||||
Select("pa.marketing_delivery_product_id AS mdp_id, SUM(pa.amount) AS total, MAX(p.payment_date) AS last_payment").
|
||||
Where("pa.marketing_delivery_product_id IN ?", mdpIDs).
|
||||
Group("pa.marketing_delivery_product_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
summary := paymentAllocationSummary{PaidAmount: r.Total}
|
||||
if r.LastPayment != nil {
|
||||
summary.LastPaymentDate = *r.LastPayment
|
||||
}
|
||||
out[r.MdpID] = summary
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func resolveDebtSupplierSortTime(purchase entity.Purchase, filterBy string, loc *time.Location) time.Time {
|
||||
if strings.EqualFold(strings.TrimSpace(filterBy), "po_date") {
|
||||
if purchase.PoDate != nil && !purchase.PoDate.IsZero() {
|
||||
@@ -2360,10 +2372,10 @@ func buildDebtSupplierExpenseRow(exp entity.Expense, warehouses []entity.Warehou
|
||||
aging = int(endDay.Sub(startDay).Hours() / 24)
|
||||
}
|
||||
|
||||
totalPrice := 0.0
|
||||
for _, ns := range exp.Nonstocks {
|
||||
totalPrice += ns.Qty * ns.Price
|
||||
}
|
||||
// TotalPrice pakai expense.GrandTotal (= SUM realisasi) supaya konsisten dengan
|
||||
// FIFO allocation yang juga pakai realisasi. Hindari pakai SUM nonstock pengajuan
|
||||
// karena bisa beda nilai dari realisasi → mismatch dengan paid_amount → status salah.
|
||||
totalPrice := exp.GrandTotal
|
||||
|
||||
var area *areaDTO.AreaRelationDTO
|
||||
if exp.Location != nil && exp.Location.Area.Id != 0 {
|
||||
|
||||
Reference in New Issue
Block a user