Update payment
This commit is contained in:
@@ -19,6 +19,7 @@ type InventoryMovementRepository interface {
|
||||
GetByPaymentID(ctx context.Context, paymentID uuid.UUID) ([]*entities.InventoryMovement, error)
|
||||
Count(ctx context.Context, filters map[string]interface{}) (int64, error)
|
||||
CreateWithTransaction(tx *gorm.DB, movement *entities.InventoryMovement) error
|
||||
CreateInBatches(ctx context.Context, movements []*entities.InventoryMovement, batchSize int) error
|
||||
}
|
||||
|
||||
type InventoryMovementRepositoryImpl struct {
|
||||
@@ -39,6 +40,13 @@ func (r *InventoryMovementRepositoryImpl) CreateWithTransaction(tx *gorm.DB, mov
|
||||
return tx.Create(movement).Error
|
||||
}
|
||||
|
||||
func (r *InventoryMovementRepositoryImpl) CreateInBatches(ctx context.Context, movements []*entities.InventoryMovement, batchSize int) error {
|
||||
if len(movements) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).CreateInBatches(movements, batchSize).Error
|
||||
}
|
||||
|
||||
func (r *InventoryMovementRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.InventoryMovement, error) {
|
||||
var movement entities.InventoryMovement
|
||||
err := r.db.WithContext(ctx).First(&movement, "id = ?", id).Error
|
||||
|
||||
@@ -28,6 +28,7 @@ type InventoryRepository interface {
|
||||
SetQuantity(ctx context.Context, productID, outletID uuid.UUID, quantity int) (*entities.Inventory, error)
|
||||
UpdateReorderLevel(ctx context.Context, id uuid.UUID, reorderLevel int) error
|
||||
BulkCreate(ctx context.Context, inventoryItems []*entities.Inventory) error
|
||||
BulkUpdate(ctx context.Context, inventoryItems []*entities.Inventory) error
|
||||
BulkAdjustQuantity(ctx context.Context, adjustments map[uuid.UUID]int, outletID uuid.UUID) error
|
||||
GetTotalValueByOutlet(ctx context.Context, outletID uuid.UUID) (float64, error)
|
||||
}
|
||||
@@ -276,6 +277,22 @@ func (r *InventoryRepositoryImpl) BulkCreate(ctx context.Context, inventoryItems
|
||||
return r.db.WithContext(ctx).CreateInBatches(inventoryItems, 100).Error
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) BulkUpdate(ctx context.Context, inventoryItems []*entities.Inventory) error {
|
||||
if len(inventoryItems) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Use GORM's transaction for bulk updates
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for _, inventory := range inventoryItems {
|
||||
if err := tx.Save(inventory).Error; err != nil {
|
||||
return fmt.Errorf("failed to update inventory for product %s: %w", inventory.ProductID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) BulkAdjustQuantity(ctx context.Context, adjustments map[uuid.UUID]int, outletID uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for productID, delta := range adjustments {
|
||||
|
||||
@@ -2,12 +2,9 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
@@ -95,207 +92,3 @@ func (r *PaymentRepositoryImpl) GetTotalPaidByOrderID(ctx context.Context, order
|
||||
Scan(&total).Error
|
||||
return total, err
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) CreatePaymentWithInventoryMovement(ctx context.Context, req *models.CreatePaymentRequest, order *entities.Order, totalPaid float64) (*entities.Payment, error) {
|
||||
var payment *entities.Payment
|
||||
var orderJustCompleted bool
|
||||
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
payment = &entities.Payment{
|
||||
OrderID: req.OrderID,
|
||||
PaymentMethodID: req.PaymentMethodID,
|
||||
Amount: req.Amount,
|
||||
Status: entities.PaymentTransactionStatusCompleted,
|
||||
TransactionID: req.TransactionID,
|
||||
SplitNumber: req.SplitNumber,
|
||||
SplitTotal: req.SplitTotal,
|
||||
SplitDescription: req.SplitDescription,
|
||||
Metadata: entities.Metadata(req.Metadata),
|
||||
}
|
||||
|
||||
if err := tx.Create(payment).Error; err != nil {
|
||||
return fmt.Errorf("failed to create payment: %w", err)
|
||||
}
|
||||
|
||||
newTotalPaid := totalPaid + req.Amount
|
||||
if newTotalPaid >= order.TotalAmount {
|
||||
if order.PaymentStatus != entities.PaymentStatusCompleted {
|
||||
orderJustCompleted = true
|
||||
}
|
||||
if err := tx.Model(&entities.Order{}).Where("id = ?", req.OrderID).Update("status", entities.OrderStatusCompleted).Error; err != nil {
|
||||
return fmt.Errorf("failed to update order status: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if orderJustCompleted {
|
||||
orderItems, err := r.getOrderItemsWithTransaction(tx, req.OrderID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get order items for inventory adjustment: %w", err)
|
||||
}
|
||||
|
||||
for _, item := range orderItems {
|
||||
updatedInventory, err := r.adjustInventoryWithTransaction(tx, item.ProductID, order.OutletID, -item.Quantity)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to adjust inventory for product %s: %w", item.ProductID, err)
|
||||
}
|
||||
|
||||
movement := &entities.InventoryMovement{
|
||||
OrganizationID: order.OrganizationID,
|
||||
OutletID: order.OutletID,
|
||||
ItemID: item.ProductID,
|
||||
ItemType: "PRODUCT",
|
||||
MovementType: entities.InventoryMovementTypeSale,
|
||||
Quantity: float64(-item.Quantity),
|
||||
PreviousQuantity: float64(updatedInventory.Quantity + item.Quantity), // Add back the quantity that was subtracted
|
||||
NewQuantity: float64(updatedInventory.Quantity),
|
||||
UnitCost: item.UnitCost,
|
||||
TotalCost: float64(item.Quantity) * item.UnitCost,
|
||||
ReferenceType: func() *entities.InventoryMovementReferenceType {
|
||||
t := entities.InventoryMovementReferenceTypePayment
|
||||
return &t
|
||||
}(),
|
||||
ReferenceID: &payment.ID,
|
||||
OrderID: &order.ID,
|
||||
PaymentID: &payment.ID,
|
||||
UserID: order.UserID,
|
||||
Reason: stringPtr("Sale from order payment"),
|
||||
Notes: stringPtr(fmt.Sprintf("Order: %s, Payment: %s", order.OrderNumber, payment.ID)),
|
||||
Metadata: entities.Metadata{"order_item_id": item.ID},
|
||||
}
|
||||
|
||||
if err := r.createInventoryMovementWithTransaction(tx, movement); err != nil {
|
||||
return fmt.Errorf("failed to create inventory movement for product %s: %w", item.ProductID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return payment, nil
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) RefundPaymentWithInventoryMovement(ctx context.Context, paymentID uuid.UUID, refundAmount float64, reason string, refundedBy uuid.UUID, payment *entities.Payment) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := r.RefundPayment(ctx, paymentID, refundAmount, reason, refundedBy); err != nil {
|
||||
return fmt.Errorf("failed to refund payment: %w", err)
|
||||
}
|
||||
|
||||
// Get order for inventory management
|
||||
order, err := r.getOrderWithTransaction(tx, payment.OrderID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get order: %w", err)
|
||||
}
|
||||
|
||||
// Update order refund amount
|
||||
order.RefundAmount += refundAmount
|
||||
if err := tx.Model(&entities.Order{}).Where("id = ?", order.ID).Update("refund_amount", order.RefundAmount).Error; err != nil {
|
||||
return fmt.Errorf("failed to update order refund amount: %w", err)
|
||||
}
|
||||
|
||||
refundRatio := refundAmount / payment.Amount
|
||||
|
||||
orderItems, err := r.getOrderItemsWithTransaction(tx, order.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get order items for inventory adjustment: %w", err)
|
||||
}
|
||||
|
||||
for _, item := range orderItems {
|
||||
refundedQuantity := int(float64(item.Quantity) * refundRatio)
|
||||
if refundedQuantity > 0 {
|
||||
updatedInventory, err := r.adjustInventoryWithTransaction(tx, item.ProductID, order.OutletID, refundedQuantity)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to restore inventory for product %s: %w", item.ProductID, err)
|
||||
}
|
||||
|
||||
movement := &entities.InventoryMovement{
|
||||
OrganizationID: order.OrganizationID,
|
||||
OutletID: order.OutletID,
|
||||
ItemID: item.ProductID,
|
||||
ItemType: "PRODUCT",
|
||||
MovementType: entities.InventoryMovementTypeRefund,
|
||||
Quantity: float64(refundedQuantity),
|
||||
PreviousQuantity: float64(updatedInventory.Quantity - refundedQuantity), // Subtract the quantity that was added
|
||||
NewQuantity: float64(updatedInventory.Quantity),
|
||||
UnitCost: item.UnitCost,
|
||||
TotalCost: float64(refundedQuantity) * item.UnitCost,
|
||||
ReferenceType: func() *entities.InventoryMovementReferenceType {
|
||||
t := entities.InventoryMovementReferenceTypeRefund
|
||||
return &t
|
||||
}(),
|
||||
ReferenceID: &paymentID,
|
||||
OrderID: &order.ID,
|
||||
PaymentID: &paymentID,
|
||||
UserID: refundedBy,
|
||||
Reason: stringPtr(fmt.Sprintf("Refund: %s", reason)),
|
||||
Notes: stringPtr(fmt.Sprintf("Order: %s, Payment: %s, Refund Amount: %.2f", order.OrderNumber, paymentID, refundAmount)),
|
||||
Metadata: entities.Metadata{"order_item_id": item.ID, "refund_ratio": refundRatio},
|
||||
}
|
||||
|
||||
if err := r.createInventoryMovementWithTransaction(tx, movement); err != nil {
|
||||
return fmt.Errorf("failed to create inventory movement for refund product %s: %w", item.ProductID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Helper methods for transaction operations
|
||||
func (r *PaymentRepositoryImpl) getOrderWithTransaction(tx *gorm.DB, orderID uuid.UUID) (*entities.Order, error) {
|
||||
var order entities.Order
|
||||
err := tx.First(&order, "id = ?", orderID).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) getOrderItemsWithTransaction(tx *gorm.DB, orderID uuid.UUID) ([]*entities.OrderItem, error) {
|
||||
var orderItems []*entities.OrderItem
|
||||
err := tx.Where("order_id = ?", orderID).Find(&orderItems).Error
|
||||
return orderItems, err
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) adjustInventoryWithTransaction(tx *gorm.DB, productID, outletID uuid.UUID, delta int) (*entities.Inventory, error) {
|
||||
var inventory entities.Inventory
|
||||
|
||||
// Try to find existing inventory
|
||||
if err := tx.Where("product_id = ? AND outlet_id = ?", productID, outletID).First(&inventory).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// Inventory doesn't exist, create it with initial quantity
|
||||
inventory = entities.Inventory{
|
||||
ProductID: productID,
|
||||
OutletID: outletID,
|
||||
Quantity: 0,
|
||||
ReorderLevel: 0,
|
||||
}
|
||||
if err := tx.Create(&inventory).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to create inventory record: %w", err)
|
||||
}
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
inventory.UpdateQuantity(delta)
|
||||
if err := tx.Save(&inventory).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &inventory, nil
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) createInventoryMovementWithTransaction(tx *gorm.DB, movement *entities.InventoryMovement) error {
|
||||
return tx.Create(movement).Error
|
||||
}
|
||||
|
||||
// Helper function to create string pointer
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type txKeyType struct{}
|
||||
|
||||
var txKey = txKeyType{}
|
||||
|
||||
// DBFromContext returns the transactional *gorm.DB from context if present; otherwise returns base.
|
||||
func DBFromContext(ctx context.Context, base *gorm.DB) *gorm.DB {
|
||||
if v := ctx.Value(txKey); v != nil {
|
||||
if tx, ok := v.(*gorm.DB); ok && tx != nil {
|
||||
return tx
|
||||
}
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
type TxManager struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewTxManager(db *gorm.DB) *TxManager { return &TxManager{db: db} }
|
||||
|
||||
// WithTransaction runs fn inside a DB transaction, injecting the *gorm.DB tx into ctx.
|
||||
func (m *TxManager) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
|
||||
return m.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
ctxTx := context.WithValue(ctx, txKey, tx)
|
||||
return fn(ctxTx)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user