78 lines
2.4 KiB
Go
78 lines
2.4 KiB
Go
package repository
|
|
|
|
import (
|
|
"enaklo-pos-be/internal/common/mycontext"
|
|
"enaklo-pos-be/internal/entity"
|
|
"enaklo-pos-be/internal/repository/models"
|
|
"github.com/google/uuid"
|
|
"github.com/pkg/errors"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type TransactionRepo interface {
|
|
Create(ctx mycontext.Context, transaction *entity.Transaction) (*entity.Transaction, error)
|
|
FindByOrderID(ctx mycontext.Context, orderID int64) ([]*entity.Transaction, error)
|
|
}
|
|
|
|
type transactionRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewTransactionRepository(db *gorm.DB) *transactionRepository {
|
|
return &transactionRepository{
|
|
db: db,
|
|
}
|
|
}
|
|
|
|
func (r *transactionRepository) Create(ctx mycontext.Context, transaction *entity.Transaction) (*entity.Transaction, error) {
|
|
transactionDB := r.toTransactionDBModel(transaction)
|
|
|
|
if err := r.db.Create(&transactionDB).Error; err != nil {
|
|
return nil, errors.Wrap(err, "failed to insert transaction")
|
|
}
|
|
|
|
return transaction, nil
|
|
}
|
|
|
|
func (r *transactionRepository) FindByOrderID(ctx mycontext.Context, orderID int64) ([]*entity.Transaction, error) {
|
|
var transactionsDB []models.TransactionDB
|
|
|
|
if err := r.db.Where("order_id = ?", orderID).Find(&transactionsDB).Error; err != nil {
|
|
return nil, errors.Wrap(err, "failed to find transactions for order")
|
|
}
|
|
|
|
transactions := make([]*entity.Transaction, 0, len(transactionsDB))
|
|
for i := range transactionsDB {
|
|
transaction := r.toDomainTransactionModel(&transactionsDB[i])
|
|
transactions = append(transactions, transaction)
|
|
}
|
|
|
|
return transactions, nil
|
|
}
|
|
|
|
func (r *transactionRepository) toTransactionDBModel(transaction *entity.Transaction) models.TransactionDB {
|
|
return models.TransactionDB{
|
|
ID: uuid.New().String(),
|
|
OrderID: transaction.OrderID,
|
|
Amount: transaction.Amount,
|
|
PaymentMethod: transaction.PaymentMethod,
|
|
Status: transaction.Status,
|
|
CreatedAt: transaction.CreatedAt,
|
|
UpdatedAt: transaction.UpdatedAt,
|
|
TransactionType: transaction.TransactionType,
|
|
PartnerID: transaction.PartnerID,
|
|
}
|
|
}
|
|
|
|
func (r *transactionRepository) toDomainTransactionModel(dbModel *models.TransactionDB) *entity.Transaction {
|
|
return &entity.Transaction{
|
|
ID: dbModel.ID,
|
|
OrderID: dbModel.OrderID,
|
|
Amount: dbModel.Amount,
|
|
PaymentMethod: dbModel.PaymentMethod,
|
|
Status: dbModel.Status,
|
|
CreatedAt: dbModel.CreatedAt,
|
|
UpdatedAt: dbModel.UpdatedAt,
|
|
}
|
|
}
|