init
This commit is contained in:
Vendored
BIN
Binary file not shown.
@@ -1,337 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/models"
|
||||
"enaklo-pos-be/internal/services/v2/inprogress_order"
|
||||
time2 "time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type InProgressOrderRepository interface {
|
||||
FindByID(ctx mycontext.Context, id int64) (*entity.Order, error)
|
||||
CreateOrder(ctx mycontext.Context, order *entity.Order, tx *gorm.DB) (*entity.Order, error)
|
||||
CreateOrderItems(ctx mycontext.Context, orderID int64, items []entity.OrderItem, tx *gorm.DB) error
|
||||
GetListByPartnerID(ctx mycontext.Context, partnerID int64, limit, offset int, status string) ([]*entity.Order, error)
|
||||
FindByIDAndPartnerID(ctx mycontext.Context, id int64, partnerID int64) (*entity.Order, error)
|
||||
FindByIDWithTx(ctx mycontext.Context, id int64, tx *gorm.DB) (*entity.Order, error)
|
||||
}
|
||||
|
||||
type inprogressOrderRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewInProgressOrderRepository(db *gorm.DB) inprogress_order.OrderRepository {
|
||||
return &inprogressOrderRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) FindByID(ctx mycontext.Context, id int64) (*entity.Order, error) {
|
||||
var orderDB models.OrderDB
|
||||
|
||||
if err := r.db.Preload("OrderItems").First(&orderDB, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("order not found")
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to find order")
|
||||
}
|
||||
|
||||
order := r.toDomainOrderModel(&orderDB)
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) FindByIDWithTx(ctx mycontext.Context, id int64, tx *gorm.DB) (*entity.Order, error) {
|
||||
var orderDB models.OrderDB
|
||||
|
||||
if err := tx.Preload("OrderItems").First(&orderDB, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("order not found")
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to find order")
|
||||
}
|
||||
|
||||
order := r.toDomainOrderModel(&orderDB)
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) CreateOrder(ctx mycontext.Context, order *entity.Order, tx *gorm.DB) (*entity.Order, error) {
|
||||
orderDB := r.toOrderDBModel(order)
|
||||
|
||||
// Use provided transaction or create new one
|
||||
var dbTx *gorm.DB
|
||||
if tx != nil {
|
||||
dbTx = tx
|
||||
} else {
|
||||
dbTx = r.db.Begin()
|
||||
if dbTx.Error != nil {
|
||||
return nil, errors.Wrap(dbTx.Error, "failed to begin transaction")
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
dbTx.Rollback()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if err := dbTx.Create(&orderDB).Error; err != nil {
|
||||
if tx == nil {
|
||||
dbTx.Rollback()
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to insert order")
|
||||
}
|
||||
order.ID = orderDB.ID
|
||||
|
||||
// Only commit if we created the transaction
|
||||
if tx == nil {
|
||||
if err := dbTx.Commit().Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to commit transaction")
|
||||
}
|
||||
}
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) CreateOrderItems(ctx mycontext.Context, orderID int64, items []entity.OrderItem, tx *gorm.DB) error {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
itemsDB := make([]models.OrderItemDB, len(items))
|
||||
for i, item := range items {
|
||||
itemDB := r.toOrderItemDBModel(&item)
|
||||
itemDB.OrderID = orderID
|
||||
itemsDB[i] = itemDB
|
||||
}
|
||||
|
||||
if err := tx.Create(&itemsDB).Error; err != nil {
|
||||
return errors.Wrap(err, "failed to bulk insert order items")
|
||||
}
|
||||
|
||||
for i := range items {
|
||||
items[i].ID = itemsDB[i].ID
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
func (r *inprogressOrderRepository) GetListByPartnerID(ctx mycontext.Context, partnerID int64, limit, offset int, status string) ([]*entity.Order, error) {
|
||||
var ordersDB []models.OrderDB
|
||||
query := r.db.Where("partner_id = ?", partnerID)
|
||||
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
query = query.Order("created_at DESC")
|
||||
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
|
||||
if offset > 0 {
|
||||
query = query.Offset(offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&ordersDB).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to find orders by partner ID")
|
||||
}
|
||||
|
||||
orders := make([]*entity.Order, 0, len(ordersDB))
|
||||
for _, orderDB := range ordersDB {
|
||||
order := r.toDomainOrderModel(&orderDB)
|
||||
|
||||
var orderItems []models.OrderItemDB
|
||||
if err := r.db.Where("order_id = ?", orderDB.ID).Find(&orderItems).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to find order items")
|
||||
}
|
||||
|
||||
order.OrderItems = make([]entity.OrderItem, 0, len(orderItems))
|
||||
|
||||
for _, itemDB := range orderItems {
|
||||
item := r.toDomainOrderItemModel(&itemDB)
|
||||
|
||||
orderItem := entity.OrderItem{
|
||||
ID: item.ID,
|
||||
ItemID: item.ItemID,
|
||||
Quantity: item.Quantity,
|
||||
ItemName: item.ItemName,
|
||||
}
|
||||
|
||||
if itemDB.ItemID > 0 {
|
||||
var product models.ProductDB
|
||||
err := r.db.First(&product, itemDB.ItemID).Error
|
||||
|
||||
if err == nil {
|
||||
productDomain := r.toDomainProductModel(&product)
|
||||
orderItem.Product = productDomain
|
||||
}
|
||||
}
|
||||
|
||||
order.OrderItems = append(order.OrderItems, orderItem)
|
||||
}
|
||||
|
||||
orders = append(orders, order)
|
||||
}
|
||||
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) FindByIDAndPartnerID(ctx mycontext.Context, id int64, partnerID int64) (*entity.Order, error) {
|
||||
var orderDB models.OrderDB
|
||||
|
||||
if err := r.db.Preload("OrderItems").Where("id = ? AND partner_id = ?", id, partnerID).First(&orderDB).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("order not found")
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to find order")
|
||||
}
|
||||
|
||||
order := r.toDomainOrderModel(&orderDB)
|
||||
|
||||
for _, itemDB := range orderDB.OrderItems {
|
||||
item := r.toDomainOrderItemModel(&itemDB)
|
||||
order.OrderItems = append(order.OrderItems, *item)
|
||||
}
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) toOrderDBModel(order *entity.Order) models.OrderDB {
|
||||
now := time2.Now()
|
||||
return models.OrderDB{
|
||||
ID: order.ID,
|
||||
PartnerID: order.PartnerID,
|
||||
CustomerID: order.CustomerID,
|
||||
CustomerName: order.CustomerName,
|
||||
PaymentType: order.PaymentType,
|
||||
PaymentProvider: order.PaymentProvider,
|
||||
CreatedBy: order.CreatedBy,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
TableNumber: order.TableNumber,
|
||||
OrderType: order.OrderType,
|
||||
Status: order.Status,
|
||||
Amount: order.Amount,
|
||||
Total: order.Total,
|
||||
Tax: order.Tax,
|
||||
Source: order.Source,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) toDomainOrderModel(dbModel *models.OrderDB) *entity.Order {
|
||||
orderItems := make([]entity.OrderItem, 0, len(dbModel.OrderItems))
|
||||
for _, itemDB := range dbModel.OrderItems {
|
||||
orderItems = append(orderItems, entity.OrderItem{
|
||||
ItemID: itemDB.ItemID,
|
||||
ItemType: itemDB.ItemType,
|
||||
ItemName: itemDB.ItemName,
|
||||
Price: itemDB.Price,
|
||||
Quantity: itemDB.Quantity,
|
||||
Status: itemDB.Status,
|
||||
CreatedBy: itemDB.CreatedBy,
|
||||
CreatedAt: itemDB.CreatedAt,
|
||||
Notes: itemDB.Notes,
|
||||
})
|
||||
}
|
||||
|
||||
return &entity.Order{
|
||||
ID: dbModel.ID,
|
||||
PartnerID: dbModel.PartnerID,
|
||||
CustomerID: dbModel.CustomerID,
|
||||
InquiryID: dbModel.InquiryID,
|
||||
Status: dbModel.Status,
|
||||
Amount: dbModel.Amount,
|
||||
Tax: dbModel.Tax,
|
||||
Total: dbModel.Total,
|
||||
PaymentType: dbModel.PaymentType,
|
||||
Source: dbModel.Source,
|
||||
CreatedBy: dbModel.CreatedBy,
|
||||
CreatedAt: dbModel.CreatedAt,
|
||||
UpdatedAt: dbModel.UpdatedAt,
|
||||
OrderItems: orderItems,
|
||||
CustomerName: dbModel.CustomerName,
|
||||
TableNumber: dbModel.TableNumber,
|
||||
OrderType: dbModel.OrderType,
|
||||
PaymentProvider: dbModel.PaymentProvider,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) toOrderItemDBModel(item *entity.OrderItem) models.OrderItemDB {
|
||||
return models.OrderItemDB{
|
||||
ID: item.ID,
|
||||
OrderID: item.OrderID,
|
||||
ItemID: item.ItemID,
|
||||
ItemType: item.ItemType,
|
||||
ItemName: item.ItemName,
|
||||
Price: item.Price,
|
||||
Quantity: item.Quantity,
|
||||
Status: item.Status,
|
||||
CreatedBy: item.CreatedBy,
|
||||
CreatedAt: item.CreatedAt,
|
||||
Notes: item.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) toDomainOrderItemModel(dbModel *models.OrderItemDB) *entity.OrderItem {
|
||||
return &entity.OrderItem{
|
||||
ID: dbModel.ID,
|
||||
OrderID: dbModel.OrderID,
|
||||
ItemID: dbModel.ItemID,
|
||||
ItemType: dbModel.ItemType,
|
||||
Price: dbModel.Price,
|
||||
Quantity: dbModel.Quantity,
|
||||
Status: dbModel.Status,
|
||||
CreatedBy: dbModel.CreatedBy,
|
||||
CreatedAt: dbModel.CreatedAt,
|
||||
ItemName: dbModel.ItemName,
|
||||
Notes: dbModel.Notes,
|
||||
Product: &entity.Product{
|
||||
ID: dbModel.ItemID,
|
||||
Name: dbModel.ItemName,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) toDomainProductModel(productDB *models.ProductDB) *entity.Product {
|
||||
if productDB == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &entity.Product{
|
||||
ID: productDB.ID,
|
||||
Name: productDB.Name,
|
||||
Description: productDB.Description,
|
||||
Price: productDB.Price,
|
||||
CreatedAt: productDB.CreatedAt,
|
||||
UpdatedAt: productDB.UpdatedAt,
|
||||
Type: productDB.Type,
|
||||
Image: productDB.Image,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *inprogressOrderRepository) UpdateOrderTotalsWithTx(ctx mycontext.Context, trx *gorm.DB, orderID int64, amount, tax, total float64) error {
|
||||
now := time2.Now()
|
||||
|
||||
result := trx.Model(&models.OrderDB{}).
|
||||
Where("id = ?", orderID).
|
||||
Updates(map[string]interface{}{
|
||||
"amount": amount,
|
||||
"tax": tax,
|
||||
"total": total,
|
||||
"updated_at": now,
|
||||
})
|
||||
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(result.Error, "failed to update order totals")
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
logger.ContextLogger(ctx).Warn("no order updated")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type AnalyticsRepository interface {
|
||||
GetPaymentMethodAnalytics(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time) ([]*entities.PaymentMethodAnalytics, error)
|
||||
GetSalesAnalytics(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time, groupBy string) ([]*entities.SalesAnalytics, error)
|
||||
GetProductAnalytics(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time, limit int) ([]*entities.ProductAnalytics, error)
|
||||
GetDashboardOverview(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time) (*entities.DashboardOverview, error)
|
||||
GetProfitLossAnalytics(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time, groupBy string) (*entities.ProfitLossAnalytics, error)
|
||||
}
|
||||
|
||||
type AnalyticsRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewAnalyticsRepositoryImpl(db *gorm.DB) *AnalyticsRepositoryImpl {
|
||||
return &AnalyticsRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AnalyticsRepositoryImpl) GetPaymentMethodAnalytics(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time) ([]*entities.PaymentMethodAnalytics, error) {
|
||||
var results []*entities.PaymentMethodAnalytics
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("payments p").
|
||||
Select(`
|
||||
pm.id as payment_method_id,
|
||||
pm.name as payment_method_name,
|
||||
pm.type as payment_method_type,
|
||||
COALESCE(SUM(p.amount), 0) as total_amount,
|
||||
COUNT(DISTINCT p.order_id) as order_count,
|
||||
COUNT(p.id) as payment_count
|
||||
`).
|
||||
Joins("JOIN payment_methods pm ON p.payment_method_id = pm.id").
|
||||
Joins("JOIN orders o ON p.order_id = o.id").
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("p.status = ?", entities.PaymentTransactionStatusCompleted).
|
||||
Where("p.created_at >= ? AND p.created_at <= ?", dateFrom, dateTo)
|
||||
|
||||
if outletID != nil {
|
||||
query = query.Where("o.outlet_id = ?", *outletID)
|
||||
}
|
||||
|
||||
err := query.
|
||||
Group("pm.id, pm.name, pm.type").
|
||||
Order("total_amount DESC").
|
||||
Scan(&results).Error
|
||||
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (r *AnalyticsRepositoryImpl) GetSalesAnalytics(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time, groupBy string) ([]*entities.SalesAnalytics, error) {
|
||||
var results []*entities.SalesAnalytics
|
||||
|
||||
var dateFormat string
|
||||
switch groupBy {
|
||||
case "hour":
|
||||
dateFormat = "DATE_TRUNC('hour', o.created_at)"
|
||||
case "week":
|
||||
dateFormat = "DATE_TRUNC('week', o.created_at)"
|
||||
case "month":
|
||||
dateFormat = "DATE_TRUNC('month', o.created_at)"
|
||||
default:
|
||||
dateFormat = "DATE(o.created_at)"
|
||||
}
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("orders o").
|
||||
Select(`
|
||||
`+dateFormat+` as date,
|
||||
COALESCE(SUM(o.total_amount), 0) as sales,
|
||||
COUNT(o.id) as orders,
|
||||
COALESCE(SUM(oi.quantity), 0) as items,
|
||||
COALESCE(SUM(o.tax_amount), 0) as tax,
|
||||
COALESCE(SUM(o.discount_amount), 0) as discount,
|
||||
COALESCE(SUM(o.total_amount - o.tax_amount - o.discount_amount), 0) as net_sales
|
||||
`).
|
||||
Joins("LEFT JOIN order_items oi ON o.id = oi.order_id").
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("o.is_void = ?", false).
|
||||
Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo)
|
||||
|
||||
if outletID != nil {
|
||||
query = query.Where("o.outlet_id = ?", *outletID)
|
||||
}
|
||||
|
||||
err := query.
|
||||
Group("date").
|
||||
Order("date ASC").
|
||||
Scan(&results).Error
|
||||
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (r *AnalyticsRepositoryImpl) GetProductAnalytics(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time, limit int) ([]*entities.ProductAnalytics, error) {
|
||||
var results []*entities.ProductAnalytics
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("order_items oi").
|
||||
Select(`
|
||||
p.id as product_id,
|
||||
p.name as product_name,
|
||||
c.id as category_id,
|
||||
c.name as category_name,
|
||||
COALESCE(SUM(oi.quantity), 0) as quantity_sold,
|
||||
COALESCE(SUM(oi.total_price), 0) as revenue,
|
||||
CASE
|
||||
WHEN SUM(oi.quantity) > 0 THEN COALESCE(SUM(oi.total_price), 0) / SUM(oi.quantity)
|
||||
ELSE 0
|
||||
END as average_price,
|
||||
COUNT(DISTINCT oi.order_id) as order_count
|
||||
`).
|
||||
Joins("JOIN products p ON oi.product_id = p.id").
|
||||
Joins("JOIN categories c ON p.category_id = c.id").
|
||||
Joins("JOIN orders o ON oi.order_id = o.id").
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("o.is_void = ?", false).
|
||||
Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo)
|
||||
|
||||
if outletID != nil {
|
||||
query = query.Where("o.outlet_id = ?", *outletID)
|
||||
}
|
||||
|
||||
err := query.
|
||||
Group("p.id, p.name, c.id, c.name").
|
||||
Order("revenue DESC").
|
||||
Limit(limit).
|
||||
Scan(&results).Error
|
||||
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (r *AnalyticsRepositoryImpl) GetDashboardOverview(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time) (*entities.DashboardOverview, error) {
|
||||
var result entities.DashboardOverview
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("orders o").
|
||||
Select(`
|
||||
COALESCE(SUM(CASE WHEN o.is_void = false THEN o.total_amount ELSE 0 END), 0) as total_sales,
|
||||
COUNT(CASE WHEN o.is_void = false THEN o.id END) as total_orders,
|
||||
CASE
|
||||
WHEN COUNT(CASE WHEN o.is_void = false THEN o.id END) > 0
|
||||
THEN COALESCE(SUM(CASE WHEN o.is_void = false THEN o.total_amount ELSE 0 END), 0) / COUNT(CASE WHEN o.is_void = false THEN o.id END)
|
||||
ELSE 0
|
||||
END as average_order_value,
|
||||
COUNT(DISTINCT o.customer_id) as total_customers,
|
||||
COUNT(CASE WHEN o.is_void = true THEN o.id END) as voided_orders,
|
||||
COUNT(CASE WHEN o.is_refund = true THEN o.id END) as refunded_orders
|
||||
`).
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo)
|
||||
|
||||
if outletID != nil {
|
||||
query = query.Where("o.outlet_id = ?", *outletID)
|
||||
}
|
||||
|
||||
err := query.Scan(&result).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (r *AnalyticsRepositoryImpl) GetProfitLossAnalytics(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, dateFrom, dateTo time.Time, groupBy string) (*entities.ProfitLossAnalytics, error) {
|
||||
// Summary query
|
||||
var summary entities.ProfitLossSummary
|
||||
|
||||
summaryQuery := r.db.WithContext(ctx).
|
||||
Table("orders o").
|
||||
Select(`
|
||||
COALESCE(SUM(o.total_amount), 0) as total_revenue,
|
||||
COALESCE(SUM(o.total_cost), 0) as total_cost,
|
||||
COALESCE(SUM(o.total_amount - o.total_cost), 0) as gross_profit,
|
||||
CASE
|
||||
WHEN SUM(o.total_amount) > 0
|
||||
THEN (SUM(o.total_amount - o.total_cost) / SUM(o.total_amount)) * 100
|
||||
ELSE 0
|
||||
END as gross_profit_margin,
|
||||
COALESCE(SUM(o.tax_amount), 0) as total_tax,
|
||||
COALESCE(SUM(o.discount_amount), 0) as total_discount,
|
||||
COALESCE(SUM(o.total_amount - o.total_cost - o.discount_amount), 0) as net_profit,
|
||||
CASE
|
||||
WHEN SUM(o.total_amount) > 0
|
||||
THEN (SUM(o.total_amount - o.total_cost - o.discount_amount) / SUM(o.total_amount)) * 100
|
||||
ELSE 0
|
||||
END as net_profit_margin,
|
||||
COUNT(o.id) as total_orders,
|
||||
CASE
|
||||
WHEN COUNT(o.id) > 0
|
||||
THEN SUM(o.total_amount - o.total_cost - o.discount_amount) / COUNT(o.id)
|
||||
ELSE 0
|
||||
END as average_profit,
|
||||
CASE
|
||||
WHEN SUM(o.total_cost) > 0
|
||||
THEN (SUM(o.total_amount - o.total_cost) / SUM(o.total_cost)) * 100
|
||||
ELSE 0
|
||||
END as profitability_ratio
|
||||
`).
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("o.status = ?", entities.OrderStatusCompleted).
|
||||
Where("o.payment_status = ?", entities.PaymentStatusCompleted).
|
||||
Where("o.is_void = false AND o.is_refund = false").
|
||||
Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo)
|
||||
|
||||
if outletID != nil {
|
||||
summaryQuery = summaryQuery.Where("o.outlet_id = ?", *outletID)
|
||||
}
|
||||
|
||||
err := summaryQuery.Scan(&summary).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Time series data query
|
||||
var timeFormat string
|
||||
switch groupBy {
|
||||
case "hour":
|
||||
timeFormat = "DATE_TRUNC('hour', o.created_at)"
|
||||
case "week":
|
||||
timeFormat = "DATE_TRUNC('week', o.created_at)"
|
||||
case "month":
|
||||
timeFormat = "DATE_TRUNC('month', o.created_at)"
|
||||
default: // day
|
||||
timeFormat = "DATE_TRUNC('day', o.created_at)"
|
||||
}
|
||||
|
||||
var data []entities.ProfitLossData
|
||||
|
||||
dataQuery := r.db.WithContext(ctx).
|
||||
Table("orders o").
|
||||
Select(`
|
||||
`+timeFormat+` as date,
|
||||
COALESCE(SUM(o.total_amount), 0) as revenue,
|
||||
COALESCE(SUM(o.total_cost), 0) as cost,
|
||||
COALESCE(SUM(o.total_amount - o.total_cost), 0) as gross_profit,
|
||||
CASE
|
||||
WHEN SUM(o.total_amount) > 0
|
||||
THEN (SUM(o.total_amount - o.total_cost) / SUM(o.total_amount)) * 100
|
||||
ELSE 0
|
||||
END as gross_profit_margin,
|
||||
COALESCE(SUM(o.tax_amount), 0) as tax,
|
||||
COALESCE(SUM(o.discount_amount), 0) as discount,
|
||||
COALESCE(SUM(o.total_amount - o.total_cost - o.discount_amount), 0) as net_profit,
|
||||
CASE
|
||||
WHEN SUM(o.total_amount) > 0
|
||||
THEN (SUM(o.total_amount - o.total_cost - o.discount_amount) / SUM(o.total_amount)) * 100
|
||||
ELSE 0
|
||||
END as net_profit_margin,
|
||||
COUNT(o.id) as orders
|
||||
`).
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("o.status = ?", entities.OrderStatusCompleted).
|
||||
Where("o.payment_status = ?", entities.PaymentStatusCompleted).
|
||||
Where("o.is_void = false AND o.is_refund = false").
|
||||
Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo).
|
||||
Group(timeFormat).
|
||||
Order(timeFormat)
|
||||
|
||||
if outletID != nil {
|
||||
dataQuery = dataQuery.Where("o.outlet_id = ?", *outletID)
|
||||
}
|
||||
|
||||
err = dataQuery.Scan(&data).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Product profit data query
|
||||
var productData []entities.ProductProfitData
|
||||
|
||||
productQuery := r.db.WithContext(ctx).
|
||||
Table("order_items oi").
|
||||
Select(`
|
||||
p.id as product_id,
|
||||
p.name as product_name,
|
||||
c.id as category_id,
|
||||
c.name as category_name,
|
||||
SUM(oi.quantity) as quantity_sold,
|
||||
SUM(oi.total_price) as revenue,
|
||||
SUM(oi.total_cost) as cost,
|
||||
SUM(oi.total_price - oi.total_cost) as gross_profit,
|
||||
CASE
|
||||
WHEN SUM(oi.total_price) > 0
|
||||
THEN (SUM(oi.total_price - oi.total_cost) / SUM(oi.total_price)) * 100
|
||||
ELSE 0
|
||||
END as gross_profit_margin,
|
||||
AVG(oi.unit_price) as average_price,
|
||||
AVG(oi.unit_cost) as average_cost,
|
||||
AVG(oi.unit_price - oi.unit_cost) as profit_per_unit
|
||||
`).
|
||||
Joins("JOIN orders o ON oi.order_id = o.id").
|
||||
Joins("JOIN products p ON oi.product_id = p.id").
|
||||
Joins("JOIN categories c ON p.category_id = c.id").
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("o.status = ?", entities.OrderStatusCompleted).
|
||||
Where("o.payment_status = ?", entities.PaymentStatusCompleted).
|
||||
Where("o.is_void = false AND o.is_refund = false").
|
||||
Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo).
|
||||
Group("p.id, p.name, c.id, c.name").
|
||||
Order("gross_profit DESC").
|
||||
Limit(20)
|
||||
|
||||
if outletID != nil {
|
||||
productQuery = productQuery.Where("o.outlet_id = ?", *outletID)
|
||||
}
|
||||
|
||||
err = productQuery.Scan(&productData).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &entities.ProfitLossAnalytics{
|
||||
Summary: summary,
|
||||
Data: data,
|
||||
ProductData: productData,
|
||||
}, nil
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
package auth
|
||||
@@ -1,98 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
)
|
||||
|
||||
type AuthRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewAuthRepository(db *gorm.DB) *AuthRepository {
|
||||
return &AuthRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AuthRepository) CheckExistsUserAccount(ctx context.Context, email string) (*entity.UserDB, error) {
|
||||
var user entity.UserDB
|
||||
|
||||
err := r.db.
|
||||
Table("users").
|
||||
Select("users.*, user_roles.role_id, user_roles.partner_id, user_roles.site_id,"+
|
||||
" sites.name, roles.role_name, partners.name as partner_name, partners.status as partner_status, users.reset_password").
|
||||
Where("users.email = ?", email).
|
||||
Joins("left join user_roles on users.id = user_roles.user_id").
|
||||
Joins("left join roles on user_roles.role_id = roles.role_id").
|
||||
Joins("left join partners on user_roles.partner_id = partners.id").
|
||||
Joins("left join sites on user_roles.site_id = sites.id").
|
||||
First(&user).Error
|
||||
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("user with email %s does not exist", email) // or use a custom error type
|
||||
}
|
||||
|
||||
logger.ContextLogger(ctx).Error(fmt.Sprintf("Failed to get user with email: %s", email), zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *AuthRepository) CheckExistsUserAccountByID(ctx context.Context, userID int64) (*entity.UserDB, error) {
|
||||
var user entity.UserDB
|
||||
|
||||
err := r.db.
|
||||
Table("users").
|
||||
Select("users.*, user_roles.role_id, user_roles.partner_id, user_roles.site_id, sites.name, roles.role_name, partners.name as partner_name, partners.status as partner_status").
|
||||
Where("users.id = ?", userID).
|
||||
Joins("left join user_roles on users.id = user_roles.user_id").
|
||||
Joins("left join roles on user_roles.role_id = roles.role_id").
|
||||
Joins("left join partners on user_roles.partner_id = partners.id").
|
||||
Joins("left join sites on user_roles.site_id = sites.id").
|
||||
First(&user).Error
|
||||
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("user with not exist") // or use a custom error type
|
||||
}
|
||||
|
||||
logger.ContextLogger(ctx).Error(fmt.Sprintf("Failed to get user"), zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *AuthRepository) UpdatePassword(ctx context.Context, trx *gorm.DB, newHashedPassword string, userID int64, resetPassword bool) error {
|
||||
// Perform the update using a single Updates call
|
||||
err := trx.Model(&entity.UserDB{}).
|
||||
Where("id = ?", userID).
|
||||
Updates(map[string]interface{}{
|
||||
"password": newHashedPassword,
|
||||
"reset_password": resetPassword,
|
||||
}).Error
|
||||
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error(fmt.Sprintf("Failed to update password for user with id: %d", userID), zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package brevo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"go.uber.org/zap"
|
||||
"html/template"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
|
||||
brevo "github.com/getbrevo/brevo-go/lib"
|
||||
)
|
||||
|
||||
type Config interface {
|
||||
GetApiKey() string
|
||||
}
|
||||
|
||||
type ServiceImpl struct {
|
||||
brevoConn *brevo.APIClient
|
||||
}
|
||||
|
||||
func (s ServiceImpl) SendEmailTransactional(ctx context.Context, param entity.SendEmailNotificationParam) error {
|
||||
templateFile, err := ioutil.ReadFile(param.TemplatePath)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when reading file template", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
tmpl := template.New(param.TemplateName).Funcs(template.FuncMap{
|
||||
"range": func(args ...interface{}) []interface{} {
|
||||
if len(args) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch items := args[0].(type) {
|
||||
case []map[string]string:
|
||||
result := make([]interface{}, len(items))
|
||||
for i, item := range items {
|
||||
result[i] = item
|
||||
}
|
||||
return result
|
||||
case []interface{}:
|
||||
return items
|
||||
default:
|
||||
if slice, ok := args[0].([]interface{}); ok {
|
||||
return slice
|
||||
}
|
||||
return nil
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
renderedTemplate, err := tmpl.Parse(string(templateFile))
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return err
|
||||
}
|
||||
|
||||
return s.sendEmail(ctx, renderedTemplate, param)
|
||||
}
|
||||
|
||||
func (s ServiceImpl) sendEmail(ctx context.Context, tmpl *template.Template, param entity.SendEmailNotificationParam) error {
|
||||
var body bytes.Buffer
|
||||
err := tmpl.Execute(&body, param.Data)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return err
|
||||
}
|
||||
|
||||
payload := brevo.SendSmtpEmail{
|
||||
Sender: &brevo.SendSmtpEmailSender{
|
||||
Name: "Enaklo",
|
||||
Email: param.Sender,
|
||||
},
|
||||
To: []brevo.SendSmtpEmailTo{
|
||||
{
|
||||
Email: param.Recipient,
|
||||
},
|
||||
},
|
||||
Subject: param.Subject,
|
||||
HtmlContent: body.String(),
|
||||
}
|
||||
|
||||
if len(param.CcEmails) != 0 {
|
||||
for _, email := range param.CcEmails {
|
||||
payload.Cc = append(payload.Cc, brevo.SendSmtpEmailCc{
|
||||
Email: email,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
_, _, err = s.brevoConn.TransactionalEmailsApi.SendTransacEmail(ctx, payload)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when sending email", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
logger.ContextLogger(ctx).Info("sending email success")
|
||||
return nil
|
||||
}
|
||||
|
||||
func New(conf Config) *ServiceImpl {
|
||||
cfg := brevo.NewConfiguration()
|
||||
cfg.AddDefaultHeader("api-key", conf.GetApiKey())
|
||||
client := brevo.NewAPIClient(cfg)
|
||||
return &ServiceImpl{brevoConn: client}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/models"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CashierSessionRepository interface {
|
||||
CreateSession(ctx mycontext.Context, session *entity.CashierSession) (*entity.CashierSession, error)
|
||||
CloseSession(ctx mycontext.Context, sessionID int64, closingAmount, expectedAmount float64) error
|
||||
GetOpenSessionByCashierID(ctx mycontext.Context, cashierID int64) (*entity.CashierSession, error)
|
||||
GetSessionByID(ctx mycontext.Context, sessionID int64) (*entity.CashierSession, error)
|
||||
GetPaymentSummaryBySessionID(ctx mycontext.Context, sessionID int64) ([]entity.PaymentSummary, error)
|
||||
GetSessionHistoryByPartnerID(ctx mycontext.Context, partnerID int64, limit, offset int) ([]*entity.CashierSession, int64, error)
|
||||
}
|
||||
|
||||
type cashierSessionRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewCashierSessionRepository(db *gorm.DB) CashierSessionRepository {
|
||||
return &cashierSessionRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *cashierSessionRepository) CreateSession(ctx mycontext.Context, session *entity.CashierSession) (*entity.CashierSession, error) {
|
||||
dbModel := models.CashierSessionDB{
|
||||
PartnerID: session.PartnerID,
|
||||
CashierID: session.CashierID,
|
||||
OpenedAt: time.Now(),
|
||||
OpeningAmount: session.OpeningAmount,
|
||||
Status: "open",
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := r.db.Create(&dbModel).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to create cashier session")
|
||||
}
|
||||
|
||||
session.ID = dbModel.ID
|
||||
session.Status = dbModel.Status
|
||||
session.OpenedAt = dbModel.OpenedAt
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (r *cashierSessionRepository) CloseSession(ctx mycontext.Context, sessionID int64, closingAmount, expectedAmount float64) error {
|
||||
result := r.db.Model(&models.CashierSessionDB{}).
|
||||
Where("id = ?", sessionID).
|
||||
Updates(map[string]interface{}{
|
||||
"closed_at": time.Now(),
|
||||
"closing_amount": closingAmount,
|
||||
"expected_amount": expectedAmount,
|
||||
"status": "closed",
|
||||
})
|
||||
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(result.Error, "failed to close session")
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("no session updated")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *cashierSessionRepository) GetOpenSessionByCashierID(ctx mycontext.Context, cashierID int64) (*entity.CashierSession, error) {
|
||||
var dbModel models.CashierSessionDB
|
||||
if err := r.db.Where("cashier_id = ? AND status = 'open'", cashierID).
|
||||
Order("opened_at DESC").First(&dbModel).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to get open session")
|
||||
}
|
||||
|
||||
return r.toEntity(&dbModel), nil
|
||||
}
|
||||
|
||||
func (r *cashierSessionRepository) GetSessionByID(ctx mycontext.Context, sessionID int64) (*entity.CashierSession, error) {
|
||||
var dbModel models.CashierSessionDB
|
||||
if err := r.db.First(&dbModel, sessionID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to get session by ID")
|
||||
}
|
||||
|
||||
return r.toEntity(&dbModel), nil
|
||||
}
|
||||
|
||||
func (r *cashierSessionRepository) toEntity(db *models.CashierSessionDB) *entity.CashierSession {
|
||||
return &entity.CashierSession{
|
||||
ID: db.ID,
|
||||
PartnerID: db.PartnerID,
|
||||
CashierID: db.CashierID,
|
||||
OpenedAt: db.OpenedAt,
|
||||
ClosedAt: db.ClosedAt,
|
||||
OpeningAmount: db.OpeningAmount,
|
||||
ClosingAmount: db.ClosingAmount,
|
||||
ExpectedAmount: db.ExpectedAmount,
|
||||
Status: db.Status,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *cashierSessionRepository) GetPaymentSummaryBySessionID(ctx mycontext.Context, sessionID int64) ([]entity.PaymentSummary, error) {
|
||||
type result struct {
|
||||
PaymentType string
|
||||
PaymentProvider string
|
||||
TotalAmount float64
|
||||
}
|
||||
|
||||
var rows []result
|
||||
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("orders").
|
||||
Select("payment_type, payment_provider, SUM(total) AS total_amount").
|
||||
Where("cashier_session_id = ?", sessionID).
|
||||
Group("payment_type, payment_provider").
|
||||
Scan(&rows).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to summarize payments from orders")
|
||||
}
|
||||
|
||||
summary := make([]entity.PaymentSummary, len(rows))
|
||||
for i, row := range rows {
|
||||
summary[i] = entity.PaymentSummary{
|
||||
PaymentType: row.PaymentType,
|
||||
PaymentProvider: row.PaymentProvider,
|
||||
TotalAmount: row.TotalAmount,
|
||||
}
|
||||
}
|
||||
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func (r *cashierSessionRepository) GetSessionHistoryByPartnerID(ctx mycontext.Context, partnerID int64, limit, offset int) ([]*entity.CashierSession, int64, error) {
|
||||
var sessionsDB []models.CashierSessionDB
|
||||
var totalCount int64
|
||||
|
||||
// Count total records
|
||||
if err := r.db.Model(&models.CashierSessionDB{}).
|
||||
Where("partner_id = ?", partnerID).
|
||||
Count(&totalCount).Error; err != nil {
|
||||
return nil, 0, errors.Wrap(err, "failed to count cashier sessions")
|
||||
}
|
||||
|
||||
// Get sessions with pagination
|
||||
query := r.db.Where("partner_id = ?", partnerID).
|
||||
Order("opened_at DESC")
|
||||
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
|
||||
if offset > 0 {
|
||||
query = query.Offset(offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&sessionsDB).Error; err != nil {
|
||||
return nil, 0, errors.Wrap(err, "failed to get cashier session history")
|
||||
}
|
||||
|
||||
// Convert to entity
|
||||
sessions := make([]*entity.CashierSession, len(sessionsDB))
|
||||
for i, sessionDB := range sessionsDB {
|
||||
sessions[i] = r.toEntity(&sessionDB)
|
||||
}
|
||||
|
||||
return sessions, totalCount, nil
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/models"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type CategoryRepository interface {
|
||||
Create(ctx mycontext.Context, category *entity.Category) (*entity.Category, error)
|
||||
GetByPartnerID(ctx mycontext.Context, partnerID int64) ([]*entity.Category, error)
|
||||
GetByID(ctx mycontext.Context, id int64) (*entity.Category, error)
|
||||
Update(ctx mycontext.Context, category *entity.Category) error
|
||||
Delete(ctx mycontext.Context, id int64) error
|
||||
}
|
||||
|
||||
type categoryRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewCategoryRepository(db *gorm.DB) CategoryRepository {
|
||||
return &categoryRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *categoryRepository) Create(ctx mycontext.Context, category *entity.Category) (*entity.Category, error) {
|
||||
dbModel := &models.CategoryDB{
|
||||
PartnerID: category.PartnerID,
|
||||
Name: category.Name,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(dbModel).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to create category")
|
||||
}
|
||||
category.ID = dbModel.ID
|
||||
return category, nil
|
||||
}
|
||||
|
||||
func (r *categoryRepository) GetByPartnerID(ctx mycontext.Context, partnerID int64) ([]*entity.Category, error) {
|
||||
var dbModels []models.CategoryDB
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("partner_id = ? AND deleted_at IS NULL", partnerID).
|
||||
Find(&dbModels).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to fetch categories by partner ID")
|
||||
}
|
||||
|
||||
var result []*entity.Category
|
||||
for _, db := range dbModels {
|
||||
result = append(result, r.toEntity(&db))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *categoryRepository) GetByID(ctx mycontext.Context, id int64) (*entity.Category, error) {
|
||||
var db models.CategoryDB
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("id = ? AND deleted_at IS NULL", id).
|
||||
First(&db).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to get category by ID")
|
||||
}
|
||||
return r.toEntity(&db), nil
|
||||
}
|
||||
|
||||
func (r *categoryRepository) Update(ctx mycontext.Context, category *entity.Category) error {
|
||||
return r.db.WithContext(ctx).Model(&models.CategoryDB{}).
|
||||
Where("id = ?", category.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"name": category.Name,
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *categoryRepository) Delete(ctx mycontext.Context, id int64) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&models.CategoryDB{}).
|
||||
Where("id = ?", id).
|
||||
Update("deleted_at", time.Now()).Error
|
||||
}
|
||||
|
||||
func (r *categoryRepository) toEntity(db *models.CategoryDB) *entity.Category {
|
||||
return &entity.Category{
|
||||
ID: db.ID,
|
||||
PartnerID: db.PartnerID,
|
||||
Name: db.Name,
|
||||
CreatedAt: db.CreatedAt.Unix(),
|
||||
UpdatedAt: db.UpdatedAt.Unix(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CategoryRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewCategoryRepositoryImpl(db *gorm.DB) *CategoryRepositoryImpl {
|
||||
return &CategoryRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) Create(ctx context.Context, category *entities.Category) error {
|
||||
return r.db.WithContext(ctx).Create(category).Error
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.Category, error) {
|
||||
var category entities.Category
|
||||
err := r.db.WithContext(ctx).First(&category, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &category, nil
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) GetWithProducts(ctx context.Context, id uuid.UUID) (*entities.Category, error) {
|
||||
var category entities.Category
|
||||
err := r.db.WithContext(ctx).Preload("Products").First(&category, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &category, nil
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) GetByOrganization(ctx context.Context, organizationID uuid.UUID) ([]*entities.Category, error) {
|
||||
var categories []*entities.Category
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ?", organizationID).Find(&categories).Error
|
||||
return categories, err
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) GetByBusinessType(ctx context.Context, businessType string) ([]*entities.Category, error) {
|
||||
var categories []*entities.Category
|
||||
err := r.db.WithContext(ctx).Where("business_type = ?", businessType).Find(&categories).Error
|
||||
return categories, err
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) Update(ctx context.Context, category *entities.Category) error {
|
||||
return r.db.WithContext(ctx).Save(category).Error
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.Category{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.Category, int64, error) {
|
||||
var categories []*entities.Category
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.Category{})
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Where("name ILIKE ? OR description ILIKE ?", searchValue, searchValue)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Find(&categories).Error
|
||||
return categories, total, err
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.Category{})
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Where("name ILIKE ? OR description ILIKE ?", searchValue, searchValue)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) GetByName(ctx context.Context, organizationID uuid.UUID, name string) (*entities.Category, error) {
|
||||
var category entities.Category
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ? AND name = ?", organizationID, name).First(&category).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &category, nil
|
||||
}
|
||||
|
||||
func (r *CategoryRepositoryImpl) ExistsByName(ctx context.Context, organizationID uuid.UUID, name string, excludeID *uuid.UUID) (bool, error) {
|
||||
query := r.db.WithContext(ctx).Model(&entities.Category{}).Where("organization_id = ? AND name = ?", organizationID, name)
|
||||
|
||||
if excludeID != nil {
|
||||
query = query.Where("id != ?", *excludeID)
|
||||
}
|
||||
|
||||
var count int64
|
||||
err := query.Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
//go:generate mockery --name Crypto --filename crypto.go --output ./mock --with-expecter
|
||||
|
||||
package crypto
|
||||
|
||||
@@ -1,324 +0,0 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"enaklo-pos-be/internal/common/errors"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
)
|
||||
|
||||
func NewCrypto(config CryptoConfig) *CryptoImpl {
|
||||
return &CryptoImpl{
|
||||
Config: config,
|
||||
}
|
||||
}
|
||||
|
||||
type CryptoConfig interface {
|
||||
AccessTokenSecret() string
|
||||
AccessTokenOrderSecret() string
|
||||
AccessTokenOrderExpiresDate() time.Time
|
||||
AccessTokenExpiresDate() time.Time
|
||||
AccessTokenResetPasswordSecret() string
|
||||
AccessTokenResetPasswordExpire() time.Time
|
||||
AccessTokenWithdrawSecret() string
|
||||
AccessTokenWithdrawExpire() time.Time
|
||||
AccessTokenCustomerSecret() string
|
||||
}
|
||||
|
||||
type CryptoImpl struct {
|
||||
Config CryptoConfig
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) CompareHashAndPassword(hash string, password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ValidateWT(tokenString string) (*jwt.Token, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(c.Config.AccessTokenSecret()), nil
|
||||
})
|
||||
|
||||
return token, err
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) GenerateJWT(user *entity.User) (string, error) {
|
||||
partnerID := int64(0)
|
||||
if user.PartnerID != nil {
|
||||
partnerID = *user.PartnerID
|
||||
}
|
||||
|
||||
siteID := int64(0)
|
||||
if user.SiteID != nil {
|
||||
siteID = *user.SiteID
|
||||
}
|
||||
|
||||
claims := &entity.JWTAuthClaims{
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
Subject: strconv.FormatInt(user.ID, 10),
|
||||
ExpiresAt: c.Config.AccessTokenExpiresDate().Unix(),
|
||||
IssuedAt: time.Now().Unix(),
|
||||
NotBefore: time.Now().Unix(),
|
||||
},
|
||||
UserID: user.ID,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
Role: int(user.RoleID),
|
||||
PartnerID: partnerID,
|
||||
SiteID: siteID,
|
||||
SiteName: user.SiteName,
|
||||
}
|
||||
|
||||
token, err := jwt.
|
||||
NewWithClaims(jwt.SigningMethodHS256, claims).
|
||||
SignedString([]byte(c.Config.AccessTokenSecret()))
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) GenerateJWTReseetPassword(user *entity.User) (string, error) {
|
||||
claims := &entity.JWTAuthClaims{
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
Subject: strconv.FormatInt(user.ID, 10),
|
||||
ExpiresAt: c.Config.AccessTokenResetPasswordExpire().Unix(),
|
||||
IssuedAt: time.Now().Unix(),
|
||||
NotBefore: time.Now().Unix(),
|
||||
},
|
||||
UserID: user.ID,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
}
|
||||
|
||||
token, err := jwt.
|
||||
NewWithClaims(jwt.SigningMethodHS256, claims).
|
||||
SignedString([]byte(c.Config.AccessTokenResetPasswordSecret()))
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ParseAndValidateJWT(tokenString string) (*entity.JWTAuthClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &entity.JWTAuthClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(c.Config.AccessTokenSecret()), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*entity.JWTAuthClaims); ok && token.Valid {
|
||||
return claims, nil
|
||||
} else {
|
||||
return nil, errors.ErrorUnauthorized
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ParseAndValidateJWTCustomer(tokenString string) (*entity.JWTAuthClaimsCustomer, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &entity.JWTAuthClaimsCustomer{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(c.Config.AccessTokenCustomerSecret()), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*entity.JWTAuthClaimsCustomer); ok && token.Valid {
|
||||
return claims, nil
|
||||
} else {
|
||||
return nil, errors.ErrorUnauthorized
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) GenerateJWTOrder(order *entity.Order) (string, error) {
|
||||
claims := &entity.JWTOrderClaims{
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
Subject: strconv.FormatInt(order.ID, 10),
|
||||
ExpiresAt: c.Config.AccessTokenOrderExpiresDate().Unix(),
|
||||
IssuedAt: time.Now().Unix(),
|
||||
NotBefore: time.Now().Unix(),
|
||||
},
|
||||
PartnerID: order.PartnerID,
|
||||
OrderID: order.ID,
|
||||
}
|
||||
|
||||
token, err := jwt.
|
||||
NewWithClaims(jwt.SigningMethodHS256, claims).
|
||||
SignedString([]byte(c.Config.AccessTokenOrderSecret()))
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) GenerateJWTOrderInquiry(inquiry *entity.OrderInquiry) (string, error) {
|
||||
claims := &entity.JWTOrderClaims{
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
Subject: inquiry.ID,
|
||||
ExpiresAt: c.Config.AccessTokenOrderExpiresDate().Unix(),
|
||||
IssuedAt: time.Now().Unix(),
|
||||
NotBefore: time.Now().Unix(),
|
||||
},
|
||||
PartnerID: inquiry.PartnerID,
|
||||
InquiryID: inquiry.ID,
|
||||
}
|
||||
|
||||
token, err := jwt.
|
||||
NewWithClaims(jwt.SigningMethodHS256, claims).
|
||||
SignedString([]byte(c.Config.AccessTokenOrderSecret()))
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ValidateJWTOrderInquiry(tokenString string) (int64, string, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &entity.JWTOrderClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(c.Config.AccessTokenOrderSecret()), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*entity.JWTOrderClaims)
|
||||
if !ok || !token.Valid {
|
||||
return 0, "", fmt.Errorf("invalid token %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return claims.PartnerID, claims.InquiryID, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ValidateJWTOrder(tokenString string) (int64, int64, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &entity.JWTOrderClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(c.Config.AccessTokenOrderSecret()), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*entity.JWTOrderClaims)
|
||||
if !ok || !token.Valid {
|
||||
return 0, 0, fmt.Errorf("invalid token %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return claims.PartnerID, claims.OrderID, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ValidateResetPassword(tokenString string) (int64, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &entity.JWTOrderClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(c.Config.AccessTokenResetPasswordSecret()), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*entity.JWTAuthClaims)
|
||||
if !ok || !token.Valid {
|
||||
return 0, fmt.Errorf("invalid token %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return claims.UserID, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) GenerateJWTWithdraw(req *entity.WalletWithdrawRequest) (string, error) {
|
||||
claims := &entity.JWTWithdrawClaims{
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
Subject: strconv.FormatInt(req.ID, 10),
|
||||
ExpiresAt: c.Config.AccessTokenWithdrawExpire().Unix(),
|
||||
IssuedAt: time.Now().Unix(),
|
||||
NotBefore: time.Now().Unix(),
|
||||
},
|
||||
PartnerID: req.PartnerID,
|
||||
Amount: req.Amount,
|
||||
Fee: req.Fee,
|
||||
Total: req.Total,
|
||||
}
|
||||
|
||||
token, err := jwt.
|
||||
NewWithClaims(jwt.SigningMethodHS256, claims).
|
||||
SignedString([]byte(c.Config.AccessTokenWithdrawSecret()))
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ValidateJWTWithdraw(tokenString string) (*entity.WalletWithdrawRequest, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &entity.JWTWithdrawClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(c.Config.AccessTokenWithdrawSecret()), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*entity.JWTWithdrawClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return &entity.WalletWithdrawRequest{
|
||||
ID: claims.ID,
|
||||
PartnerID: claims.PartnerID,
|
||||
Total: claims.Total,
|
||||
Amount: claims.Amount,
|
||||
Fee: claims.Fee,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) GenerateJWTCustomer(user *entity.Customer) (string, error) {
|
||||
claims := &entity.JWTAuthClaimsCustomer{
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
Subject: strconv.FormatInt(user.ID, 10),
|
||||
ExpiresAt: c.Config.AccessTokenExpiresDate().Unix(),
|
||||
IssuedAt: time.Now().Unix(),
|
||||
NotBefore: time.Now().Unix(),
|
||||
},
|
||||
UserID: user.ID,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
}
|
||||
|
||||
token, err := jwt.
|
||||
NewWithClaims(jwt.SigningMethodHS256, claims).
|
||||
SignedString([]byte(c.Config.AccessTokenCustomerSecret()))
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
@@ -1,387 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/models"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
type CustomerRepo interface {
|
||||
Create(ctx mycontext.Context, customer *entity.Customer) (*entity.Customer, error)
|
||||
FindByID(ctx mycontext.Context, id int64) (*entity.Customer, error)
|
||||
FindByPhone(ctx mycontext.Context, phone string) (*entity.Customer, error)
|
||||
FindByEmail(ctx mycontext.Context, email string) (*entity.Customer, error)
|
||||
AddPoints(ctx mycontext.Context, id int64, points int, reference string) error
|
||||
GetPointsByCustomerID(
|
||||
ctx mycontext.Context,
|
||||
customerID int64,
|
||||
) (*entity.CustomerPoints, error)
|
||||
FindSequence(ctx mycontext.Context, partnerID int64) (int64, error)
|
||||
GetAllCustomers(ctx mycontext.Context, req entity.MemberSearch) (entity.MemberList, int, error)
|
||||
VerifyOTP(ctx mycontext.Context, verificationHash string, otpCode string) (int64, error)
|
||||
}
|
||||
|
||||
type customerRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewCustomerRepository(db *gorm.DB) *customerRepository {
|
||||
return &customerRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *customerRepository) Create(ctx mycontext.Context, customer *entity.Customer) (*entity.Customer, error) {
|
||||
tx := r.db.Begin()
|
||||
if tx.Error != nil {
|
||||
return nil, errors.Wrap(tx.Error, "failed to begin transaction")
|
||||
}
|
||||
|
||||
customerDB := r.toCustomerDBModel(customer)
|
||||
if err := tx.Omit("CustomerID").Create(&customerDB).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return nil, errors.Wrap(err, "failed to insert customer")
|
||||
}
|
||||
|
||||
customerPoints := models.CustomerPointsDB{
|
||||
CustomerID: uint64(customerDB.ID),
|
||||
TotalPoints: 0,
|
||||
AvailablePoints: 0,
|
||||
LastUpdated: time.Now(),
|
||||
}
|
||||
|
||||
if err := tx.Create(&customerPoints).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return nil, errors.Wrap(err, "failed to create initial customer points")
|
||||
}
|
||||
|
||||
otpCode := r.generateOTPCode()
|
||||
expiresAt := time.Now().Add(15 * time.Minute)
|
||||
|
||||
verificationCode := models.CustomerVerificationCodeDB{
|
||||
CustomerID: uint64(customerDB.ID),
|
||||
Code: otpCode,
|
||||
Type: "EMAIL",
|
||||
ExpiresAt: expiresAt,
|
||||
IsUsed: false,
|
||||
VerificationID: uuid.New(),
|
||||
}
|
||||
|
||||
if err := tx.Create(&verificationCode).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return nil, errors.Wrap(err, "failed to create verification code")
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to commit transaction")
|
||||
}
|
||||
|
||||
customer.ID = customerDB.ID
|
||||
customer.VerificationID = verificationCode.VerificationID.String()
|
||||
customer.OTP = otpCode
|
||||
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
func (r *customerRepository) FindByID(ctx mycontext.Context, id int64) (*entity.Customer, error) {
|
||||
var customerDB models.CustomerDB
|
||||
|
||||
if err := r.db.First(&customerDB, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to find customer")
|
||||
}
|
||||
|
||||
customer := r.toDomainCustomerModel(&customerDB)
|
||||
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
func (r *customerRepository) FindByPhone(ctx mycontext.Context, phone string) (*entity.Customer, error) {
|
||||
var customerDB models.CustomerDB
|
||||
|
||||
if err := r.db.Where("phone = ?", phone).First(&customerDB).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to find customer by phone")
|
||||
}
|
||||
|
||||
customer := r.toDomainCustomerModel(&customerDB)
|
||||
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
func (r *customerRepository) FindByEmail(ctx mycontext.Context, email string) (*entity.Customer, error) {
|
||||
var customerDB models.CustomerDB
|
||||
|
||||
if err := r.db.Where("email = ?", email).First(&customerDB).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to find customer by email")
|
||||
}
|
||||
|
||||
customer := r.toDomainCustomerModel(&customerDB)
|
||||
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
func (r *customerRepository) AddPoints(ctx mycontext.Context, customerID int64, points int, reference string) error {
|
||||
tx := r.db.Begin()
|
||||
if tx.Error != nil {
|
||||
return errors.Wrap(tx.Error, "failed to begin transaction")
|
||||
}
|
||||
|
||||
result := tx.Model(&models.CustomerPointsDB{}).
|
||||
Where("customer_id = ?", customerID).
|
||||
Updates(map[string]interface{}{
|
||||
"total_points": gorm.Expr("total_points + ?", points),
|
||||
"available_points": gorm.Expr("available_points + ?", points),
|
||||
"last_updated": time.Now(),
|
||||
})
|
||||
|
||||
if result.Error != nil {
|
||||
tx.Rollback()
|
||||
return errors.Wrap(result.Error, "failed to update customer points")
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
tx.Rollback()
|
||||
return errors.New("customer points record not found")
|
||||
}
|
||||
|
||||
pointTransaction := models.CustomerPointTransactionDB{
|
||||
CustomerID: customerID,
|
||||
Reference: reference,
|
||||
PointsEarned: points,
|
||||
TransactionDate: time.Now(),
|
||||
Status: "active",
|
||||
}
|
||||
|
||||
if err := tx.Create(&pointTransaction).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return errors.Wrap(err, "failed to create point transaction record")
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return errors.Wrap(err, "failed to commit transaction")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *customerRepository) GetPointsByCustomerID(
|
||||
ctx mycontext.Context,
|
||||
customerID int64,
|
||||
) (*entity.CustomerPoints, error) {
|
||||
var cp models.CustomerPointsDB
|
||||
|
||||
if err := r.db.Where("customer_id = ?", customerID).First(&cp).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to find customer point by customer_id")
|
||||
}
|
||||
|
||||
return r.toDomainCustomerPoint(cp), nil
|
||||
}
|
||||
|
||||
func (r *customerRepository) toDomainCustomerPoint(dbModel models.CustomerPointsDB) *entity.CustomerPoints {
|
||||
return &entity.CustomerPoints{
|
||||
ID: dbModel.ID,
|
||||
CustomerID: dbModel.CustomerID,
|
||||
TotalPoints: dbModel.TotalPoints,
|
||||
AvailablePoints: dbModel.AvailablePoints,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *customerRepository) toCustomerDBModel(customer *entity.Customer) models.CustomerDB {
|
||||
return models.CustomerDB{
|
||||
ID: customer.ID,
|
||||
Name: customer.Name,
|
||||
Email: customer.Email,
|
||||
Phone: customer.Phone,
|
||||
Points: customer.Points,
|
||||
CreatedAt: customer.CreatedAt,
|
||||
UpdatedAt: customer.UpdatedAt,
|
||||
BirthDate: customer.BirthDate,
|
||||
Password: customer.Password,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *customerRepository) FindSequence(ctx mycontext.Context, partnerID int64) (int64, error) {
|
||||
tx := r.db.Begin()
|
||||
if tx.Error != nil {
|
||||
return 0, errors.Wrap(tx.Error, "failed to begin transaction")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
var sequence models.PartnerMemberSequence
|
||||
|
||||
result := tx.Where("partner_id = ?", partnerID).First(&sequence)
|
||||
if result.Error != nil {
|
||||
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
||||
now := time.Now()
|
||||
newSequence := models.PartnerMemberSequence{
|
||||
PartnerID: partnerID,
|
||||
LastSequence: 1,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
if err := tx.Create(&newSequence).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return 0, errors.Wrap(err, "failed to create new sequence")
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return 0, errors.Wrap(err, "failed to commit transaction")
|
||||
}
|
||||
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
tx.Rollback()
|
||||
return 0, errors.Wrap(result.Error, "failed to query sequence")
|
||||
}
|
||||
|
||||
newSequenceValue := sequence.LastSequence + 1
|
||||
updates := map[string]interface{}{
|
||||
"last_sequence": newSequenceValue,
|
||||
"updated_at": time.Now(),
|
||||
}
|
||||
|
||||
if err := tx.Model(&sequence).Updates(updates).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return 0, errors.Wrap(err, "failed to update sequence")
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return 0, errors.Wrap(err, "failed to commit transaction")
|
||||
}
|
||||
|
||||
return newSequenceValue, nil
|
||||
}
|
||||
|
||||
func (r *customerRepository) toDomainCustomerModel(dbModel *models.CustomerDB) *entity.Customer {
|
||||
return &entity.Customer{
|
||||
ID: dbModel.ID,
|
||||
Name: dbModel.Name,
|
||||
Email: dbModel.Email,
|
||||
Phone: dbModel.Phone,
|
||||
Points: dbModel.Points,
|
||||
CreatedAt: dbModel.CreatedAt,
|
||||
UpdatedAt: dbModel.UpdatedAt,
|
||||
CustomerID: dbModel.CustomerID,
|
||||
BirthDate: dbModel.BirthDate,
|
||||
Password: dbModel.Password,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *customerRepository) GetAllCustomers(ctx mycontext.Context, req entity.MemberSearch) (entity.MemberList, int, error) {
|
||||
if req.Limit <= 0 {
|
||||
req.Limit = 10
|
||||
}
|
||||
if req.Offset < 0 {
|
||||
req.Offset = 0
|
||||
}
|
||||
|
||||
query := r.db.Model(&models.CustomerDB{})
|
||||
|
||||
if req.Search != "" {
|
||||
searchTerm := "%" + req.Search + "%"
|
||||
query = query.Where(
|
||||
"name ILIKE ? OR email ILIKE ? OR phone ILIKE ?",
|
||||
searchTerm, searchTerm, searchTerm,
|
||||
)
|
||||
}
|
||||
|
||||
var totalCount int64
|
||||
if err := query.Count(&totalCount).Error; err != nil {
|
||||
return nil, 0, errors.Wrap(err, "failed to count customers")
|
||||
}
|
||||
|
||||
var customersDB []models.CustomerDB
|
||||
result := query.
|
||||
Order("created_at DESC").
|
||||
Limit(req.Limit).
|
||||
Offset(req.Offset).
|
||||
Find(&customersDB)
|
||||
|
||||
if result.Error != nil {
|
||||
return nil, 0, errors.Wrap(result.Error, "failed to retrieve customers")
|
||||
}
|
||||
|
||||
customers := make(entity.MemberList, len(customersDB))
|
||||
for i, customerDB := range customersDB {
|
||||
customers[i] = r.toDomainCustomerModel(&customerDB)
|
||||
}
|
||||
|
||||
return customers, int(totalCount), nil
|
||||
}
|
||||
|
||||
func (r *customerRepository) generateOTPCode() string {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
otpCode := fmt.Sprintf("%06d", rand.Intn(1000000))
|
||||
return otpCode
|
||||
}
|
||||
|
||||
func (r *customerRepository) VerifyOTP(ctx mycontext.Context, verificationHash string, otpCode string) (int64, error) {
|
||||
var verificationCode models.CustomerVerificationCodeDB
|
||||
if err := r.db.Where("verification_id = ? AND is_used = false", verificationHash).First(&verificationCode).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return 0, errors.New("invalid or expired verification code")
|
||||
}
|
||||
return 0, errors.Wrap(err, "failed to find verification code")
|
||||
}
|
||||
|
||||
if time.Now().After(verificationCode.ExpiresAt) {
|
||||
return 0, errors.New("verification code has expired")
|
||||
}
|
||||
|
||||
if verificationCode.Code != otpCode {
|
||||
return 0, errors.New("invalid verification code")
|
||||
}
|
||||
|
||||
tx := r.db.Begin()
|
||||
if tx.Error != nil {
|
||||
return 0, errors.Wrap(tx.Error, "failed to begin transaction")
|
||||
}
|
||||
|
||||
if err := tx.Model(&verificationCode).Updates(map[string]interface{}{
|
||||
"is_used": true,
|
||||
}).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return 0, errors.Wrap(err, "failed to mark verification code as used")
|
||||
}
|
||||
|
||||
if verificationCode.Type == "EMAIL" {
|
||||
if err := tx.Model(&models.CustomerDB{}).Where("id = ?", verificationCode.CustomerID).
|
||||
Update("is_email_verified", true).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return 0, errors.Wrap(err, "failed to update customer verification status")
|
||||
}
|
||||
} else if verificationCode.Type == "PHONE" {
|
||||
if err := tx.Model(&models.CustomerDB{}).Where("id = ?", verificationCode.CustomerID).
|
||||
Update("is_phone_verified", true).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return 0, errors.Wrap(err, "failed to update customer verification status")
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return 0, errors.Wrap(err, "failed to commit transaction")
|
||||
}
|
||||
|
||||
return int64(verificationCode.CustomerID), nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/entities"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CustomerRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewCustomerRepository(db *gorm.DB) *CustomerRepository {
|
||||
return &CustomerRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) Create(ctx context.Context, customer *entities.Customer) error {
|
||||
return r.db.WithContext(ctx).Create(customer).Error
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) GetByID(ctx context.Context, id uuid.UUID) (*entities.Customer, error) {
|
||||
var customer entities.Customer
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&customer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &customer, nil
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) GetByIDAndOrganization(ctx context.Context, id, organizationID uuid.UUID) (*entities.Customer, error) {
|
||||
var customer entities.Customer
|
||||
err := r.db.WithContext(ctx).Where("id = ? AND organization_id = ?", id, organizationID).First(&customer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &customer, nil
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) GetDefaultCustomer(ctx context.Context, organizationID uuid.UUID) (*entities.Customer, error) {
|
||||
var customer entities.Customer
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ? AND is_default = ?", organizationID, true).First(&customer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &customer, nil
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) List(ctx context.Context, organizationID uuid.UUID, offset, limit int, search string, isActive, isDefault *bool, sortBy, sortOrder string) ([]entities.Customer, int64, error) {
|
||||
var customers []entities.Customer
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Where("organization_id = ?", organizationID)
|
||||
|
||||
if search != "" {
|
||||
searchTerm := "%" + search + "%"
|
||||
query = query.Where("name ILIKE ? OR email ILIKE ? OR phone ILIKE ?", searchTerm, searchTerm, searchTerm)
|
||||
}
|
||||
|
||||
if isActive != nil {
|
||||
query = query.Where("is_active = ?", *isActive)
|
||||
}
|
||||
|
||||
if isDefault != nil {
|
||||
query = query.Where("is_default = ?", *isDefault)
|
||||
}
|
||||
|
||||
if err := query.Model(&entities.Customer{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if sortBy != "" {
|
||||
if sortOrder == "" {
|
||||
sortOrder = "asc"
|
||||
}
|
||||
query = query.Order(fmt.Sprintf("%s %s", sortBy, sortOrder))
|
||||
} else {
|
||||
query = query.Order("created_at DESC")
|
||||
}
|
||||
|
||||
err := query.Offset(offset).Limit(limit).Find(&customers).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return customers, total, nil
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) Update(ctx context.Context, customer *entities.Customer) error {
|
||||
return r.db.WithContext(ctx).Save(customer).Error
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.Customer{}, id).Error
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) SetAsDefault(ctx context.Context, customerID, organizationID uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&entities.Customer{}).
|
||||
Where("organization_id = ? AND is_default = ?", organizationID, true).
|
||||
Update("is_default", false).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Model(&entities.Customer{}).
|
||||
Where("id = ? AND organization_id = ?", customerID, organizationID).
|
||||
Update("is_default", true).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) CreateDefaultCustomer(ctx context.Context, organizationID uuid.UUID) (*entities.Customer, error) {
|
||||
defaultCustomer := &entities.Customer{
|
||||
OrganizationID: organizationID,
|
||||
Name: "Walk In Customer",
|
||||
IsDefault: true,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
err := r.db.WithContext(ctx).Create(defaultCustomer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return defaultCustomer, nil
|
||||
}
|
||||
|
||||
func (r *CustomerRepository) GetByEmail(ctx context.Context, email string, organizationID uuid.UUID) (*entities.Customer, error) {
|
||||
var customer entities.Customer
|
||||
err := r.db.WithContext(ctx).Where("email = ? AND organization_id = ?", email, organizationID).First(&customer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &customer, nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type FileRepository interface {
|
||||
Create(ctx context.Context, file *entities.File) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*entities.File, error)
|
||||
GetByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.File, error)
|
||||
GetByUserID(ctx context.Context, userID uuid.UUID) ([]*entities.File, error)
|
||||
Update(ctx context.Context, file *entities.File) error
|
||||
Delete(ctx context.Context, id uuid.UUID) error
|
||||
List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.File, int64, error)
|
||||
GetByFileName(ctx context.Context, fileName string) (*entities.File, error)
|
||||
ExistsByFileName(ctx context.Context, fileName string) (bool, error)
|
||||
}
|
||||
|
||||
type FileRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewFileRepositoryImpl(db *gorm.DB) *FileRepositoryImpl {
|
||||
return &FileRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) Create(ctx context.Context, file *entities.File) error {
|
||||
return r.db.WithContext(ctx).Create(file).Error
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.File, error) {
|
||||
var file entities.File
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&file).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &file, nil
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) GetByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.File, error) {
|
||||
var files []*entities.File
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ?", organizationID).Find(&files).Error
|
||||
return files, err
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) GetByUserID(ctx context.Context, userID uuid.UUID) ([]*entities.File, error) {
|
||||
var files []*entities.File
|
||||
err := r.db.WithContext(ctx).Where("user_id = ?", userID).Find(&files).Error
|
||||
return files, err
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) Update(ctx context.Context, file *entities.File) error {
|
||||
return r.db.WithContext(ctx).Save(file).Error
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entities.File{}).Error
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.File, int64, error) {
|
||||
var files []*entities.File
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.File{})
|
||||
|
||||
// Apply filters
|
||||
for key, value := range filters {
|
||||
if value != nil && value != "" {
|
||||
query = query.Where(fmt.Sprintf("%s = ?", key), value)
|
||||
}
|
||||
}
|
||||
|
||||
// Get total count
|
||||
err := query.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Get paginated results
|
||||
err = query.Offset(offset).Limit(limit).Order("created_at DESC").Find(&files).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return files, total, nil
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) GetByFileName(ctx context.Context, fileName string) (*entities.File, error) {
|
||||
var file entities.File
|
||||
err := r.db.WithContext(ctx).Where("file_name = ?", fileName).First(&file).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &file, nil
|
||||
}
|
||||
|
||||
func (r *FileRepositoryImpl) ExistsByFileName(ctx context.Context, fileName string) (bool, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&entities.File{}).Where("file_name = ?", fileName).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type InventoryRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewInventoryRepositoryImpl(db *gorm.DB) *InventoryRepositoryImpl {
|
||||
return &InventoryRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) Create(ctx context.Context, inventory *entities.Inventory) error {
|
||||
return r.db.WithContext(ctx).Create(inventory).Error
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.Inventory, error) {
|
||||
var inventory entities.Inventory
|
||||
err := r.db.WithContext(ctx).First(&inventory, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &inventory, nil
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) GetWithRelations(ctx context.Context, id uuid.UUID) (*entities.Inventory, error) {
|
||||
var inventory entities.Inventory
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Product").
|
||||
Preload("Product.Category").
|
||||
Preload("Outlet").
|
||||
First(&inventory, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &inventory, nil
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) GetByProductAndOutlet(ctx context.Context, productID, outletID uuid.UUID) (*entities.Inventory, error) {
|
||||
var inventory entities.Inventory
|
||||
err := r.db.WithContext(ctx).Where("product_id = ? AND outlet_id = ?", productID, outletID).First(&inventory).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &inventory, nil
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) GetByOutlet(ctx context.Context, outletID uuid.UUID) ([]*entities.Inventory, error) {
|
||||
var inventory []*entities.Inventory
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Product").
|
||||
Preload("Product.Category").
|
||||
Where("outlet_id = ?", outletID).
|
||||
Find(&inventory).Error
|
||||
return inventory, err
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) GetByProduct(ctx context.Context, productID uuid.UUID) ([]*entities.Inventory, error) {
|
||||
var inventory []*entities.Inventory
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Outlet").
|
||||
Where("product_id = ?", productID).
|
||||
Find(&inventory).Error
|
||||
return inventory, err
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) GetLowStock(ctx context.Context, outletID uuid.UUID) ([]*entities.Inventory, error) {
|
||||
var inventory []*entities.Inventory
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Product").
|
||||
Preload("Product.Category").
|
||||
Where("outlet_id = ? AND quantity <= reorder_level", outletID).
|
||||
Find(&inventory).Error
|
||||
return inventory, err
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) GetZeroStock(ctx context.Context, outletID uuid.UUID) ([]*entities.Inventory, error) {
|
||||
var inventory []*entities.Inventory
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Product").
|
||||
Preload("Product.Category").
|
||||
Where("outlet_id = ? AND quantity = 0", outletID).
|
||||
Find(&inventory).Error
|
||||
return inventory, err
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) Update(ctx context.Context, inventory *entities.Inventory) error {
|
||||
return r.db.WithContext(ctx).Save(inventory).Error
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.Inventory{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.Inventory, int64, error) {
|
||||
var inventory []*entities.Inventory
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.Inventory{}).
|
||||
Preload("Product").
|
||||
Preload("Product.Category").
|
||||
Preload("Outlet")
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Joins("JOIN products ON inventory.product_id = products.id").
|
||||
Where("products.name ILIKE ? OR products.sku ILIKE ?", searchValue, searchValue)
|
||||
case "low_stock":
|
||||
if value.(bool) {
|
||||
query = query.Where("quantity <= reorder_level")
|
||||
}
|
||||
case "zero_stock":
|
||||
if value.(bool) {
|
||||
query = query.Where("quantity = 0")
|
||||
}
|
||||
case "category_id":
|
||||
query = query.Joins("JOIN products ON inventory.product_id = products.id").
|
||||
Where("products.category_id = ?", value)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Find(&inventory).Error
|
||||
return inventory, total, err
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.Inventory{})
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Joins("JOIN products ON inventory.product_id = products.id").
|
||||
Where("products.name ILIKE ? OR products.sku ILIKE ?", searchValue, searchValue)
|
||||
case "low_stock":
|
||||
if value.(bool) {
|
||||
query = query.Where("quantity <= reorder_level")
|
||||
}
|
||||
case "zero_stock":
|
||||
if value.(bool) {
|
||||
query = query.Where("quantity = 0")
|
||||
}
|
||||
case "category_id":
|
||||
query = query.Joins("JOIN products ON inventory.product_id = products.id").
|
||||
Where("products.category_id = ?", value)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) AdjustQuantity(ctx context.Context, productID, outletID uuid.UUID, delta int) (*entities.Inventory, error) {
|
||||
var inventory entities.Inventory
|
||||
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// 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 fmt.Errorf("failed to create inventory record: %w", err)
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
inventory.UpdateQuantity(delta)
|
||||
return tx.Save(&inventory).Error
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &inventory, nil
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) SetQuantity(ctx context.Context, productID, outletID uuid.UUID, quantity int) (*entities.Inventory, error) {
|
||||
var inventory entities.Inventory
|
||||
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// Get current 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 the specified quantity
|
||||
inventory = entities.Inventory{
|
||||
ProductID: productID,
|
||||
OutletID: outletID,
|
||||
Quantity: quantity,
|
||||
ReorderLevel: 0,
|
||||
}
|
||||
if inventory.Quantity < 0 {
|
||||
inventory.Quantity = 0
|
||||
}
|
||||
if err := tx.Create(&inventory).Error; err != nil {
|
||||
return fmt.Errorf("failed to create inventory record: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Set new quantity
|
||||
inventory.Quantity = quantity
|
||||
if inventory.Quantity < 0 {
|
||||
inventory.Quantity = 0
|
||||
}
|
||||
|
||||
// Save updated inventory
|
||||
return tx.Save(&inventory).Error
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &inventory, nil
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) UpdateReorderLevel(ctx context.Context, id uuid.UUID, reorderLevel int) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.Inventory{}).
|
||||
Where("id = ?", id).
|
||||
Update("reorder_level", reorderLevel).Error
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) BulkCreate(ctx context.Context, inventoryItems []*entities.Inventory) error {
|
||||
return r.db.WithContext(ctx).CreateInBatches(inventoryItems, 100).Error
|
||||
}
|
||||
|
||||
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 {
|
||||
var inventory entities.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 fmt.Errorf("failed to create inventory record for product %s: %w", productID, err)
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
inventory.UpdateQuantity(delta)
|
||||
|
||||
if err := tx.Save(&inventory).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *InventoryRepositoryImpl) GetTotalValueByOutlet(ctx context.Context, outletID uuid.UUID) (float64, error) {
|
||||
var totalValue float64
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("inventory").
|
||||
Select("SUM(inventory.quantity * products.cost)").
|
||||
Joins("JOIN products ON inventory.product_id = products.id").
|
||||
Where("inventory.outlet_id = ?", outletID).
|
||||
Scan(&totalValue).Error
|
||||
|
||||
return totalValue, err
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package license
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LicenseRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewLicenseRepository(db *gorm.DB) *LicenseRepository {
|
||||
return &LicenseRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *LicenseRepository) Create(ctx context.Context, license *entity.LicenseDB) (*entity.LicenseDB, error) {
|
||||
if err := r.db.WithContext(ctx).Create(license).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when creating license", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return license, nil
|
||||
}
|
||||
|
||||
func (r *LicenseRepository) Update(ctx context.Context, license *entity.LicenseDB) (*entity.LicenseDB, error) {
|
||||
if err := r.db.WithContext(ctx).Save(license).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating license", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return license, nil
|
||||
}
|
||||
|
||||
func (r *LicenseRepository) FindByID(ctx context.Context, id string) (*entity.LicenseDB, error) {
|
||||
licenseID, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
license := new(entity.LicenseDB)
|
||||
if err := r.db.WithContext(ctx).First(license, licenseID).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding license by ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return license, nil
|
||||
}
|
||||
|
||||
func (r *LicenseRepository) GetAll(ctx context.Context, limit, offset int, statusFilter string) ([]*entity.LicenseGetAll, int64, error) {
|
||||
var licenses []*entity.LicenseGetAll
|
||||
var total int64
|
||||
|
||||
// Define the main query with status calculation and days to expire
|
||||
subQuery := r.db.WithContext(ctx).
|
||||
Table("licenses").
|
||||
Select(`licenses.*, partners.name as partner_name,
|
||||
CASE
|
||||
WHEN licenses.end_date < CURRENT_DATE THEN 'EXPIRED'
|
||||
WHEN licenses.end_date < CURRENT_DATE + INTERVAL '30 days' THEN 'EXPIRING_SOON'
|
||||
ELSE 'ACTIVE'
|
||||
END as license_status,
|
||||
(GREATEST(licenses.end_date - CURRENT_DATE, 0)) as days_to_expire,
|
||||
users.name as created_by_name`).
|
||||
Joins("LEFT JOIN partners ON licenses.partner_id = partners.id").
|
||||
Joins("LEFT JOIN users ON licenses.created_by = users.id")
|
||||
|
||||
// Wrap the main query as a subquery to filter by status and apply pagination
|
||||
query := r.db.Table("(?) as sub", subQuery)
|
||||
if statusFilter != "" {
|
||||
query = query.Where("license_status = ?", statusFilter)
|
||||
}
|
||||
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
if offset > 0 {
|
||||
query = query.Offset(offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&licenses).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Get the total count of records matching the filter
|
||||
countQuery := r.db.Table("(?) as sub", subQuery)
|
||||
if statusFilter != "" {
|
||||
countQuery = countQuery.Where("license_status = ?", statusFilter)
|
||||
}
|
||||
|
||||
if err := countQuery.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return licenses, total, nil
|
||||
}
|
||||
|
||||
func (r *LicenseRepository) FindByPartnerIDMaxEndDate(ctx context.Context, partnerID *int64) (*entity.LicenseDB, error) {
|
||||
var licenseDB entity.LicenseDB
|
||||
|
||||
today := time.Now().Format("2006-01-02")
|
||||
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("partner_id = ?", partnerID).
|
||||
Where("start_date <= ?", today).
|
||||
Where("end_date >= ?", today).
|
||||
Order("end_date DESC").
|
||||
First(&licenseDB).Error; err != nil {
|
||||
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &licenseDB, nil
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
package linkqu
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LinkQuConfig interface {
|
||||
LinkQuBaseURL() string
|
||||
LinkQuClientID() string
|
||||
LinkQuClientSecret() string
|
||||
LinkQuSignatureKey() string
|
||||
LinkQuUsername() string
|
||||
LinkQuPIN() string
|
||||
LinkQuCallbackURL() string
|
||||
}
|
||||
|
||||
type LinkQuService struct {
|
||||
config LinkQuConfig
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type CreateQRISRequest struct {
|
||||
Amount int64 `json:"amount"`
|
||||
PartnerReff string `json:"partner_reff"`
|
||||
CustomerID string `json:"customer_id"`
|
||||
CustomerName string `json:"customer_name"`
|
||||
Expired string `json:"expired"`
|
||||
Username string `json:"username"`
|
||||
Pin string `json:"pin"`
|
||||
CustomerPhone string `json:"customer_phone"`
|
||||
CustomerEmail string `json:"customer_email"`
|
||||
Signature string `json:"signature"`
|
||||
ClientID string `json:"client_id"`
|
||||
URLCallback string `json:"url_callback"`
|
||||
}
|
||||
|
||||
type CreateVARequest struct {
|
||||
Amount int64 `json:"amount"`
|
||||
PartnerReff string `json:"partner_reff"`
|
||||
CustomerID string `json:"customer_id"`
|
||||
CustomerName string `json:"customer_name"`
|
||||
Expired string `json:"expired"`
|
||||
Username string `json:"username"`
|
||||
Pin string `json:"pin"`
|
||||
CustomerPhone string `json:"customer_phone"`
|
||||
CustomerEmail string `json:"customer_email"`
|
||||
Signature string `json:"signature"`
|
||||
ClientID string `json:"client_id"`
|
||||
URLCallback string `json:"url_callback"`
|
||||
BankCode string `json:"bank_code"`
|
||||
}
|
||||
|
||||
func NewLinkQuService(config LinkQuConfig) *LinkQuService {
|
||||
return &LinkQuService{
|
||||
config: config,
|
||||
client: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *LinkQuService) constructQRISPayload(req entity.LinkQuRequest) CreateQRISRequest {
|
||||
return CreateQRISRequest{
|
||||
Amount: req.TotalAmount,
|
||||
PartnerReff: req.PaymentReferenceID,
|
||||
CustomerID: req.CustomerID,
|
||||
CustomerName: req.CustomerName,
|
||||
Expired: time.Now().Add(1 * time.Hour).Format("20060102150405"),
|
||||
Username: s.config.LinkQuUsername(),
|
||||
Pin: s.config.LinkQuPIN(),
|
||||
CustomerPhone: req.CustomerPhone,
|
||||
CustomerEmail: req.CustomerEmail,
|
||||
ClientID: s.config.LinkQuClientID(),
|
||||
URLCallback: s.config.LinkQuCallbackURL(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *LinkQuService) constructVAPayload(req entity.LinkQuRequest) CreateVARequest {
|
||||
return CreateVARequest{
|
||||
Amount: req.TotalAmount,
|
||||
PartnerReff: req.PaymentReferenceID,
|
||||
CustomerID: req.CustomerID,
|
||||
CustomerName: req.CustomerName,
|
||||
Expired: time.Now().Add(1 * time.Hour).Format("20060102150405"),
|
||||
Username: s.config.LinkQuUsername(),
|
||||
Pin: s.config.LinkQuPIN(),
|
||||
CustomerPhone: req.CustomerPhone,
|
||||
CustomerEmail: req.CustomerEmail,
|
||||
ClientID: s.config.LinkQuClientID(),
|
||||
URLCallback: s.config.LinkQuCallbackURL(),
|
||||
BankCode: req.BankCode,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *LinkQuService) CreateQrisPayment(linkQuRequest entity.LinkQuRequest) (*entity.LinkQuQRISResponse, error) {
|
||||
path := "/transaction/create/qris"
|
||||
method := "POST"
|
||||
|
||||
req := s.constructQRISPayload(linkQuRequest)
|
||||
|
||||
if req.Expired == "" {
|
||||
req.Expired = time.Now().Add(1 * time.Hour).Format("20060102150405")
|
||||
}
|
||||
|
||||
paramOrder := []string{"Amount", "Expired", "PartnerReff", "CustomerID", "CustomerName", "CustomerEmail", "ClientID"}
|
||||
|
||||
signature, err := s.generateSignature(path, method, req, paramOrder)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate signature: %w", err)
|
||||
}
|
||||
req.Signature = signature
|
||||
|
||||
reqBody, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal request body: %w", err)
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("%s/%s%s", s.config.LinkQuBaseURL(), "linkqu-partner", path)
|
||||
httpReq, err := http.NewRequest(method, url, bytes.NewBuffer(reqBody))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create HTTP request: %w", err)
|
||||
}
|
||||
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("client-id", s.config.LinkQuClientID())
|
||||
httpReq.Header.Set("client-secret", s.config.LinkQuClientSecret())
|
||||
|
||||
resp, err := s.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Read response body
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
// Check for non-200 status code
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("unexpected status code: %d, body: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var qrisResp entity.LinkQuQRISResponse
|
||||
if err := json.Unmarshal(body, &qrisResp); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
if qrisResp.ResponseCode != "00" {
|
||||
return nil, fmt.Errorf("error when create qris linkqu, status code %s , %s", qrisResp.ResponseCode, qrisResp.ResponseDesc)
|
||||
}
|
||||
|
||||
return &qrisResp, nil
|
||||
}
|
||||
|
||||
func (s *LinkQuService) CreatePaymentVA(linkQuRequest entity.LinkQuRequest) (*entity.LinkQuPaymentVAResponse, error) {
|
||||
path := "/transaction/create/va"
|
||||
method := "POST"
|
||||
|
||||
req := s.constructVAPayload(linkQuRequest)
|
||||
|
||||
if req.Expired == "" {
|
||||
req.Expired = time.Now().Add(1 * time.Hour).Format("20060102150405")
|
||||
}
|
||||
|
||||
paramOrder := []string{"Amount", "Expired", "BankCode", "PartnerReff", "CustomerID", "CustomerName", "CustomerEmail", "ClientID"}
|
||||
|
||||
signature, err := s.generateSignature(path, method, req, paramOrder)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate signature: %w", err)
|
||||
}
|
||||
req.Signature = signature
|
||||
|
||||
reqBody, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal request body: %w", err)
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("%s/%s%s", s.config.LinkQuBaseURL(), "linkqu-partner", path)
|
||||
httpReq, err := http.NewRequest(method, url, bytes.NewBuffer(reqBody))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create HTTP request: %w", err)
|
||||
}
|
||||
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("client-id", s.config.LinkQuClientID())
|
||||
httpReq.Header.Set("client-secret", s.config.LinkQuClientSecret())
|
||||
|
||||
resp, err := s.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Read response body
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
// Check for non-200 status code
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("unexpected status code: %d, body: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var qrisResp entity.LinkQuPaymentVAResponse
|
||||
if err := json.Unmarshal(body, &qrisResp); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
if qrisResp.ResponseCode != "00" {
|
||||
return nil, fmt.Errorf("error when create qris linkqu, status code %s", qrisResp.ResponseCode)
|
||||
}
|
||||
|
||||
return &qrisResp, nil
|
||||
}
|
||||
|
||||
func (s *LinkQuService) generateSignature(path, method string, req interface{}, paramOrder []string) (string, error) {
|
||||
var values []string
|
||||
reqValue := reflect.ValueOf(req)
|
||||
|
||||
for _, param := range paramOrder {
|
||||
field := reqValue.FieldByNameFunc(func(fieldName string) bool {
|
||||
return strings.EqualFold(fieldName, param)
|
||||
})
|
||||
|
||||
if field.IsValid() {
|
||||
values = append(values, fmt.Sprintf("%v", field.Interface()))
|
||||
} else {
|
||||
return "", fmt.Errorf("field %s not found in request struct", param)
|
||||
}
|
||||
}
|
||||
|
||||
secondValue := strings.Join(values, "")
|
||||
secondValue = cleanString(secondValue)
|
||||
|
||||
signToString := path + method + secondValue
|
||||
|
||||
h := hmac.New(sha256.New, []byte(s.config.LinkQuSignatureKey()))
|
||||
h.Write([]byte(signToString))
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func cleanString(s string) string {
|
||||
reg := regexp.MustCompile("[^a-zA-Z0-9]+")
|
||||
return strings.ToLower(reg.ReplaceAllString(s, ""))
|
||||
}
|
||||
|
||||
func (s *LinkQuService) CheckPaymentStatus(partnerReff string) (*entity.LinkQuCheckStatusResponse, error) {
|
||||
path := "/transaction/payment/checkstatus"
|
||||
method := "GET"
|
||||
|
||||
url := fmt.Sprintf("%s%s%s?username=%s&partnerreff=%s",
|
||||
s.config.LinkQuBaseURL(), "/linkqu-partner", path, s.config.LinkQuUsername(), partnerReff)
|
||||
|
||||
httpReq, err := http.NewRequest(method, url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create HTTP request: %w", err)
|
||||
}
|
||||
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("client-id", s.config.LinkQuClientID())
|
||||
httpReq.Header.Set("client-secret", s.config.LinkQuClientSecret())
|
||||
|
||||
resp, err := s.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("unexpected status code: %d, body: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var checkStatusResp entity.LinkQuCheckStatusResponse
|
||||
if err := json.Unmarshal(body, &checkStatusResp); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
if checkStatusResp.ResponseCode != "00" {
|
||||
return nil, fmt.Errorf("error when checking payment status, status code %s", checkStatusResp.ResponseCode)
|
||||
}
|
||||
|
||||
return &checkStatusResp, nil
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/constants"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/models"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type MemberRepository interface {
|
||||
CreateRegistration(ctx mycontext.Context, registration *entity.MemberRegistration) (*entity.MemberRegistration, error)
|
||||
GetRegistrationByToken(ctx mycontext.Context, token string) (*entity.MemberRegistration, error)
|
||||
UpdateRegistrationStatus(ctx mycontext.Context, token string, status constants.RegistrationStatus) error
|
||||
UpdateRegistrationOTP(ctx mycontext.Context, token string, otp string, expiresAt time.Time) error
|
||||
}
|
||||
|
||||
type memberRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewMemberRepository(db *gorm.DB) MemberRepository {
|
||||
return &memberRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *memberRepository) CreateRegistration(ctx mycontext.Context, registration *entity.MemberRegistration) (*entity.MemberRegistration, error) {
|
||||
registrationDB := r.toRegistrationDBModel(registration)
|
||||
|
||||
if err := r.db.Create(®istrationDB).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("failed to create member registration", zap.Error(err))
|
||||
return nil, errors.New("failed to insert member registration")
|
||||
}
|
||||
|
||||
return registration, nil
|
||||
}
|
||||
|
||||
func (r *memberRepository) GetRegistrationByToken(ctx mycontext.Context, token string) (*entity.MemberRegistration, error) {
|
||||
var registrationDB models.MemberRegistrationDB
|
||||
|
||||
if err := r.db.Where("token = ?", token).First(®istrationDB).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("registration not found")
|
||||
}
|
||||
logger.ContextLogger(ctx).Error("failed to get registration by token", zap.Error(err))
|
||||
return nil, errors.New("failed to get registration by token")
|
||||
}
|
||||
|
||||
registration := r.toDomainRegistrationModel(®istrationDB)
|
||||
return registration, nil
|
||||
}
|
||||
|
||||
func (r *memberRepository) UpdateRegistrationStatus(ctx mycontext.Context, token string, status constants.RegistrationStatus) error {
|
||||
now := time.Now()
|
||||
|
||||
result := r.db.Model(&models.MemberRegistrationDB{}).
|
||||
Where("token = ?", token).
|
||||
Updates(map[string]interface{}{
|
||||
"status": status,
|
||||
"updated_at": now,
|
||||
})
|
||||
|
||||
if result.Error != nil {
|
||||
logger.ContextLogger(ctx).Error("failed to update registration status", zap.Error(result.Error))
|
||||
return errors.New("failed to update registration status")
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("registration not found")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *memberRepository) UpdateRegistrationOTP(ctx mycontext.Context, token string, otp string, expiresAt time.Time) error {
|
||||
now := time.Now()
|
||||
|
||||
result := r.db.Model(&models.MemberRegistrationDB{}).
|
||||
Where("token = ?", token).
|
||||
Updates(map[string]interface{}{
|
||||
"otp": otp,
|
||||
"expires_at": expiresAt,
|
||||
"updated_at": now,
|
||||
})
|
||||
|
||||
if result.Error != nil {
|
||||
logger.ContextLogger(ctx).Error("failed to update registration OTP", zap.Error(result.Error))
|
||||
return errors.New("failed to update registration OTP")
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("registration not found")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *memberRepository) toRegistrationDBModel(registration *entity.MemberRegistration) models.MemberRegistrationDB {
|
||||
return models.MemberRegistrationDB{
|
||||
ID: registration.ID,
|
||||
Token: registration.Token,
|
||||
Name: registration.Name,
|
||||
Email: registration.Email,
|
||||
Phone: registration.Phone,
|
||||
BirthDate: registration.BirthDate,
|
||||
OTP: registration.OTP,
|
||||
Status: registration.Status.String(),
|
||||
ExpiresAt: registration.ExpiresAt,
|
||||
CreatedAt: registration.CreatedAt,
|
||||
UpdatedAt: registration.UpdatedAt,
|
||||
BranchID: registration.BranchID,
|
||||
CashierID: registration.CashierID,
|
||||
Password: registration.Password,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *memberRepository) toDomainRegistrationModel(dbModel *models.MemberRegistrationDB) *entity.MemberRegistration {
|
||||
return &entity.MemberRegistration{
|
||||
ID: dbModel.ID,
|
||||
Token: dbModel.Token,
|
||||
Name: dbModel.Name,
|
||||
Email: dbModel.Email,
|
||||
Phone: dbModel.Phone,
|
||||
BirthDate: dbModel.BirthDate,
|
||||
OTP: dbModel.OTP,
|
||||
Status: constants.RegistrationStatus(dbModel.Status),
|
||||
ExpiresAt: dbModel.ExpiresAt,
|
||||
CreatedAt: dbModel.CreatedAt,
|
||||
UpdatedAt: dbModel.UpdatedAt,
|
||||
BranchID: dbModel.BranchID,
|
||||
CashierID: dbModel.CashierID,
|
||||
Password: dbModel.Password,
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
package mdtrns
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
|
||||
"github.com/veritrans/go-midtrans"
|
||||
)
|
||||
|
||||
type MidtransConfig interface {
|
||||
MidtransServerKey() string
|
||||
MidtransClientKey() string
|
||||
MidtranEnvType() int
|
||||
}
|
||||
|
||||
type ClientService struct {
|
||||
client midtrans.Client
|
||||
midtransConfig MidtransConfig
|
||||
}
|
||||
|
||||
func New(midtransConfig MidtransConfig) *ClientService {
|
||||
midclient := midtrans.NewClient()
|
||||
midclient.ServerKey = midtransConfig.MidtransServerKey()
|
||||
midclient.ClientKey = midtransConfig.MidtransClientKey()
|
||||
midclient.APIEnvType = midtrans.EnvironmentType(midtransConfig.MidtranEnvType())
|
||||
|
||||
return &ClientService{
|
||||
client: midclient,
|
||||
midtransConfig: midtransConfig,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ClientService) CreatePayment(order entity.MidtransRequest) (*entity.MidtransResponse, error) {
|
||||
var snapGateway midtrans.SnapGateway
|
||||
snapGateway = midtrans.SnapGateway{
|
||||
Client: c.client,
|
||||
}
|
||||
|
||||
var paymentMethod []midtrans.PaymentType
|
||||
|
||||
if order.PaymentMethod == "QRIS" {
|
||||
paymentMethod = []midtrans.PaymentType{midtrans.SourceGopay}
|
||||
}
|
||||
|
||||
snapReq := &midtrans.SnapReq{
|
||||
EnabledPayments: paymentMethod,
|
||||
TransactionDetails: midtrans.TransactionDetails{
|
||||
OrderID: order.PaymentReferenceID,
|
||||
GrossAmt: order.TotalAmount,
|
||||
},
|
||||
}
|
||||
|
||||
log.Println("GetToken:")
|
||||
snapTokenResp, err := snapGateway.GetToken(snapReq)
|
||||
|
||||
if err != nil {
|
||||
logger.GetLogger().Error(fmt.Sprintf("error when create midtrans payment %v", err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &entity.MidtransResponse{
|
||||
Token: snapTokenResp.Token,
|
||||
RedirectURL: snapTokenResp.RedirectURL,
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
func (c ClientService) getProductItems(products []entity.OrderItem) []midtrans.ItemDetail {
|
||||
var items []midtrans.ItemDetail
|
||||
|
||||
for _, product := range products {
|
||||
item := midtrans.ItemDetail{
|
||||
ID: strconv.FormatInt(product.ID, 10),
|
||||
Name: product.ItemType,
|
||||
Qty: int32(product.Quantity),
|
||||
Price: int64(product.Price),
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
func (c *ClientService) CreateQrisPayment(order entity.MidtransRequest) (*entity.MidtransQrisResponse, error) {
|
||||
coreGateway := midtrans.CoreGateway{
|
||||
Client: c.client,
|
||||
}
|
||||
|
||||
req := &midtrans.ChargeReq{
|
||||
PaymentType: midtrans.SourceGopay,
|
||||
TransactionDetails: midtrans.TransactionDetails{
|
||||
OrderID: order.PaymentReferenceID,
|
||||
GrossAmt: order.TotalAmount,
|
||||
},
|
||||
}
|
||||
|
||||
// Request charge and retrieve response
|
||||
resp, err := coreGateway.Charge(req)
|
||||
if err != nil {
|
||||
logger.GetLogger().Error(fmt.Sprintf("error when creating QRIS payment: %v", err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Extract QR code URL from response actions
|
||||
var qrCodeURL string
|
||||
for _, action := range resp.Actions {
|
||||
if action.Name == "generate-qr-code" {
|
||||
qrCodeURL = action.URL
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if qrCodeURL == "" {
|
||||
logger.GetLogger().Error("error: QR code URL not provided in response")
|
||||
return nil, fmt.Errorf("QR code URL not provided in response")
|
||||
}
|
||||
|
||||
return &entity.MidtransQrisResponse{
|
||||
QrCodeUrl: qrCodeURL,
|
||||
OrderID: order.PaymentReferenceID,
|
||||
Amount: order.TotalAmount,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type CashierSessionDB struct {
|
||||
ID int64 `gorm:"primaryKey"`
|
||||
PartnerID int64 `gorm:"not null"`
|
||||
CashierID int64 `gorm:"not null"`
|
||||
OpenedAt time.Time `gorm:"not null"`
|
||||
ClosedAt *time.Time
|
||||
OpeningAmount float64 `gorm:"not null"`
|
||||
ClosingAmount *float64
|
||||
ExpectedAmount *float64
|
||||
Notes *string
|
||||
Status string `gorm:"not null"`
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (CashierSessionDB) TableName() string {
|
||||
return "cashier_sessions"
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type CategoryDB struct {
|
||||
ID int64 `gorm:"primaryKey;autoIncrement"`
|
||||
PartnerID int64 `gorm:"not null"`
|
||||
Name string `gorm:"type:varchar(255);not null"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||
DeletedAt *time.Time
|
||||
}
|
||||
|
||||
func (CategoryDB) TableName() string {
|
||||
return "categories"
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"time"
|
||||
)
|
||||
|
||||
type CustomerDB struct {
|
||||
ID int64 `gorm:"primaryKey;column:id"`
|
||||
Name string `gorm:"column:name"`
|
||||
Email string `gorm:"column:email"`
|
||||
Phone string `gorm:"column:phone"`
|
||||
Points int `gorm:"column:points"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
CustomerID string `gorm:"column:customer_id"`
|
||||
BirthDate time.Time `gorm:"column:birth_date"`
|
||||
Password string `gorm:"column:password"`
|
||||
IsEmailVerified bool `gorm:"column:is_email_verified"`
|
||||
IsPhoneVerified bool `gorm:"column:is_phone_verified"`
|
||||
}
|
||||
|
||||
func (CustomerDB) TableName() string {
|
||||
return "customers"
|
||||
}
|
||||
|
||||
type PartnerMemberSequence struct {
|
||||
ID int64 `gorm:"column:id;primary_key;auto_increment"`
|
||||
PartnerID int64 `gorm:"column:partner_id;not null;index:idx_partner_month,unique"`
|
||||
LastSequence int64 `gorm:"column:last_sequence;not null;default:0"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;not null"`
|
||||
}
|
||||
|
||||
func (PartnerMemberSequence) TableName() string {
|
||||
return "partner_member_sequences"
|
||||
}
|
||||
|
||||
type CustomerPointsDB struct {
|
||||
ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
|
||||
CustomerID uint64 `gorm:"column:customer_id;not null"`
|
||||
TotalPoints int `gorm:"column:total_points;not null;default:0"`
|
||||
AvailablePoints int `gorm:"column:available_points;not null;default:0"`
|
||||
LastUpdated time.Time `gorm:"column:last_updated;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (CustomerPointsDB) TableName() string {
|
||||
return "customer_points"
|
||||
}
|
||||
|
||||
type CustomerPointTransactionDB struct {
|
||||
ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
|
||||
CustomerID int64 `gorm:"column:customer_id;not null"`
|
||||
Reference string `gorm:"column:reference"`
|
||||
PointsEarned int `gorm:"column:points_earned;not null"`
|
||||
TransactionDate time.Time `gorm:"column:transaction_date;not null"`
|
||||
ExpirationDate *time.Time `gorm:"column:expiration_date"`
|
||||
Status string `gorm:"column:status;default:active"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (CustomerPointTransactionDB) TableName() string {
|
||||
return "customer_point_transactions"
|
||||
}
|
||||
|
||||
type CustomerVerificationCodeDB struct {
|
||||
ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
|
||||
CustomerID uint64 `gorm:"column:customer_id;not null"`
|
||||
Code string `gorm:"column:code;not null"`
|
||||
Type string `gorm:"column:type;not null"`
|
||||
ExpiresAt time.Time `gorm:"column:expires_at;not null"`
|
||||
IsUsed bool `gorm:"column:is_used;default:false"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
VerificationID uuid.UUID `gorm:"column:verification_id;type:uuid;default:uuid_generate_v4()"`
|
||||
}
|
||||
|
||||
func (CustomerVerificationCodeDB) TableName() string {
|
||||
return "customer_verification_codes"
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type InProgressOrderDB struct {
|
||||
ID string `gorm:"primaryKey;column:id"`
|
||||
PartnerID int64 `gorm:"column:partner_id"`
|
||||
CustomerID *int64 `gorm:"column:customer_id"`
|
||||
CustomerName string `gorm:"column:customer_name"`
|
||||
PaymentType string `gorm:"column:payment_type"`
|
||||
CreatedBy int64 `gorm:"column:created_by"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
TableNumber string `gorm:"column:table_number"`
|
||||
OrderItems []InProgressOrderItemDB `gorm:"foreignKey:InProgressOrderIO"`
|
||||
OrderType string `gorm:"column:order_type"`
|
||||
}
|
||||
|
||||
type InProgressOrderItemDB struct {
|
||||
ID int64 `gorm:"primaryKey;column:id"`
|
||||
InProgressOrderIO string `gorm:"column:in_progress_order_id"`
|
||||
ItemID int64 `gorm:"column:item_id"`
|
||||
Quantity int `gorm:"column:quantity"`
|
||||
CreatedBy int64 `gorm:"column:created_by"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
Product ProductDB `gorm:"foreignKey:ItemID;references:ID"`
|
||||
}
|
||||
|
||||
func (InProgressOrderItemDB) TableName() string {
|
||||
return "in_progress_order_items"
|
||||
}
|
||||
|
||||
func (InProgressOrderDB) TableName() string {
|
||||
return "in_progress_order"
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type MemberRegistrationDB struct {
|
||||
ID string `gorm:"column:id;primary_key"`
|
||||
Token string `gorm:"column:token;unique_index"`
|
||||
Name string `gorm:"column:name"`
|
||||
Email string `gorm:"column:email"`
|
||||
Phone string `gorm:"column:phone"`
|
||||
BirthDate time.Time `gorm:"column:birth_date"`
|
||||
OTP string `gorm:"column:otp"`
|
||||
Status string `gorm:"column:status"`
|
||||
ExpiresAt time.Time `gorm:"column:expires_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
BranchID int64 `gorm:"column:branch_id"`
|
||||
CashierID int64 `gorm:"column:cashier_id"`
|
||||
Password string `gorm:"column:password"`
|
||||
}
|
||||
|
||||
func (MemberRegistrationDB) TableName() string {
|
||||
return "member_registrations"
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type OrderDB struct {
|
||||
ID int64 `gorm:"primaryKey;column:id"`
|
||||
PartnerID int64 `gorm:"column:partner_id"`
|
||||
CustomerID *int64 `gorm:"column:customer_id"`
|
||||
InquiryID *string `gorm:"column:inquiry_id"`
|
||||
Status string `gorm:"column:status"`
|
||||
Amount float64 `gorm:"column:amount"`
|
||||
Tax float64 `gorm:"column:tax"`
|
||||
Total float64 `gorm:"column:total"`
|
||||
PaymentType string `gorm:"column:payment_type"`
|
||||
Source string `gorm:"column:source"`
|
||||
CreatedBy int64 `gorm:"column:created_by"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
OrderItems []OrderItemDB `gorm:"foreignKey:OrderID"`
|
||||
OrderType string `gorm:"column:order_type"`
|
||||
TableNumber string `gorm:"column:table_number"`
|
||||
PaymentProvider string `gorm:"column:payment_provider"`
|
||||
CustomerName string `gorm:"column:customer_name"`
|
||||
CashierSessionID int64 `gorm:"column:cashier_session_id"`
|
||||
Description string `gorm:"column:description"`
|
||||
}
|
||||
|
||||
func (OrderDB) TableName() string {
|
||||
return "orders"
|
||||
}
|
||||
|
||||
type OrderItemDB struct {
|
||||
ID int64 `gorm:"primaryKey;column:order_item_id"`
|
||||
OrderID int64 `gorm:"column:order_id"`
|
||||
ItemID int64 `gorm:"column:item_id"`
|
||||
ItemName string `gorm:"column:item_name"`
|
||||
ItemType string `gorm:"column:item_type"`
|
||||
Price float64 `gorm:"column:price"`
|
||||
Quantity int `gorm:"column:quantity"`
|
||||
Status string `gorm:"column:status;default:ACTIVE"`
|
||||
CreatedBy int64 `gorm:"column:created_by"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
Product ProductDB `gorm:"foreignKey:ItemID;references:ID"`
|
||||
Notes string `gorm:"column:notes"`
|
||||
}
|
||||
|
||||
func (OrderItemDB) TableName() string {
|
||||
return "order_items"
|
||||
}
|
||||
|
||||
type OrderInquiryDB struct {
|
||||
ID string `gorm:"primaryKey;column:id"`
|
||||
PartnerID int64 `gorm:"column:partner_id"`
|
||||
CustomerID *int64 `gorm:"column:customer_id"`
|
||||
CustomerName string `gorm:"column:customer_name"`
|
||||
CustomerEmail string `gorm:"column:customer_email"`
|
||||
CustomerPhoneNumber string `gorm:"column:customer_phone_number"`
|
||||
Status string `gorm:"column:status"`
|
||||
Amount float64 `gorm:"column:amount"`
|
||||
Tax float64 `gorm:"column:tax"`
|
||||
Total float64 `gorm:"column:total"`
|
||||
PaymentType string `gorm:"column:payment_type"`
|
||||
Source string `gorm:"column:source"`
|
||||
CreatedBy int64 `gorm:"column:created_by"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
ExpiresAt time.Time `gorm:"column:expires_at"`
|
||||
InquiryItems []InquiryItemDB `gorm:"foreignKey:InquiryID"`
|
||||
PaymentProvider string `gorm:"column:payment_provider"`
|
||||
TableNumber string `gorm:"column:table_number"`
|
||||
OrderType string `gorm:"column:order_type"`
|
||||
CashierSessionID int64 `gorm:"column:cashier_session_id"`
|
||||
}
|
||||
|
||||
func (OrderInquiryDB) TableName() string {
|
||||
return "order_inquiries"
|
||||
}
|
||||
|
||||
type InquiryItemDB struct {
|
||||
ID int64 `gorm:"primaryKey;column:id"`
|
||||
InquiryID string `gorm:"column:inquiry_id"`
|
||||
ItemID int64 `gorm:"column:item_id"`
|
||||
ItemType string `gorm:"column:item_type"`
|
||||
ItemName string `gorm:"column:item_name"`
|
||||
Price float64 `gorm:"column:price"`
|
||||
Quantity int `gorm:"column:quantity"`
|
||||
CreatedBy int64 `gorm:"column:created_by"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
Notes string `gorm:"column:notes"`
|
||||
}
|
||||
|
||||
func (InquiryItemDB) TableName() string {
|
||||
return "inquiry_items"
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type PartnerSettingsDB struct {
|
||||
PartnerID int64 `gorm:"primaryKey;column:partner_id"`
|
||||
TaxEnabled bool `gorm:"column:tax_enabled;default:false"`
|
||||
TaxPercentage float64 `gorm:"column:tax_percentage;default:10.00"`
|
||||
InvoicePrefix string `gorm:"column:invoice_prefix;default:INV"`
|
||||
BusinessHours string `gorm:"column:business_hours;type:json"` // JSON string
|
||||
LogoURL string `gorm:"column:logo_url"`
|
||||
ThemeColor string `gorm:"column:theme_color;default:#000000"`
|
||||
ReceiptFooterText string `gorm:"column:receipt_footer_text;type:text"`
|
||||
ReceiptHeaderText string `gorm:"column:receipt_header_text;type:text"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (PartnerSettingsDB) TableName() string {
|
||||
return "partner_settings"
|
||||
}
|
||||
|
||||
type PartnerPaymentMethodDB struct {
|
||||
ID int64 `gorm:"primaryKey;column:id;autoIncrement"`
|
||||
PartnerID int64 `gorm:"column:partner_id;index:idx_partner_payment"`
|
||||
PaymentMethod string `gorm:"column:payment_method;index:idx_partner_payment"`
|
||||
IsEnabled bool `gorm:"column:is_enabled;default:true"`
|
||||
DisplayName string `gorm:"column:display_name"`
|
||||
DisplayOrder int `gorm:"column:display_order;default:0"`
|
||||
AdditionalInfo string `gorm:"column:additional_info;type:json"` // JSON string
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (PartnerPaymentMethodDB) TableName() string {
|
||||
return "partner_payment_methods"
|
||||
}
|
||||
|
||||
type PartnerFeatureFlagDB struct {
|
||||
ID int64 `gorm:"primaryKey;column:id;autoIncrement"`
|
||||
PartnerID int64 `gorm:"column:partner_id;index:idx_partner_feature"`
|
||||
FeatureKey string `gorm:"column:feature_key;index:idx_partner_feature"`
|
||||
IsEnabled bool `gorm:"column:is_enabled;default:true"`
|
||||
Config string `gorm:"column:config;type:json"` // JSON string
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (PartnerFeatureFlagDB) TableName() string {
|
||||
return "partner_feature_flags"
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type ProductDB struct {
|
||||
ID int64 `gorm:"primaryKey;column:id"`
|
||||
SiteID int64 `gorm:"column:site_id"`
|
||||
PartnerID int64 `gorm:"column:partner_id"`
|
||||
Name string `gorm:"column:name"`
|
||||
Description string `gorm:"column:description"`
|
||||
Price float64 `gorm:"column:price"`
|
||||
Type string `gorm:"column:type"`
|
||||
Status string `gorm:"column:status"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
Image string `gorm:"column:image"`
|
||||
}
|
||||
|
||||
func (ProductDB) TableName() string {
|
||||
return "products"
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type TransactionDB struct {
|
||||
ID string `gorm:"type:uuid;default:gen_random_uuid();primaryKey;column:id"`
|
||||
OrderID int64 `gorm:"column:order_id"`
|
||||
Amount float64 `gorm:"column:amount"`
|
||||
PaymentMethod string `gorm:"column:payment_method"`
|
||||
Status string `gorm:"column:status"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
PartnerID int64 `gorm:"column:partner_id"`
|
||||
TransactionType string `gorm:"column:transaction_type"`
|
||||
}
|
||||
|
||||
func (TransactionDB) TableName() string {
|
||||
return "transactions"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,136 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrderItemRepository interface {
|
||||
Create(ctx context.Context, orderItem *entities.OrderItem) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*entities.OrderItem, error)
|
||||
GetByOrderID(ctx context.Context, orderID uuid.UUID) ([]*entities.OrderItem, error)
|
||||
Update(ctx context.Context, orderItem *entities.OrderItem) error
|
||||
Delete(ctx context.Context, id uuid.UUID) error
|
||||
RefundOrderItem(ctx context.Context, id uuid.UUID, refundQuantity int, refundAmount float64, reason string, refundedBy uuid.UUID) error
|
||||
VoidOrderItem(ctx context.Context, id uuid.UUID, voidQuantity int, reason string, voidedBy uuid.UUID) error
|
||||
UpdateStatus(ctx context.Context, id uuid.UUID, status entities.OrderItemStatus) error
|
||||
}
|
||||
|
||||
type OrderItemRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderItemRepositoryImpl(db *gorm.DB) *OrderItemRepositoryImpl {
|
||||
return &OrderItemRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *OrderItemRepositoryImpl) Create(ctx context.Context, orderItem *entities.OrderItem) error {
|
||||
return r.db.WithContext(ctx).Create(orderItem).Error
|
||||
}
|
||||
|
||||
func (r *OrderItemRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.OrderItem, error) {
|
||||
var orderItem entities.OrderItem
|
||||
err := r.db.WithContext(ctx).First(&orderItem, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &orderItem, nil
|
||||
}
|
||||
|
||||
func (r *OrderItemRepositoryImpl) GetByOrderID(ctx context.Context, orderID uuid.UUID) ([]*entities.OrderItem, error) {
|
||||
var orderItems []*entities.OrderItem
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Product").
|
||||
Preload("ProductVariant").
|
||||
Where("order_id = ?", orderID).
|
||||
Find(&orderItems).Error
|
||||
return orderItems, err
|
||||
}
|
||||
|
||||
func (r *OrderItemRepositoryImpl) Update(ctx context.Context, orderItem *entities.OrderItem) error {
|
||||
return r.db.WithContext(ctx).Save(orderItem).Error
|
||||
}
|
||||
|
||||
func (r *OrderItemRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.OrderItem{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *OrderItemRepositoryImpl) RefundOrderItem(ctx context.Context, id uuid.UUID, refundQuantity int, refundAmount float64, reason string, refundedBy uuid.UUID) error {
|
||||
now := time.Now()
|
||||
|
||||
// Get current order item
|
||||
var orderItem entities.OrderItem
|
||||
if err := r.db.WithContext(ctx).First(&orderItem, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Calculate new refund quantities and amounts
|
||||
newRefundQuantity := orderItem.RefundQuantity + refundQuantity
|
||||
newRefundAmount := orderItem.RefundAmount + refundAmount
|
||||
|
||||
// Determine if fully or partially refunded
|
||||
isFullyRefunded := newRefundQuantity >= orderItem.Quantity
|
||||
isPartiallyRefunded := newRefundQuantity > 0 && newRefundQuantity < orderItem.Quantity
|
||||
|
||||
updates := map[string]interface{}{
|
||||
"refund_quantity": newRefundQuantity,
|
||||
"refund_amount": newRefundAmount,
|
||||
"is_partially_refunded": isPartiallyRefunded,
|
||||
"is_fully_refunded": isFullyRefunded,
|
||||
"refund_reason": reason,
|
||||
"refunded_at": now,
|
||||
"refunded_by": refundedBy,
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Model(&entities.OrderItem{}).
|
||||
Where("id = ?", id).
|
||||
Updates(updates).Error
|
||||
}
|
||||
|
||||
func (r *OrderItemRepositoryImpl) UpdateStatus(ctx context.Context, id uuid.UUID, status entities.OrderItemStatus) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.OrderItem{}).
|
||||
Where("id = ?", id).
|
||||
Update("status", status).Error
|
||||
}
|
||||
|
||||
func (r *OrderItemRepositoryImpl) VoidOrderItem(ctx context.Context, id uuid.UUID, voidQuantity int, reason string, voidedBy uuid.UUID) error {
|
||||
now := time.Now()
|
||||
|
||||
// Get current order item
|
||||
var orderItem entities.OrderItem
|
||||
if err := r.db.WithContext(ctx).First(&orderItem, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Calculate new voided quantity
|
||||
newVoidedQuantity := orderItem.RefundQuantity + voidQuantity // Using refund_quantity field for voided quantity
|
||||
|
||||
// Determine if fully or partially voided
|
||||
isFullyVoided := newVoidedQuantity >= orderItem.Quantity
|
||||
isPartiallyVoided := newVoidedQuantity > 0 && newVoidedQuantity < orderItem.Quantity
|
||||
|
||||
// Calculate voided amount
|
||||
voidedAmount := float64(voidQuantity) * orderItem.UnitPrice
|
||||
|
||||
updates := map[string]interface{}{
|
||||
"refund_quantity": newVoidedQuantity, // Reusing refund_quantity field for voided quantity
|
||||
"refund_amount": orderItem.RefundAmount + voidedAmount,
|
||||
"is_partially_refunded": isPartiallyVoided, // Reusing refunded flags for voided status
|
||||
"is_fully_refunded": isFullyVoided,
|
||||
"refund_reason": reason,
|
||||
"refunded_at": now,
|
||||
"refunded_by": voidedBy,
|
||||
"status": entities.OrderItemStatusCancelled, // Mark as cancelled when voided
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Model(&entities.OrderItem{}).
|
||||
Where("id = ?", id).
|
||||
Updates(updates).Error
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrderRepository interface {
|
||||
Create(ctx context.Context, order *entities.Order) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*entities.Order, error)
|
||||
GetWithRelations(ctx context.Context, id uuid.UUID) (*entities.Order, error)
|
||||
Update(ctx context.Context, order *entities.Order) error
|
||||
Delete(ctx context.Context, id uuid.UUID) error
|
||||
List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.Order, int64, error)
|
||||
GetByOrderNumber(ctx context.Context, orderNumber string) (*entities.Order, error)
|
||||
ExistsByOrderNumber(ctx context.Context, orderNumber string) (bool, error)
|
||||
VoidOrder(ctx context.Context, id uuid.UUID, reason string, voidedBy uuid.UUID) error
|
||||
VoidOrderWithStatus(ctx context.Context, id uuid.UUID, status entities.OrderStatus, reason string, voidedBy uuid.UUID) error
|
||||
RefundOrder(ctx context.Context, id uuid.UUID, reason string, refundedBy uuid.UUID) error
|
||||
UpdatePaymentStatus(ctx context.Context, id uuid.UUID, status entities.PaymentStatus) error
|
||||
UpdateStatus(ctx context.Context, id uuid.UUID, status entities.OrderStatus) error
|
||||
GetNextOrderNumber(ctx context.Context, organizationID, outletID uuid.UUID) (string, error)
|
||||
}
|
||||
|
||||
type OrderRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderRepositoryImpl(db *gorm.DB) *OrderRepositoryImpl {
|
||||
return &OrderRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) Create(ctx context.Context, order *entities.Order) error {
|
||||
return r.db.WithContext(ctx).Create(order).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.Order, error) {
|
||||
var order entities.Order
|
||||
err := r.db.WithContext(ctx).First(&order, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) GetWithRelations(ctx context.Context, id uuid.UUID) (*entities.Order, error) {
|
||||
var order entities.Order
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Organization").
|
||||
Preload("Outlet").
|
||||
Preload("User").
|
||||
Preload("OrderItems").
|
||||
Preload("OrderItems.Product").
|
||||
Preload("OrderItems.ProductVariant").
|
||||
Preload("Payments").
|
||||
Preload("Payments.PaymentMethod").
|
||||
Preload("Payments.PaymentOrderItems").
|
||||
First(&order, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) Update(ctx context.Context, order *entities.Order) error {
|
||||
return r.db.WithContext(ctx).Save(order).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.Order{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.Order, int64, error) {
|
||||
var orders []*entities.Order
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.Order{}).
|
||||
Preload("Organization").
|
||||
Preload("Outlet").
|
||||
Preload("User").
|
||||
Preload("OrderItems").
|
||||
Preload("OrderItems.Product").
|
||||
Preload("OrderItems.ProductVariant").
|
||||
Preload("Payments").
|
||||
Preload("Payments.PaymentMethod")
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Where("order_number ILIKE ?", searchValue)
|
||||
case "date_from":
|
||||
query = query.Where("created_at >= ?", value)
|
||||
case "date_to":
|
||||
query = query.Where("created_at <= ?", value)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Order("created_at DESC").Find(&orders).Error
|
||||
return orders, total, err
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) GetByOrderNumber(ctx context.Context, orderNumber string) (*entities.Order, error) {
|
||||
var order entities.Order
|
||||
err := r.db.WithContext(ctx).First(&order, "order_number = ?", orderNumber).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) ExistsByOrderNumber(ctx context.Context, orderNumber string) (bool, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&entities.Order{}).Where("order_number = ?", orderNumber).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) VoidOrder(ctx context.Context, id uuid.UUID, reason string, voidedBy uuid.UUID) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).Model(&entities.Order{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"is_void": true,
|
||||
"void_reason": reason,
|
||||
"voided_at": now,
|
||||
"voided_by": voidedBy,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) VoidOrderWithStatus(ctx context.Context, id uuid.UUID, status entities.OrderStatus, reason string, voidedBy uuid.UUID) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).Model(&entities.Order{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"status": status,
|
||||
"is_void": true,
|
||||
"void_reason": reason,
|
||||
"voided_at": now,
|
||||
"voided_by": voidedBy,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) RefundOrder(ctx context.Context, id uuid.UUID, reason string, refundedBy uuid.UUID) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).Model(&entities.Order{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"is_refund": true,
|
||||
"refund_reason": reason,
|
||||
"refunded_at": now,
|
||||
"refunded_by": refundedBy,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) UpdatePaymentStatus(ctx context.Context, id uuid.UUID, status entities.PaymentStatus) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.Order{}).
|
||||
Where("id = ?", id).
|
||||
Update("payment_status", status).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) UpdateStatus(ctx context.Context, id uuid.UUID, status entities.OrderStatus) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.Order{}).
|
||||
Where("id = ?", id).
|
||||
Update("status", status).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepositoryImpl) GetNextOrderNumber(ctx context.Context, organizationID, outletID uuid.UUID) (string, error) {
|
||||
now := time.Now()
|
||||
year := now.Year()
|
||||
month := int(now.Month())
|
||||
|
||||
// Use a transaction to ensure atomic sequence increment
|
||||
tx := r.db.WithContext(ctx).Begin()
|
||||
if tx.Error != nil {
|
||||
return "", tx.Error
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
// Get or create sequence record
|
||||
var sequence entities.OrderSequence
|
||||
err := tx.Where("organization_id = ? AND outlet_id = ? AND year = ? AND month = ?",
|
||||
organizationID, outletID, year, month).
|
||||
First(&sequence).Error
|
||||
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
// Create new sequence record
|
||||
sequence = entities.OrderSequence{
|
||||
OrganizationID: organizationID,
|
||||
OutletID: outletID,
|
||||
Year: year,
|
||||
Month: month,
|
||||
SequenceNumber: 0,
|
||||
}
|
||||
if err := tx.Create(&sequence).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
tx.Rollback()
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
// Increment sequence number
|
||||
sequence.SequenceNumber++
|
||||
if err := tx.Save(&sequence).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Commit transaction
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
orderNumber := fmt.Sprintf("ORD/%04d%02d/%06d", year, month, sequence.SequenceNumber)
|
||||
return orderNumber, nil
|
||||
}
|
||||
@@ -1,354 +0,0 @@
|
||||
package orders
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrderRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderRepository(db *gorm.DB) *OrderRepository {
|
||||
return &OrderRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *OrderRepository) Create(ctx context.Context, order *entity.Order) (*entity.Order, error) {
|
||||
err := r.db.WithContext(ctx).Create(order).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when creating order", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return r.FindByID(ctx, order.ID)
|
||||
}
|
||||
|
||||
func (r *OrderRepository) UpdateStatus(ctx context.Context, orderID int64, status string) (*entity.Order, error) {
|
||||
order := new(entity.Order)
|
||||
if err := r.db.WithContext(ctx).First(order, orderID).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding order", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
order.Status = status
|
||||
if err := r.db.WithContext(ctx).Save(order).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating order status", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) FindByID(ctx context.Context, id int64) (*entity.Order, error) {
|
||||
var order entity.Order
|
||||
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("OrderItems", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("Product")
|
||||
}).
|
||||
Preload("Site").
|
||||
Preload("User").
|
||||
Preload("Payment").
|
||||
First(&order, id).Error
|
||||
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding order by ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) FindPrintDetailByID(ctx context.Context, id int64) (*entity.OrderPrintDetail, error) {
|
||||
var printDetail entity.OrderPrintDetail
|
||||
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("orders").
|
||||
Select("orders.id, partners.name as partner_name, sites.name as site_name, partners.logo as logo, orders.ref_id as order_id, "+
|
||||
"orders.visit_date, orders.payment_type, orders.source, "+
|
||||
"orders.ticket_status, orders.total, orders.fee").
|
||||
Joins("JOIN partners ON partners.id = orders.partner_id").
|
||||
Joins("JOIN sites ON sites.id = orders.site_id").
|
||||
Where("orders.id = ?", id).
|
||||
Scan(&printDetail).Error
|
||||
|
||||
if err == nil {
|
||||
err = r.db.WithContext(ctx).Where("order_id = ?", id).Preload("Product").Find(&printDetail.OrderItems).Error
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding print detail by ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &printDetail, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) FindByQRCode(ctx context.Context, refID string) (*entity.Order, error) {
|
||||
var order entity.Order
|
||||
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("OrderItems", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("Product")
|
||||
}).
|
||||
Preload("User").
|
||||
Preload("Payment").
|
||||
Where("ref_id = ?", refID).
|
||||
First(&order).Error
|
||||
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding order by refID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) SetOrderStatus(ctx context.Context, db *gorm.DB, orderID int64, status string) error {
|
||||
var order entity.Order
|
||||
if err := db.WithContext(ctx).Preload("OrderItems").First(&order, orderID).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding order by ID", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
order.Status = status
|
||||
|
||||
if err := db.WithContext(ctx).Save(&order).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating order status", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) Update(ctx context.Context, order *entity.Order) (*entity.Order, error) {
|
||||
if err := r.db.WithContext(ctx).Model(&entity.Order{}).Where("id = ?", order.ID).Updates(order).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating order", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (b *OrderRepository) GetAllHystoryOrders(ctx context.Context, req entity.OrderSearch) (entity.HistoryOrderList, int, error) {
|
||||
var orders []*entity.HistoryOrderDB
|
||||
var total int64
|
||||
|
||||
query := b.db.Table("orders").
|
||||
Select("orders.id as id, users.name as employee, sites.name as site, orders.created_at as timestamp, orders.created_at as booking_time, STRING_AGG(ticket_summary.name || ' x' || ticket_summary.total_qty, ', ') AS tickets, orders.payment_type as payment_type, orders.status as status, orders.amount as amount, orders.visit_date as visit_date, orders.ticket_status as ticket_status, orders.source as source").
|
||||
Joins("left join (SELECT items.order_id, products.name, SUM(items.quantity) AS total_qty FROM order_items items LEFT JOIN products ON items.item_id = products.id GROUP BY items.order_id, products.name) AS ticket_summary ON orders.id = ticket_summary.order_id").
|
||||
Joins("left join users on orders.created_by = users.id").
|
||||
Where("orders.payment_type != ?", "NEW")
|
||||
|
||||
if req.PaymentType != "" {
|
||||
query = query.Where("orders.payment_type = ?", req.PaymentType)
|
||||
}
|
||||
|
||||
if req.CreatedBy != 0 {
|
||||
query = query.Where("orders.created_by = ?", req.CreatedBy)
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
query = query.Where("orders.status = ?", req.Status)
|
||||
}
|
||||
|
||||
if !req.IsAdmin && !req.IsCustomer {
|
||||
query = query.Where("orders.partner_id = ?", req.PartnerID)
|
||||
}
|
||||
|
||||
if req.StartDate != "" && req.EndDate != "" {
|
||||
// Assuming req.Date and req.EndDate are in string format "YYYY-MM-DD"
|
||||
startDate := req.StartDate + " 00:00:00"
|
||||
endDate := req.EndDate + " 23:59:59"
|
||||
|
||||
query = query.Where("orders.created_at BETWEEN ? AND ?", startDate, endDate)
|
||||
} else {
|
||||
currentTime := time.Now()
|
||||
startOfMonth := time.Date(currentTime.Year(), currentTime.Month(), 1, 0, 0, 0, 0, time.Local)
|
||||
endOfMonth := startOfMonth.AddDate(0, 1, 0).Add(-time.Second)
|
||||
query = query.Where("orders.created_at BETWEEN ? AND ?", startOfMonth, endOfMonth)
|
||||
}
|
||||
|
||||
if req.SiteID != nil {
|
||||
query = query.Where("orders.partner_id = ?", req.SiteID)
|
||||
}
|
||||
|
||||
if req.Source != "" {
|
||||
query = query.Where("orders.source = ?", req.Source)
|
||||
}
|
||||
|
||||
query = query.Group("orders.id, users.name, sites.name, orders.created_at, orders.payment_type, orders.status")
|
||||
|
||||
query = query.Order("orders.created_at DESC")
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count history orders", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if err := query.Debug().Scan(&orders).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all history orders", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
for i, order := range orders {
|
||||
if order.RawTickets != "" {
|
||||
orders[i].Tickets = strings.Split(order.RawTickets, ", ")
|
||||
}
|
||||
}
|
||||
|
||||
return orders, int(total), nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) CountSoldOfTicket(ctx mycontext.Context, req entity.OrderSearch) (*entity.TicketSoldDB, error) {
|
||||
ticketCount := new(entity.TicketSoldDB)
|
||||
|
||||
query := r.db.Table("orders").
|
||||
Select("sum(items.qty) as count").
|
||||
Joins("left join order_items items on orders.id = items.order_id").
|
||||
Where("orders.status = ?", "PAID").
|
||||
Where("EXTRACT(MONTH FROM orders.created_at) = ?", time.Now().Month())
|
||||
|
||||
if !req.IsAdmin {
|
||||
query = query.Where("orders.partner_id = ?", req.PartnerID)
|
||||
}
|
||||
|
||||
if err := query.Scan(&ticketCount).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get count ticket", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ticketCount, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) SumAmount(ctx mycontext.Context, req entity.OrderSearch) (*entity.OrderDB, error) {
|
||||
amount := new(entity.OrderDB)
|
||||
|
||||
query := r.db.Table("orders").
|
||||
Select("sum(amount) as amount").
|
||||
Where("status = ?", "PAID").
|
||||
Where("EXTRACT(MONTH FROM orders.created_at) = ?", time.Now().Month())
|
||||
|
||||
if req.PaymentType == "CASH" {
|
||||
query = query.Where("payment_type = ?", req.PaymentType)
|
||||
} else {
|
||||
query = query.Where("payment_type != ?", "CASH")
|
||||
}
|
||||
|
||||
if req.PartnerID != nil {
|
||||
query = query.Where("orders.partner_id = ?", req.PartnerID)
|
||||
}
|
||||
|
||||
if err := query.Scan(&amount).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get cash amount", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return amount, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) GetDailySalesMetrics(ctx context.Context, req entity.OrderSearch) ([]entity.ProductDailySales, error) {
|
||||
var sales []entity.ProductDailySales
|
||||
|
||||
var dateTrunc, periodFilter string
|
||||
now := time.Now()
|
||||
|
||||
switch req.Period {
|
||||
case "1d":
|
||||
dateTrunc = "hour"
|
||||
periodFilter = now.Add(-24 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
case "7d":
|
||||
dateTrunc = "day"
|
||||
periodFilter = now.Add(-7 * 24 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
case "1m":
|
||||
dateTrunc = "day"
|
||||
periodFilter = now.AddDate(0, -1, 0).Format("2006-01-02 15:04:05")
|
||||
case "1y":
|
||||
dateTrunc = "week"
|
||||
periodFilter = now.AddDate(-1, 0, 0).Format("2006-01-02 15:04:05")
|
||||
default:
|
||||
dateTrunc = "day"
|
||||
periodFilter = now.AddDate(0, -1, 0).Format("2006-01-02 15:04:05") // Default to last month
|
||||
}
|
||||
|
||||
// Build the query with GORM
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("orders o").
|
||||
Select(`DATE_TRUNC(?, o.created_at) AS day, s.id AS site_id, s.name AS site_name, o.payment_type, SUM(oi.qty * oi.price) AS total`, dateTrunc).
|
||||
Joins("JOIN order_items oi ON o.id = oi.order_id").
|
||||
Joins("JOIN sites s ON o.site_id = s.id").
|
||||
Where("o.status = ?", "PAID").
|
||||
Where("o.created_at >= ?", periodFilter)
|
||||
|
||||
if req.PartnerID != nil {
|
||||
query = query.Where("o.partner_id = ?", *req.PartnerID)
|
||||
}
|
||||
|
||||
if req.SiteID != nil {
|
||||
query = query.Where("o.site_id = ?", *req.SiteID)
|
||||
}
|
||||
|
||||
query = query.Group("day, s.id, s.name, o.payment_type").
|
||||
Order("day")
|
||||
|
||||
if err := query.Find(&sales).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sales, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) GetPaymentTypeDistribution(ctx context.Context, req entity.OrderSearch) ([]entity.PaymentTypeDistribution, error) {
|
||||
var distribution []entity.PaymentTypeDistribution
|
||||
|
||||
var periodFilter string
|
||||
now := time.Now()
|
||||
|
||||
switch req.Period {
|
||||
case "1d":
|
||||
periodFilter = now.Add(-24 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
case "7d":
|
||||
periodFilter = now.Add(-7 * 24 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
case "1m":
|
||||
periodFilter = now.AddDate(0, -1, 0).Format("2006-01-02 15:04:05")
|
||||
case "1y":
|
||||
periodFilter = now.AddDate(-1, 0, 0).Format("2006-01-02 15:04:05")
|
||||
default:
|
||||
periodFilter = now.AddDate(0, -1, 0).Format("2006-01-02 15:04:05") // Default to last month
|
||||
}
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("orders o").
|
||||
Select("payment_type, COUNT(*) as count").
|
||||
Where("status = ?", "PAID").
|
||||
Where("o.created_at >= ?", periodFilter)
|
||||
|
||||
if req.PartnerID != nil {
|
||||
query = query.Where("o.partner_id = ?", *req.PartnerID)
|
||||
}
|
||||
|
||||
if req.SiteID != nil {
|
||||
query = query.Where("o.site_id = ?", *req.SiteID)
|
||||
}
|
||||
|
||||
query = query.Group("payment_type")
|
||||
|
||||
if err := query.Scan(&distribution).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return distribution, nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrganizationRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrganizationRepositoryImpl(db *gorm.DB) *OrganizationRepositoryImpl {
|
||||
return &OrganizationRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) Create(ctx context.Context, org *entities.Organization) error {
|
||||
return r.db.WithContext(ctx).Create(org).Error
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.Organization, error) {
|
||||
var org entities.Organization
|
||||
err := r.db.WithContext(ctx).First(&org, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) GetWithOutlets(ctx context.Context, id uuid.UUID) (*entities.Organization, error) {
|
||||
var org entities.Organization
|
||||
err := r.db.WithContext(ctx).Preload("Outlets").First(&org, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) GetByPlanType(ctx context.Context, planType string) ([]*entities.Organization, error) {
|
||||
var organizations []*entities.Organization
|
||||
err := r.db.WithContext(ctx).Where("plan_type = ?", planType).Find(&organizations).Error
|
||||
return organizations, err
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) UpdatePlanType(ctx context.Context, id uuid.UUID, planType string) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.Organization{}).
|
||||
Where("id = ?", id).
|
||||
Update("plan_type", planType).Error
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) Update(ctx context.Context, org *entities.Organization) error {
|
||||
return r.db.WithContext(ctx).Save(org).Error
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.Organization{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.Organization, int64, error) {
|
||||
var organizations []*entities.Organization
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.Organization{})
|
||||
|
||||
for key, value := range filters {
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Find(&organizations).Error
|
||||
return organizations, total, err
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.Organization{})
|
||||
|
||||
for key, value := range filters {
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *OrganizationRepositoryImpl) GetByEmail(ctx context.Context, email string) (*entities.Organization, error) {
|
||||
var org entities.Organization
|
||||
err := r.db.WithContext(ctx).First(&org, "email = ?", email).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package oss
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
)
|
||||
|
||||
type OSSConfig interface {
|
||||
GetAccessKeyID() string
|
||||
GetAccessKeySecret() string
|
||||
GetEndpoint() string
|
||||
GetBucketName() string
|
||||
GetHostURL() string
|
||||
}
|
||||
|
||||
const _awsRegion = "us-east-1"
|
||||
const _s3ACL = "public-read"
|
||||
|
||||
type OssRepositoryImpl struct {
|
||||
s3 *s3.S3
|
||||
cfg OSSConfig
|
||||
}
|
||||
|
||||
func NewOssRepositoryImpl(ossCfg OSSConfig) *OssRepositoryImpl {
|
||||
sess, err := session.NewSession(&aws.Config{
|
||||
S3ForcePathStyle: aws.Bool(true),
|
||||
Endpoint: aws.String(ossCfg.GetEndpoint()),
|
||||
Region: aws.String(_awsRegion),
|
||||
Credentials: credentials.NewStaticCredentials(ossCfg.GetAccessKeyID(), ossCfg.GetAccessKeySecret(), ""),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("Failed to create AWS session:", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return &OssRepositoryImpl{
|
||||
s3: s3.New(sess),
|
||||
cfg: ossCfg,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *OssRepositoryImpl) UploadFile(ctx context.Context, fileName string, fileContent []byte) (fileUrl string, err error) {
|
||||
reader := bytes.NewReader(fileContent)
|
||||
|
||||
_, err = r.s3.PutObject(&s3.PutObjectInput{
|
||||
Bucket: aws.String(r.cfg.GetBucketName()),
|
||||
Key: aws.String(fileName),
|
||||
Body: reader,
|
||||
ACL: aws.String(_s3ACL),
|
||||
})
|
||||
|
||||
return r.GetPublicURL(fileName), err
|
||||
}
|
||||
|
||||
func (r *OssRepositoryImpl) GetPublicURL(fileName string) string {
|
||||
if fileName == "" {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%s%s%s", r.cfg.GetHostURL(), r.cfg.GetBucketName(), fileName)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/entities"
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OutletRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOutletRepositoryImpl(db *gorm.DB) *OutletRepositoryImpl {
|
||||
return &OutletRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) Create(ctx context.Context, outlet *entities.Outlet) error {
|
||||
return r.db.WithContext(ctx).Create(outlet).Error
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.Outlet, error) {
|
||||
var outlet entities.Outlet
|
||||
err := r.db.WithContext(ctx).First(&outlet, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &outlet, nil
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) GetWithOrders(ctx context.Context, id uuid.UUID) (*entities.Outlet, error) {
|
||||
var outlet entities.Outlet
|
||||
err := r.db.WithContext(ctx).Preload("Orders").First(&outlet, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &outlet, nil
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) GetByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.Outlet, error) {
|
||||
var outlets []*entities.Outlet
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ?", organizationID).Find(&outlets).Error
|
||||
return outlets, err
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) GetByOrganizationIDWithPagination(ctx context.Context, organizationID uuid.UUID, limit, offset int) ([]*entities.Outlet, int64, error) {
|
||||
var outlets []*entities.Outlet
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Where("organization_id = ?", organizationID)
|
||||
|
||||
if err := query.Model(&entities.Outlet{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Find(&outlets).Error
|
||||
return outlets, total, err
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) Update(ctx context.Context, outlet *entities.Outlet) error {
|
||||
return r.db.WithContext(ctx).Save(outlet).Error
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.Outlet{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) UpdateActiveStatus(ctx context.Context, id uuid.UUID, isActive bool) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.Outlet{}).
|
||||
Where("id = ?", id).
|
||||
Update("is_active", isActive).Error
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.Outlet, int64, error) {
|
||||
var outlets []*entities.Outlet
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.Outlet{})
|
||||
|
||||
for key, value := range filters {
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Find(&outlets).Error
|
||||
return outlets, total, err
|
||||
}
|
||||
|
||||
func (r *OutletRepositoryImpl) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.Outlet{})
|
||||
|
||||
for key, value := range filters {
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/entities"
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OutletSettingRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOutletSettingRepositoryImpl(db *gorm.DB) *OutletSettingRepositoryImpl {
|
||||
return &OutletSettingRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) Create(ctx context.Context, setting *entities.OutletSetting) error {
|
||||
return r.db.WithContext(ctx).Create(setting).Error
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.OutletSetting, error) {
|
||||
var setting entities.OutletSetting
|
||||
err := r.db.WithContext(ctx).First(&setting, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) GetByOutletIDAndKey(ctx context.Context, outletID uuid.UUID, key string) (*entities.OutletSetting, error) {
|
||||
var setting entities.OutletSetting
|
||||
err := r.db.WithContext(ctx).Where("outlet_id = ? AND key = ?", outletID, key).First(&setting).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) GetByOutletID(ctx context.Context, outletID uuid.UUID) ([]*entities.OutletSetting, error) {
|
||||
var settings []*entities.OutletSetting
|
||||
err := r.db.WithContext(ctx).Where("outlet_id = ?", outletID).Find(&settings).Error
|
||||
return settings, err
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) Update(ctx context.Context, setting *entities.OutletSetting) error {
|
||||
return r.db.WithContext(ctx).Save(setting).Error
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) Upsert(ctx context.Context, setting *entities.OutletSetting) error {
|
||||
return r.db.WithContext(ctx).Save(setting).Error
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.OutletSetting{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) DeleteByOutletIDAndKey(ctx context.Context, outletID uuid.UUID, key string) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.OutletSetting{}, "outlet_id = ? AND key = ?", outletID, key).Error
|
||||
}
|
||||
|
||||
func (r *OutletSettingRepositoryImpl) GetPrinterSettingsByOutletID(ctx context.Context, outletID uuid.UUID) (map[string]string, error) {
|
||||
var settings []*entities.OutletSetting
|
||||
err := r.db.WithContext(ctx).Where("outlet_id = ? AND key IN (?, ?, ?, ?, ?, ?)",
|
||||
outletID,
|
||||
"printer_outlet_name",
|
||||
"printer_address",
|
||||
"printer_phone_number",
|
||||
"printer_paper_size",
|
||||
"printer_footer",
|
||||
"printer_footer_hashtag",
|
||||
).Find(&settings).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make(map[string]string)
|
||||
for _, setting := range settings {
|
||||
result[setting.Key] = setting.Value
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/models"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PartnerSettingsRepository interface {
|
||||
GetByPartnerID(ctx mycontext.Context, partnerID int64) (*entity.PartnerSettings, error)
|
||||
Upsert(ctx mycontext.Context, settings *entity.PartnerSettings) error
|
||||
GetPaymentMethods(ctx mycontext.Context, partnerID int64) ([]entity.PartnerPaymentMethod, error)
|
||||
UpsertPaymentMethod(ctx mycontext.Context, method *entity.PartnerPaymentMethod) error
|
||||
DeletePaymentMethod(ctx mycontext.Context, id int64, partnerID int64) error
|
||||
UpdatePaymentMethodOrder(ctx mycontext.Context, partnerID int64, methodIDs []int64) error
|
||||
}
|
||||
|
||||
type partnerSettingsRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPartnerSettingsRepository(db *gorm.DB) PartnerSettingsRepository {
|
||||
return &partnerSettingsRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) GetByPartnerID(ctx mycontext.Context, partnerID int64) (*entity.PartnerSettings, error) {
|
||||
var settingsDB models.PartnerSettingsDB
|
||||
|
||||
err := r.db.Where("partner_id = ?", partnerID).First(&settingsDB).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return &entity.PartnerSettings{
|
||||
PartnerID: partnerID,
|
||||
TaxEnabled: true,
|
||||
TaxPercentage: 10.0,
|
||||
}, nil
|
||||
}
|
||||
return nil, errors.Wrap(err, "failed to get partner settings")
|
||||
}
|
||||
|
||||
return r.toDomainModel(&settingsDB), nil
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) Upsert(ctx mycontext.Context, settings *entity.PartnerSettings) error {
|
||||
settingsDB := r.toDBModel(settings)
|
||||
settingsDB.UpdatedAt = time.Now()
|
||||
|
||||
// Check if record exists
|
||||
var count int64
|
||||
if err := r.db.Model(&models.PartnerSettingsDB{}).Where("partner_id = ?", settings.PartnerID).Count(&count).Error; err != nil {
|
||||
return errors.Wrap(err, "failed to check partner settings existence")
|
||||
}
|
||||
|
||||
if count > 0 {
|
||||
// Update existing record
|
||||
if err := r.db.Model(&models.PartnerSettingsDB{}).Where("partner_id = ?", settings.PartnerID).Updates(settingsDB).Error; err != nil {
|
||||
return errors.Wrap(err, "failed to update partner settings")
|
||||
}
|
||||
} else {
|
||||
// Create new record
|
||||
settingsDB.CreatedAt = time.Now()
|
||||
if err := r.db.Create(&settingsDB).Error; err != nil {
|
||||
return errors.Wrap(err, "failed to create partner settings")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) GetPaymentMethods(ctx mycontext.Context, partnerID int64) ([]entity.PartnerPaymentMethod, error) {
|
||||
var methodsDB []models.PartnerPaymentMethodDB
|
||||
|
||||
if err := r.db.Where("partner_id = ?", partnerID).Order("display_order").Find(&methodsDB).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to get partner payment methods")
|
||||
}
|
||||
|
||||
methods := make([]entity.PartnerPaymentMethod, len(methodsDB))
|
||||
for i, methodDB := range methodsDB {
|
||||
methods[i] = *r.toDomainPaymentMethodModel(&methodDB)
|
||||
}
|
||||
|
||||
return methods, nil
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) UpsertPaymentMethod(ctx mycontext.Context, method *entity.PartnerPaymentMethod) error {
|
||||
methodDB := r.toDBPaymentMethodModel(method)
|
||||
methodDB.UpdatedAt = time.Now()
|
||||
|
||||
tx := r.db.Begin()
|
||||
if tx.Error != nil {
|
||||
return errors.Wrap(tx.Error, "failed to begin transaction")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
if method.ID > 0 {
|
||||
// Update existing record
|
||||
if err := tx.Model(&models.PartnerPaymentMethodDB{}).Where("id = ? AND partner_id = ?", method.ID, method.PartnerID).Updates(methodDB).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return errors.Wrap(err, "failed to update payment method")
|
||||
}
|
||||
} else {
|
||||
// Get the next display order if not specified
|
||||
if method.DisplayOrder == 0 {
|
||||
var maxOrder int
|
||||
if err := tx.Model(&models.PartnerPaymentMethodDB{}).Where("partner_id = ?", method.PartnerID).Select("COALESCE(MAX(display_order), 0)").Row().Scan(&maxOrder); err != nil {
|
||||
tx.Rollback()
|
||||
return errors.Wrap(err, "failed to get max display order")
|
||||
}
|
||||
methodDB.DisplayOrder = maxOrder + 1
|
||||
}
|
||||
|
||||
// Create new record
|
||||
methodDB.CreatedAt = time.Now()
|
||||
if err := tx.Create(&methodDB).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return errors.Wrap(err, "failed to create payment method")
|
||||
}
|
||||
|
||||
method.ID = methodDB.ID
|
||||
}
|
||||
|
||||
return tx.Commit().Error
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) DeletePaymentMethod(ctx mycontext.Context, id int64, partnerID int64) error {
|
||||
result := r.db.Where("id = ? AND partner_id = ?", id, partnerID).Delete(&models.PartnerPaymentMethodDB{})
|
||||
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(result.Error, "failed to delete payment method")
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("payment method not found or not authorized")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) UpdatePaymentMethodOrder(ctx mycontext.Context, partnerID int64, methodIDs []int64) error {
|
||||
tx := r.db.Begin()
|
||||
if tx.Error != nil {
|
||||
return errors.Wrap(tx.Error, "failed to begin transaction")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
for i, id := range methodIDs {
|
||||
if err := tx.Model(&models.PartnerPaymentMethodDB{}).
|
||||
Where("id = ? AND partner_id = ?", id, partnerID).
|
||||
Update("display_order", i+1).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return errors.Wrap(err, "failed to update payment method order")
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit().Error
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) toDomainModel(dbModel *models.PartnerSettingsDB) *entity.PartnerSettings {
|
||||
return &entity.PartnerSettings{
|
||||
PartnerID: dbModel.PartnerID,
|
||||
TaxEnabled: dbModel.TaxEnabled,
|
||||
TaxPercentage: dbModel.TaxPercentage,
|
||||
InvoicePrefix: dbModel.InvoicePrefix,
|
||||
BusinessHours: dbModel.BusinessHours,
|
||||
LogoURL: dbModel.LogoURL,
|
||||
ThemeColor: dbModel.ThemeColor,
|
||||
ReceiptFooterText: dbModel.ReceiptFooterText,
|
||||
ReceiptHeaderText: dbModel.ReceiptHeaderText,
|
||||
CreatedAt: dbModel.CreatedAt,
|
||||
UpdatedAt: dbModel.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) toDBModel(domainModel *entity.PartnerSettings) models.PartnerSettingsDB {
|
||||
return models.PartnerSettingsDB{
|
||||
PartnerID: domainModel.PartnerID,
|
||||
TaxEnabled: domainModel.TaxEnabled,
|
||||
TaxPercentage: domainModel.TaxPercentage,
|
||||
InvoicePrefix: domainModel.InvoicePrefix,
|
||||
BusinessHours: domainModel.BusinessHours,
|
||||
LogoURL: domainModel.LogoURL,
|
||||
ThemeColor: domainModel.ThemeColor,
|
||||
ReceiptFooterText: domainModel.ReceiptFooterText,
|
||||
ReceiptHeaderText: domainModel.ReceiptHeaderText,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) toDomainPaymentMethodModel(dbModel *models.PartnerPaymentMethodDB) *entity.PartnerPaymentMethod {
|
||||
return &entity.PartnerPaymentMethod{
|
||||
ID: dbModel.ID,
|
||||
PartnerID: dbModel.PartnerID,
|
||||
PaymentMethod: dbModel.PaymentMethod,
|
||||
IsEnabled: dbModel.IsEnabled,
|
||||
DisplayName: dbModel.DisplayName,
|
||||
DisplayOrder: dbModel.DisplayOrder,
|
||||
AdditionalInfo: dbModel.AdditionalInfo,
|
||||
CreatedAt: dbModel.CreatedAt,
|
||||
UpdatedAt: dbModel.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *partnerSettingsRepository) toDBPaymentMethodModel(domainModel *entity.PartnerPaymentMethod) models.PartnerPaymentMethodDB {
|
||||
return models.PartnerPaymentMethodDB{
|
||||
ID: domainModel.ID,
|
||||
PartnerID: domainModel.PartnerID,
|
||||
PaymentMethod: domainModel.PaymentMethod,
|
||||
IsEnabled: domainModel.IsEnabled,
|
||||
DisplayName: domainModel.DisplayName,
|
||||
DisplayOrder: domainModel.DisplayOrder,
|
||||
AdditionalInfo: domainModel.AdditionalInfo,
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package partners
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PartnerRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPartnerRepository(db *gorm.DB) *PartnerRepository {
|
||||
return &PartnerRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) Create(ctx context.Context, Partner *entity.PartnerDB) (*entity.PartnerDB, error) {
|
||||
err := b.db.Create(Partner).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return Partner, nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) CreateWithTx(ctx context.Context, tx *gorm.DB, Partner *entity.PartnerDB) (*entity.PartnerDB, error) {
|
||||
err := tx.Create(Partner).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return Partner, nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) Update(ctx context.Context, Partner *entity.PartnerDB) (*entity.PartnerDB, error) {
|
||||
if err := b.db.Save(Partner).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return Partner, nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) UpdateWithTx(ctx context.Context, tx *gorm.DB, Partner *entity.PartnerDB) (*entity.PartnerDB, error) {
|
||||
if err := tx.Save(Partner).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return Partner, nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) GetByID(ctx context.Context, id int64) (*entity.PartnerDB, error) {
|
||||
Partner := new(entity.PartnerDBSearch)
|
||||
|
||||
query := b.db.Table("partners p").
|
||||
Select("p.*, w.balance as wallet_balance, u.name as admin_name, u.email as admin_email, u.phone_number as admin_phone_number").
|
||||
Joins("LEFT JOIN wallets w ON w.partner_id = p.id").
|
||||
Joins("LEFT JOIN users u ON p.admin_user_id = u.id").
|
||||
Where("p.id = ? AND p.deleted_at IS NULL", id)
|
||||
|
||||
if err := query.First(&Partner).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get by id Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
Partner.Partner.Balance = Partner.WalletBalance
|
||||
Partner.Partner.AdminName = Partner.AdminName
|
||||
Partner.Partner.AdminPhoneNumber = Partner.AdminPhoneNumber
|
||||
Partner.Partner.AdminEmail = Partner.AdminEmail
|
||||
|
||||
return &entity.PartnerDB{Partner.Partner}, nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) GetAll(ctx context.Context, req entity.PartnerSearch) (entity.PartnerList, int, error) {
|
||||
var partners []*entity.PartnerDBSearch
|
||||
var total int64
|
||||
|
||||
query := b.db.Table("partners p").
|
||||
Select("p.*, w.balance as wallet_balance, u.name as admin_name, u.email as admin_email, u.phone_number as admin_phone_number").
|
||||
Joins("LEFT JOIN wallets w ON w.partner_id = p.id").
|
||||
Joins("LEFT JOIN users u ON p.admin_user_id = u.id").
|
||||
Where("p.deleted_at IS NULL")
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("p.name ILIKE ?", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("p.name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.PartnerID != nil {
|
||||
query = query.Where("p.id = ?", req.PartnerID)
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
// Find partners with joined wallet balances
|
||||
if err := query.Find(&partners).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting all partners", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Counting total records
|
||||
if err := b.db.Table("partners p").
|
||||
Joins("LEFT JOIN wallets w ON w.partner_id = p.id").
|
||||
Where("p.deleted_at IS NULL").
|
||||
Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when counting partners", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
partnersSearchResult := entity.PartnerList{}
|
||||
|
||||
for _, partner := range partners {
|
||||
partner.Balance = partner.WalletBalance
|
||||
partner.Partner.AdminName = partner.AdminName
|
||||
partner.Partner.AdminPhoneNumber = partner.AdminPhoneNumber
|
||||
partner.Partner.AdminEmail = partner.AdminEmail
|
||||
partnersSearchResult = append(partnersSearchResult, &entity.PartnerDB{partner.Partner})
|
||||
}
|
||||
|
||||
return partnersSearchResult, int(total), nil
|
||||
|
||||
}
|
||||
func (b *PartnerRepository) Delete(ctx context.Context, id int64) error {
|
||||
Partner := new(entity.PartnerDB)
|
||||
Partner.ID = id
|
||||
if err := b.db.Delete(Partner).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type PaymentRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPaymentRepository(db *gorm.DB) *PaymentRepository {
|
||||
return &PaymentRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PaymentRepository) Create(ctx context.Context, payment *entity.Payment) (*entity.Payment, error) {
|
||||
payment.ID = uuid.New()
|
||||
if err := r.db.WithContext(ctx).Create(payment).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when creating payment", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return payment, nil
|
||||
}
|
||||
|
||||
// Update updates an existing payment record in the database
|
||||
func (r *PaymentRepository) Update(ctx context.Context, payment *entity.Payment) (*entity.Payment, error) {
|
||||
if err := r.db.WithContext(ctx).Save(payment).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating payment", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return payment, nil
|
||||
}
|
||||
|
||||
func (r *PaymentRepository) UpdateWithTx(ctx context.Context, tx *gorm.DB, payment *entity.Payment) (*entity.Payment, error) {
|
||||
if err := tx.WithContext(ctx).Save(payment).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating payment", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return payment, nil
|
||||
}
|
||||
|
||||
// FindByID retrieves a payment record by its ID
|
||||
func (r *PaymentRepository) FindByID(ctx context.Context, id uuid.UUID) (*entity.Payment, error) {
|
||||
payment := new(entity.Payment)
|
||||
if err := r.db.WithContext(ctx).First(payment, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding payment by ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return payment, nil
|
||||
}
|
||||
|
||||
func (r *PaymentRepository) FindByOrderAndPartnerID(ctx context.Context, orderID, partnerID int64) (*entity.Payment, error) {
|
||||
payment := new(entity.Payment)
|
||||
orderIDStr := strconv.FormatInt(orderID, 10)
|
||||
partnerIDStr := strconv.FormatInt(partnerID, 10)
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("order_id = ? AND partner_id = ?", orderIDStr, partnerIDStr).
|
||||
First(payment).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding payment by order ID and partner ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return payment, nil
|
||||
}
|
||||
|
||||
// FindByReferenceID retrieves a payment record by its reference ID
|
||||
func (r *PaymentRepository) FindByReferenceID(ctx context.Context, db *gorm.DB, referenceID string) (*entity.Payment, error) {
|
||||
payment := new(entity.Payment)
|
||||
if db == nil {
|
||||
db = r.db
|
||||
}
|
||||
|
||||
if err := db.WithContext(ctx).Where("reference_id = ?", referenceID).First(payment).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding payment by reference ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return payment, nil
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package pg
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/linkqu"
|
||||
mdtrns "enaklo-pos-be/internal/repository/midtrans"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type PaymentGatewayRepo struct {
|
||||
midtransService *mdtrns.ClientService
|
||||
linkquService *linkqu.LinkQuService
|
||||
}
|
||||
|
||||
func NewPaymentGatewayRepo(midtransConfig mdtrns.MidtransConfig, linkquConfig linkqu.LinkQuConfig) *PaymentGatewayRepo {
|
||||
return &PaymentGatewayRepo{
|
||||
midtransService: mdtrns.New(midtransConfig),
|
||||
linkquService: linkqu.NewLinkQuService(linkquConfig),
|
||||
}
|
||||
}
|
||||
|
||||
func (repo *PaymentGatewayRepo) CreatePayment(request entity.PaymentRequest) (*entity.PaymentResponse, error) {
|
||||
return repo.createMidtransPayment(request)
|
||||
}
|
||||
|
||||
func (repo *PaymentGatewayRepo) CreateQRISPayment(request entity.PaymentRequest) (*entity.PaymentResponse, error) {
|
||||
switch request.Provider {
|
||||
case "MIDTRANS":
|
||||
return repo.createMidtransQRISPayment(request)
|
||||
case "LINKQU":
|
||||
return repo.createLinkQuQRISPayment(request)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported payment method for QRIS: %s", request.Provider)
|
||||
}
|
||||
}
|
||||
|
||||
func (repo *PaymentGatewayRepo) CreatePaymentVA(request entity.PaymentRequest) (*entity.PaymentResponse, error) {
|
||||
resp, err := repo.linkquService.CreatePaymentVA(entity.LinkQuRequest{
|
||||
TotalAmount: request.TotalAmount,
|
||||
PaymentReferenceID: request.PaymentReferenceID,
|
||||
CustomerID: request.CustomerID,
|
||||
CustomerName: request.CustomerName,
|
||||
CustomerEmail: request.CustomerEmail,
|
||||
BankCode: request.BankCode,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &entity.PaymentResponse{
|
||||
VirtualAccountNumber: resp.VirtualAccount,
|
||||
BankName: resp.BankName,
|
||||
BankCode: resp.BankCode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repo *PaymentGatewayRepo) createMidtransPayment(request entity.PaymentRequest) (*entity.PaymentResponse, error) {
|
||||
midtransReq := entity.MidtransRequest{
|
||||
PaymentReferenceID: request.PaymentReferenceID,
|
||||
PaymentMethod: request.Provider,
|
||||
TotalAmount: request.TotalAmount,
|
||||
}
|
||||
|
||||
resp, err := repo.midtransService.CreatePayment(midtransReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &entity.PaymentResponse{
|
||||
Token: resp.Token,
|
||||
RedirectURL: resp.RedirectURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repo *PaymentGatewayRepo) createLinkQuPayment(request entity.PaymentRequest) (*entity.PaymentResponse, error) {
|
||||
linkquReq := entity.LinkQuRequest{
|
||||
PaymentReferenceID: request.PaymentReferenceID,
|
||||
TotalAmount: request.TotalAmount,
|
||||
CustomerID: request.CustomerID,
|
||||
CustomerName: request.CustomerName,
|
||||
CustomerPhone: request.CustomerPhone,
|
||||
CustomerEmail: request.CustomerEmail,
|
||||
}
|
||||
|
||||
resp, err := repo.linkquService.CreateQrisPayment(linkquReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &entity.PaymentResponse{
|
||||
Token: resp.PartnerReff2,
|
||||
RedirectURL: resp.ImageQRIS,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repo *PaymentGatewayRepo) createMidtransQRISPayment(request entity.PaymentRequest) (*entity.PaymentResponse, error) {
|
||||
midtransReq := entity.MidtransRequest{
|
||||
PaymentReferenceID: request.PaymentReferenceID,
|
||||
PaymentMethod: "QRIS",
|
||||
TotalAmount: request.TotalAmount,
|
||||
}
|
||||
|
||||
resp, err := repo.midtransService.CreateQrisPayment(midtransReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &entity.PaymentResponse{
|
||||
QRCodeURL: resp.QrCodeUrl,
|
||||
OrderID: resp.OrderID,
|
||||
Amount: resp.Amount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repo *PaymentGatewayRepo) createLinkQuQRISPayment(request entity.PaymentRequest) (*entity.PaymentResponse, error) {
|
||||
linkquReq := entity.LinkQuRequest{
|
||||
PaymentReferenceID: request.PaymentReferenceID,
|
||||
TotalAmount: request.TotalAmount,
|
||||
CustomerID: request.CustomerID,
|
||||
CustomerName: request.CustomerName,
|
||||
CustomerPhone: request.CustomerPhone,
|
||||
CustomerEmail: request.CustomerEmail,
|
||||
}
|
||||
|
||||
resp, err := repo.linkquService.CreateQrisPayment(linkquReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &entity.PaymentResponse{
|
||||
QRCodeURL: resp.ImageQRIS,
|
||||
OrderID: resp.PartnerReff,
|
||||
Amount: resp.Amount,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PaymentMethodRepository interface {
|
||||
Create(ctx context.Context, paymentMethod *entities.PaymentMethod) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*entities.PaymentMethod, error)
|
||||
GetByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.PaymentMethod, error)
|
||||
GetActiveByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.PaymentMethod, error)
|
||||
Update(ctx context.Context, paymentMethod *entities.PaymentMethod) error
|
||||
Delete(ctx context.Context, id uuid.UUID) error
|
||||
List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.PaymentMethod, int64, error)
|
||||
Count(ctx context.Context, filters map[string]interface{}) (int64, error)
|
||||
ExistsByName(ctx context.Context, organizationID uuid.UUID, name string, excludeID *uuid.UUID) (bool, error)
|
||||
}
|
||||
|
||||
type PaymentMethodRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPaymentMethodRepositoryImpl(db *gorm.DB) *PaymentMethodRepositoryImpl {
|
||||
return &PaymentMethodRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) Create(ctx context.Context, paymentMethod *entities.PaymentMethod) error {
|
||||
return r.db.WithContext(ctx).Create(paymentMethod).Error
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.PaymentMethod, error) {
|
||||
var paymentMethod entities.PaymentMethod
|
||||
err := r.db.WithContext(ctx).First(&paymentMethod, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &paymentMethod, nil
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) GetByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.PaymentMethod, error) {
|
||||
var paymentMethods []*entities.PaymentMethod
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ?", organizationID).Find(&paymentMethods).Error
|
||||
return paymentMethods, err
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) GetActiveByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.PaymentMethod, error) {
|
||||
var paymentMethods []*entities.PaymentMethod
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ? AND is_active = ?", organizationID, true).Find(&paymentMethods).Error
|
||||
return paymentMethods, err
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) Update(ctx context.Context, paymentMethod *entities.PaymentMethod) error {
|
||||
return r.db.WithContext(ctx).Save(paymentMethod).Error
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.PaymentMethod{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.PaymentMethod, int64, error) {
|
||||
var paymentMethods []*entities.PaymentMethod
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.PaymentMethod{})
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Where("name ILIKE ? OR processor ILIKE ?", searchValue, searchValue)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Find(&paymentMethods).Error
|
||||
return paymentMethods, total, err
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.PaymentMethod{})
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Where("name ILIKE ? OR processor ILIKE ?", searchValue, searchValue)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *PaymentMethodRepositoryImpl) ExistsByName(ctx context.Context, organizationID uuid.UUID, name string, excludeID *uuid.UUID) (bool, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.PaymentMethod{}).Where("organization_id = ? AND name = ?", organizationID, name)
|
||||
|
||||
if excludeID != nil {
|
||||
query = query.Where("id != ?", *excludeID)
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PaymentRepository interface {
|
||||
Create(ctx context.Context, payment *entities.Payment) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*entities.Payment, error)
|
||||
GetByOrderID(ctx context.Context, orderID uuid.UUID) ([]*entities.Payment, error)
|
||||
Update(ctx context.Context, payment *entities.Payment) error
|
||||
Delete(ctx context.Context, id uuid.UUID) error
|
||||
RefundPayment(ctx context.Context, id uuid.UUID, refundAmount float64, reason string, refundedBy uuid.UUID) error
|
||||
UpdateStatus(ctx context.Context, id uuid.UUID, status entities.PaymentTransactionStatus) error
|
||||
GetTotalPaidByOrderID(ctx context.Context, orderID uuid.UUID) (float64, error)
|
||||
}
|
||||
|
||||
type PaymentRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPaymentRepositoryImpl(db *gorm.DB) *PaymentRepositoryImpl {
|
||||
return &PaymentRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) Create(ctx context.Context, payment *entities.Payment) error {
|
||||
return r.db.WithContext(ctx).Create(payment).Error
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.Payment, error) {
|
||||
var payment entities.Payment
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("PaymentMethod").
|
||||
Preload("PaymentOrderItems").
|
||||
First(&payment, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &payment, nil
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) GetByOrderID(ctx context.Context, orderID uuid.UUID) ([]*entities.Payment, error) {
|
||||
var payments []*entities.Payment
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("PaymentMethod").
|
||||
Preload("PaymentOrderItems").
|
||||
Where("order_id = ?", orderID).
|
||||
Find(&payments).Error
|
||||
return payments, err
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) Update(ctx context.Context, payment *entities.Payment) error {
|
||||
return r.db.WithContext(ctx).Save(payment).Error
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.Payment{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) RefundPayment(ctx context.Context, id uuid.UUID, refundAmount float64, reason string, refundedBy uuid.UUID) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).Model(&entities.Payment{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"refund_amount": refundAmount,
|
||||
"refund_reason": reason,
|
||||
"refunded_at": now,
|
||||
"refunded_by": refundedBy,
|
||||
"status": entities.PaymentTransactionStatusRefunded,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) UpdateStatus(ctx context.Context, id uuid.UUID, status entities.PaymentTransactionStatus) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.Payment{}).
|
||||
Where("id = ?", id).
|
||||
Update("status", status).Error
|
||||
}
|
||||
|
||||
func (r *PaymentRepositoryImpl) GetTotalPaidByOrderID(ctx context.Context, orderID uuid.UUID) (float64, error) {
|
||||
var total float64
|
||||
err := r.db.WithContext(ctx).Model(&entities.Payment{}).
|
||||
Where("order_id = ? AND status = ?", orderID, entities.PaymentTransactionStatusCompleted).
|
||||
Select("COALESCE(SUM(amount), 0)").
|
||||
Scan(&total).Error
|
||||
return total, err
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/models"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ProductRepository interface {
|
||||
GetProductsByIDs(ctx mycontext.Context, ids []int64, partnerID int64) ([]*entity.Product, error)
|
||||
GetProductDetails(ctx mycontext.Context, productIDs []int64, partnerID int64) (*entity.ProductDetails, error)
|
||||
GetProductsByPartnerID(ctx mycontext.Context, req entity.ProductSearch) ([]*entity.Product, int64, error)
|
||||
}
|
||||
|
||||
type productRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewproductRepository(db *gorm.DB) *productRepository {
|
||||
return &productRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *productRepository) GetProductsByIDs(ctx mycontext.Context, ids []int64, partnerID int64) ([]*entity.Product, error) {
|
||||
if len(ids) == 0 {
|
||||
return []*entity.Product{}, nil
|
||||
}
|
||||
|
||||
var productsDB []models.ProductDB
|
||||
|
||||
if err := r.db.Where("id IN ? AND partner_id = ?", ids, partnerID).Find(&productsDB).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to find products")
|
||||
}
|
||||
|
||||
products := make([]*entity.Product, 0, len(productsDB))
|
||||
for i := range productsDB {
|
||||
product := r.toDomainProductModel(&productsDB[i])
|
||||
products = append(products, product)
|
||||
}
|
||||
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (r *productRepository) GetProductDetails(ctx mycontext.Context, productIDs []int64, partnerID int64) (*entity.ProductDetails, error) {
|
||||
if len(productIDs) == 0 {
|
||||
return &entity.ProductDetails{
|
||||
Products: make(map[int64]*entity.Product),
|
||||
}, nil
|
||||
}
|
||||
|
||||
var productsDB []models.ProductDB
|
||||
|
||||
if err := r.db.Where("id IN ? AND partner_id = ?", productIDs, partnerID).Find(&productsDB).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to find products")
|
||||
}
|
||||
|
||||
productMap := make(map[int64]*entity.Product, len(productsDB))
|
||||
|
||||
for i := range productsDB {
|
||||
product := r.toDomainProductModel(&productsDB[i])
|
||||
productMap[product.ID] = product
|
||||
}
|
||||
|
||||
return &entity.ProductDetails{
|
||||
Products: productMap,
|
||||
PartnerID: partnerID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *productRepository) toDomainProductModel(dbModel *models.ProductDB) *entity.Product {
|
||||
return &entity.Product{
|
||||
ID: dbModel.ID,
|
||||
PartnerID: dbModel.PartnerID,
|
||||
Name: dbModel.Name,
|
||||
Description: dbModel.Description,
|
||||
Price: dbModel.Price,
|
||||
Type: dbModel.Type,
|
||||
Status: dbModel.Status,
|
||||
CreatedAt: dbModel.CreatedAt,
|
||||
UpdatedAt: dbModel.UpdatedAt,
|
||||
Image: dbModel.Image,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *productRepository) GetProductsByPartnerID(ctx mycontext.Context, req entity.ProductSearch) ([]*entity.Product, int64, error) {
|
||||
if req.PartnerID == 0 {
|
||||
return nil, 0, nil
|
||||
}
|
||||
query := r.db.Where("partner_id = ?", req.PartnerID)
|
||||
|
||||
if req.Type != "" {
|
||||
query = query.Where("type = ?", req.Type)
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Model(&models.ProductDB{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, errors.Wrap(err, "failed to count products")
|
||||
}
|
||||
|
||||
var productsDB []models.ProductDB
|
||||
|
||||
if err := query.Find(&productsDB).Error; err != nil {
|
||||
return nil, 0, errors.Wrap(err, "failed to find products")
|
||||
}
|
||||
|
||||
products := make([]*entity.Product, 0, len(productsDB))
|
||||
for i := range productsDB {
|
||||
product := r.toDomainProductModel(&productsDB[i])
|
||||
products = append(products, product)
|
||||
}
|
||||
|
||||
return products, total, nil
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ProductRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewProductRepositoryImpl(db *gorm.DB) *ProductRepositoryImpl {
|
||||
return &ProductRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) Create(ctx context.Context, product *entities.Product) error {
|
||||
return r.db.WithContext(ctx).Create(product).Error
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.Product, error) {
|
||||
var product entities.Product
|
||||
err := r.db.WithContext(ctx).First(&product, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &product, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetWithCategory(ctx context.Context, id uuid.UUID) (*entities.Product, error) {
|
||||
var product entities.Product
|
||||
err := r.db.WithContext(ctx).Preload("Category").Preload("ProductVariants").First(&product, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &product, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetWithRelations(ctx context.Context, id uuid.UUID) (*entities.Product, error) {
|
||||
var product entities.Product
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Category").
|
||||
Preload("ProductVariants").
|
||||
Preload("Inventory").
|
||||
First(&product, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &product, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetByOrganization(ctx context.Context, organizationID uuid.UUID) ([]*entities.Product, error) {
|
||||
var products []*entities.Product
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ?", organizationID).Find(&products).Error
|
||||
return products, err
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetByCategory(ctx context.Context, categoryID uuid.UUID) ([]*entities.Product, error) {
|
||||
var products []*entities.Product
|
||||
err := r.db.WithContext(ctx).Where("category_id = ?", categoryID).Find(&products).Error
|
||||
return products, err
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetByBusinessType(ctx context.Context, businessType string) ([]*entities.Product, error) {
|
||||
var products []*entities.Product
|
||||
err := r.db.WithContext(ctx).Where("business_type = ?", businessType).Find(&products).Error
|
||||
return products, err
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetActiveByCategoryID(ctx context.Context, categoryID uuid.UUID) ([]*entities.Product, error) {
|
||||
var products []*entities.Product
|
||||
err := r.db.WithContext(ctx).Where("category_id = ? AND is_active = ?", categoryID, true).Find(&products).Error
|
||||
return products, err
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) Update(ctx context.Context, product *entities.Product) error {
|
||||
return r.db.WithContext(ctx).Save(product).Error
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.Product{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.Product, int64, error) {
|
||||
var products []*entities.Product
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.Product{}).Preload("Category").Preload("ProductVariants")
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Where("name ILIKE ? OR description ILIKE ? OR sku ILIKE ?", searchValue, searchValue, searchValue)
|
||||
case "price_min":
|
||||
query = query.Where("price >= ?", value)
|
||||
case "price_max":
|
||||
query = query.Where("price <= ?", value)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Find(&products).Error
|
||||
return products, total, err
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.Product{})
|
||||
|
||||
for key, value := range filters {
|
||||
switch key {
|
||||
case "search":
|
||||
searchValue := "%" + value.(string) + "%"
|
||||
query = query.Where("name ILIKE ? OR description ILIKE ? OR sku ILIKE ?", searchValue, searchValue, searchValue)
|
||||
case "price_min":
|
||||
query = query.Where("price >= ?", value)
|
||||
case "price_max":
|
||||
query = query.Where("price <= ?", value)
|
||||
default:
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetBySKU(ctx context.Context, organizationID uuid.UUID, sku string) (*entities.Product, error) {
|
||||
var product entities.Product
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ? AND sku = ?", organizationID, sku).First(&product).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &product, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) ExistsBySKU(ctx context.Context, organizationID uuid.UUID, sku string, excludeID *uuid.UUID) (bool, error) {
|
||||
query := r.db.WithContext(ctx).Model(&entities.Product{}).Where("organization_id = ? AND sku = ?", organizationID, sku)
|
||||
|
||||
if excludeID != nil {
|
||||
query = query.Where("id != ?", *excludeID)
|
||||
}
|
||||
|
||||
var count int64
|
||||
err := query.Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetByName(ctx context.Context, organizationID uuid.UUID, name string) (*entities.Product, error) {
|
||||
var product entities.Product
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ? AND name = ?", organizationID, name).First(&product).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &product, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) ExistsByName(ctx context.Context, organizationID uuid.UUID, name string, excludeID *uuid.UUID) (bool, error) {
|
||||
query := r.db.WithContext(ctx).Model(&entities.Product{}).Where("organization_id = ? AND name = ?", organizationID, name)
|
||||
|
||||
if excludeID != nil {
|
||||
query = query.Where("id != ?", *excludeID)
|
||||
}
|
||||
|
||||
var count int64
|
||||
err := query.Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) UpdateActiveStatus(ctx context.Context, id uuid.UUID, isActive bool) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.Product{}).
|
||||
Where("id = ?", id).
|
||||
Update("is_active", isActive).Error
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetLowCostProducts(ctx context.Context, organizationID uuid.UUID, maxCost float64) ([]*entities.Product, error) {
|
||||
var products []*entities.Product
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ? AND cost <= ? AND is_active = ?", organizationID, maxCost, true).Find(&products).Error
|
||||
return products, err
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ProductVariantRepository interface {
|
||||
Create(ctx context.Context, variant *entities.ProductVariant) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*entities.ProductVariant, error)
|
||||
GetByProductID(ctx context.Context, productID uuid.UUID) ([]*entities.ProductVariant, error)
|
||||
GetByProductAndName(ctx context.Context, productID uuid.UUID, name string) (*entities.ProductVariant, error)
|
||||
Update(ctx context.Context, variant *entities.ProductVariant) error
|
||||
Delete(ctx context.Context, id uuid.UUID) error
|
||||
ExistsByName(ctx context.Context, productID uuid.UUID, name string, excludeID *uuid.UUID) (bool, error)
|
||||
}
|
||||
|
||||
type ProductVariantRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewProductVariantRepositoryImpl(db *gorm.DB) *ProductVariantRepositoryImpl {
|
||||
return &ProductVariantRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ProductVariantRepositoryImpl) Create(ctx context.Context, variant *entities.ProductVariant) error {
|
||||
return r.db.WithContext(ctx).Create(variant).Error
|
||||
}
|
||||
|
||||
func (r *ProductVariantRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.ProductVariant, error) {
|
||||
var variant entities.ProductVariant
|
||||
err := r.db.WithContext(ctx).First(&variant, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &variant, nil
|
||||
}
|
||||
|
||||
func (r *ProductVariantRepositoryImpl) GetByProductID(ctx context.Context, productID uuid.UUID) ([]*entities.ProductVariant, error) {
|
||||
var variants []*entities.ProductVariant
|
||||
err := r.db.WithContext(ctx).Where("product_id = ?", productID).Find(&variants).Error
|
||||
return variants, err
|
||||
}
|
||||
|
||||
func (r *ProductVariantRepositoryImpl) GetByProductAndName(ctx context.Context, productID uuid.UUID, name string) (*entities.ProductVariant, error) {
|
||||
var variant entities.ProductVariant
|
||||
err := r.db.WithContext(ctx).Where("product_id = ? AND name = ?", productID, name).First(&variant).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &variant, nil
|
||||
}
|
||||
|
||||
func (r *ProductVariantRepositoryImpl) Update(ctx context.Context, variant *entities.ProductVariant) error {
|
||||
return r.db.WithContext(ctx).Save(variant).Error
|
||||
}
|
||||
|
||||
func (r *ProductVariantRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.ProductVariant{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *ProductVariantRepositoryImpl) ExistsByName(ctx context.Context, productID uuid.UUID, name string, excludeID *uuid.UUID) (bool, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.ProductVariant{}).Where("product_id = ? AND name = ?", productID, name)
|
||||
|
||||
if excludeID != nil {
|
||||
query = query.Where("id != ?", *excludeID)
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
package products
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ProductRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewProductRepository(db *gorm.DB) *ProductRepository {
|
||||
return &ProductRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *ProductRepository) CreateProduct(ctx context.Context, product *entity.ProductDB) (*entity.ProductDB, error) {
|
||||
err := b.db.Create(product).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create product", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) UpdateProduct(ctx context.Context, product *entity.ProductDB) (*entity.ProductDB, error) {
|
||||
if err := b.db.Save(product).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update product", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) GetProductByID(ctx context.Context, id int64) (*entity.ProductDB, error) {
|
||||
product := new(entity.ProductDB)
|
||||
if err := b.db.Preload("Category").First(product, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get by id product", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) GetProductByPartnerIDAndSiteID(ctx context.Context, partnerID, siteID int64) (entity.ProductList, error) {
|
||||
var products []*entity.ProductDB
|
||||
if err := b.db.WithContext(ctx).Where("partner_id = ? AND site_id = ?", partnerID, siteID).Find(&products).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding product by partner ID and site id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) GetProductsBySiteID(ctx context.Context, siteID int64) (entity.ProductList, error) {
|
||||
var products []*entity.ProductDB
|
||||
if err := b.db.WithContext(ctx).Where("site_id = ?", siteID).Find(&products).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding product by partner ID and site id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) GetAllProducts(ctx context.Context, req entity.ProductSearch) (entity.ProductList, int, error) {
|
||||
var products []*entity.ProductDB
|
||||
var total int64
|
||||
|
||||
query := b.db
|
||||
query = query.Where("deleted_at is null")
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.Type != "" {
|
||||
query = query.Where("type = ? ", req.Type)
|
||||
}
|
||||
|
||||
if req.CategoryID > 0 {
|
||||
query = query.Where("category_id = ? ", req.CategoryID)
|
||||
}
|
||||
|
||||
if req.PartnerID > 0 {
|
||||
query = query.Where("partner_id = ? ", req.PartnerID)
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
if err := query.Preload("Category").Find(&products).Order("id ASC").Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all products", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if err := b.db.Model(&entity.ProductDB{}).Where(query).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count products", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return products, int(total), nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) DeleteProduct(ctx context.Context, id int64) error {
|
||||
product := new(entity.ProductDB)
|
||||
product.ID = id
|
||||
if err := b.db.Delete(product).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) GetProductsByIDs(ctx context.Context, ids []int64, partnerID int64) ([]*entity.ProductDB, error) {
|
||||
var products []*entity.ProductDB
|
||||
if err := b.db.Where("partner_id = ? AND id IN ?", partnerID, ids).Find(&products).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting products by IDs and partner ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type QueryBuilder[T any] struct {
|
||||
db *gorm.DB
|
||||
model T
|
||||
}
|
||||
|
||||
func NewQueryBuilder[T any](db *gorm.DB) *QueryBuilder[T] {
|
||||
var model T
|
||||
return &QueryBuilder[T]{
|
||||
db: db,
|
||||
model: model,
|
||||
}
|
||||
}
|
||||
|
||||
type Filter struct {
|
||||
Field string
|
||||
Operator string // "=", "!=", ">", "<", ">=", "<=", "LIKE", "IN", "NOT IN", "IS NULL", "IS NOT NULL"
|
||||
Value interface{}
|
||||
}
|
||||
|
||||
type QueryOptions struct {
|
||||
Filters []Filter
|
||||
Limit int
|
||||
Offset int
|
||||
OrderBy []string
|
||||
Preloads []string
|
||||
GroupBy []string
|
||||
Having []Filter
|
||||
Distinct []string
|
||||
CountOnly bool
|
||||
}
|
||||
|
||||
func (qb *QueryBuilder[T]) BuildQuery(options QueryOptions) *gorm.DB {
|
||||
query := qb.db.Model(&qb.model)
|
||||
|
||||
for _, filter := range options.Filters {
|
||||
query = qb.applyFilter(query, filter)
|
||||
}
|
||||
|
||||
if len(options.Distinct) > 0 {
|
||||
for _, distinct := range options.Distinct {
|
||||
query = query.Distinct(distinct)
|
||||
}
|
||||
}
|
||||
|
||||
if len(options.GroupBy) > 0 {
|
||||
for _, groupBy := range options.GroupBy {
|
||||
query = query.Group(groupBy)
|
||||
}
|
||||
}
|
||||
|
||||
for _, having := range options.Having {
|
||||
query = qb.applyFilter(query, having)
|
||||
}
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
func (qb *QueryBuilder[T]) applyFilter(query *gorm.DB, filter Filter) *gorm.DB {
|
||||
switch filter.Operator {
|
||||
case "=", "":
|
||||
return query.Where(filter.Field+" = ?", filter.Value)
|
||||
case "!=":
|
||||
return query.Where(filter.Field+" != ?", filter.Value)
|
||||
case ">":
|
||||
return query.Where(filter.Field+" > ?", filter.Value)
|
||||
case "<":
|
||||
return query.Where(filter.Field+" < ?", filter.Value)
|
||||
case ">=":
|
||||
return query.Where(filter.Field+" >= ?", filter.Value)
|
||||
case "<=":
|
||||
return query.Where(filter.Field+" <= ?", filter.Value)
|
||||
case "LIKE":
|
||||
return query.Where(filter.Field+" LIKE ?", filter.Value)
|
||||
case "IN":
|
||||
return query.Where(filter.Field+" IN ?", filter.Value)
|
||||
case "NOT IN":
|
||||
return query.Where(filter.Field+" NOT IN ?", filter.Value)
|
||||
case "IS NULL":
|
||||
return query.Where(filter.Field + " IS NULL")
|
||||
case "IS NOT NULL":
|
||||
return query.Where(filter.Field + " IS NOT NULL")
|
||||
case "BETWEEN":
|
||||
if values, ok := filter.Value.([]interface{}); ok && len(values) == 2 {
|
||||
return query.Where(filter.Field+" BETWEEN ? AND ?", values[0], values[1])
|
||||
}
|
||||
return query
|
||||
default:
|
||||
return query.Where(filter.Field+" = ?", filter.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func (qb *QueryBuilder[T]) ExecuteQuery(baseQuery *gorm.DB, options QueryOptions) *gorm.DB {
|
||||
query := baseQuery.Session(&gorm.Session{})
|
||||
|
||||
if len(options.OrderBy) > 0 {
|
||||
for _, orderBy := range options.OrderBy {
|
||||
query = query.Order(orderBy)
|
||||
}
|
||||
}
|
||||
|
||||
for _, preload := range options.Preloads {
|
||||
query = query.Preload(preload)
|
||||
}
|
||||
|
||||
if options.Limit > 0 {
|
||||
query = query.Limit(options.Limit)
|
||||
}
|
||||
|
||||
if options.Offset > 0 {
|
||||
query = query.Offset(options.Offset)
|
||||
}
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
func (qb *QueryBuilder[T]) Count(baseQuery *gorm.DB) (int64, error) {
|
||||
var count int64
|
||||
if err := baseQuery.Count(&count).Error; err != nil {
|
||||
return 0, errors.Wrap(err, "failed to count records")
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (qb *QueryBuilder[T]) Find(query *gorm.DB) ([]T, error) {
|
||||
var results []T
|
||||
if err := query.Find(&results).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to find records")
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func (qb *QueryBuilder[T]) First(query *gorm.DB) (*T, error) {
|
||||
var result T
|
||||
if err := query.First(&result).Error; err != nil {
|
||||
return nil, errors.Wrap(err, "failed to find record")
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func Equal(field string, value interface{}) Filter {
|
||||
return Filter{Field: field, Operator: "=", Value: value}
|
||||
}
|
||||
|
||||
func NotEqual(field string, value interface{}) Filter {
|
||||
return Filter{Field: field, Operator: "!=", Value: value}
|
||||
}
|
||||
|
||||
func GreaterThan(field string, value interface{}) Filter {
|
||||
return Filter{Field: field, Operator: ">", Value: value}
|
||||
}
|
||||
|
||||
func LessThan(field string, value interface{}) Filter {
|
||||
return Filter{Field: field, Operator: "<", Value: value}
|
||||
}
|
||||
|
||||
func GreaterEqual(field string, value interface{}) Filter {
|
||||
return Filter{Field: field, Operator: ">=", Value: value}
|
||||
}
|
||||
|
||||
func LessEqual(field string, value interface{}) Filter {
|
||||
return Filter{Field: field, Operator: "<=", Value: value}
|
||||
}
|
||||
|
||||
func Like(field string, value string) Filter {
|
||||
return Filter{Field: field, Operator: "LIKE", Value: value}
|
||||
}
|
||||
|
||||
func In(field string, values interface{}) Filter {
|
||||
return Filter{Field: field, Operator: "IN", Value: values}
|
||||
}
|
||||
|
||||
func NotIn(field string, values interface{}) Filter {
|
||||
return Filter{Field: field, Operator: "NOT IN", Value: values}
|
||||
}
|
||||
|
||||
func IsNull(field string) Filter {
|
||||
return Filter{Field: field, Operator: "IS NULL"}
|
||||
}
|
||||
|
||||
func IsNotNull(field string) Filter {
|
||||
return Filter{Field: field, Operator: "IS NOT NULL"}
|
||||
}
|
||||
|
||||
func Between(field string, start, end interface{}) Filter {
|
||||
return Filter{Field: field, Operator: "BETWEEN", Value: []interface{}{start, end}}
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/repository/brevo"
|
||||
"enaklo-pos-be/internal/repository/license"
|
||||
"enaklo-pos-be/internal/repository/linkqu"
|
||||
mdtrns "enaklo-pos-be/internal/repository/midtrans"
|
||||
"enaklo-pos-be/internal/repository/orders"
|
||||
"enaklo-pos-be/internal/repository/oss"
|
||||
"enaklo-pos-be/internal/repository/partners"
|
||||
"enaklo-pos-be/internal/repository/payment"
|
||||
pg "enaklo-pos-be/internal/repository/payment_gateway"
|
||||
"enaklo-pos-be/internal/repository/products"
|
||||
"enaklo-pos-be/internal/repository/sites"
|
||||
transactions "enaklo-pos-be/internal/repository/transaction"
|
||||
"enaklo-pos-be/internal/repository/users"
|
||||
repository "enaklo-pos-be/internal/repository/wallet"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"enaklo-pos-be/config"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"enaklo-pos-be/internal/repository/auth"
|
||||
"enaklo-pos-be/internal/repository/crypto"
|
||||
)
|
||||
|
||||
type RepoManagerImpl struct {
|
||||
Crypto Crypto
|
||||
Auth Auth
|
||||
User User
|
||||
Product Product
|
||||
Order Order
|
||||
OSS OSSRepository
|
||||
Partner PartnerRepository
|
||||
Site SiteRepository
|
||||
Trx Trx
|
||||
Wallet WalletRepository
|
||||
Midtrans Midtrans
|
||||
Payment Payment
|
||||
EmailService EmailService
|
||||
License License
|
||||
Transaction TransactionRepository
|
||||
PG PaymentGateway
|
||||
LinkQu LinkQu
|
||||
|
||||
OrderRepo OrderRepository
|
||||
InProgressOrderRepo InProgressOrderRepository
|
||||
CustomerRepo CustomerRepo
|
||||
ProductRepo ProductRepository
|
||||
TransactionRepo TransactionRepo
|
||||
MemberRepository MemberRepository
|
||||
PartnerSetting PartnerSettingsRepository
|
||||
UndianRepository UndianRepo
|
||||
CashierSeasionRepo CashierSessionRepository
|
||||
CategoryRepository CategoryRepository
|
||||
}
|
||||
|
||||
func NewRepoManagerImpl(db *gorm.DB, cfg *config.Config) *RepoManagerImpl {
|
||||
return &RepoManagerImpl{
|
||||
Crypto: crypto.NewCrypto(cfg.Auth()),
|
||||
Auth: auth.NewAuthRepository(db),
|
||||
User: users.NewUserRepository(db),
|
||||
Product: products.NewProductRepository(db),
|
||||
Order: orders.NewOrderRepository(db),
|
||||
OSS: oss.NewOssRepositoryImpl(cfg.OSSConfig),
|
||||
Partner: partners.NewPartnerRepository(db),
|
||||
Site: sites.NewSiteRepository(db),
|
||||
Trx: NewTransactionManager(db),
|
||||
Wallet: repository.NewWalletRepository(db),
|
||||
Midtrans: mdtrns.New(&cfg.Midtrans),
|
||||
Payment: payment.NewPaymentRepository(db),
|
||||
EmailService: brevo.New(&cfg.Brevo),
|
||||
License: license.NewLicenseRepository(db),
|
||||
Transaction: transactions.NewTransactionRepository(db),
|
||||
PG: pg.NewPaymentGatewayRepo(&cfg.Midtrans, &cfg.LinkQu),
|
||||
LinkQu: linkqu.NewLinkQuService(&cfg.LinkQu),
|
||||
|
||||
OrderRepo: NeworderRepository(db),
|
||||
CustomerRepo: NewCustomerRepository(db),
|
||||
ProductRepo: NewproductRepository(db),
|
||||
TransactionRepo: NewTransactionRepository(db),
|
||||
MemberRepository: NewMemberRepository(db),
|
||||
InProgressOrderRepo: NewInProgressOrderRepository(db),
|
||||
PartnerSetting: NewPartnerSettingsRepository(db),
|
||||
UndianRepository: NewUndianRepository(db),
|
||||
CashierSeasionRepo: NewCashierSessionRepository(db),
|
||||
CategoryRepository: NewCategoryRepository(db),
|
||||
}
|
||||
}
|
||||
|
||||
type Auth interface {
|
||||
CheckExistsUserAccount(ctx context.Context, email string) (*entity.UserDB, error)
|
||||
CheckExistsUserAccountByID(ctx context.Context, userID int64) (*entity.UserDB, error)
|
||||
UpdatePassword(ctx context.Context, trx *gorm.DB, newHashedPassword string, userID int64, resetPassword bool) error
|
||||
}
|
||||
|
||||
type Crypto interface {
|
||||
CompareHashAndPassword(hash string, password string) bool
|
||||
ValidateWT(tokenString string) (*jwt.Token, error)
|
||||
GenerateJWT(user *entity.User) (string, error)
|
||||
GenerateJWTReseetPassword(user *entity.User) (string, error)
|
||||
GenerateJWTOrder(order *entity.Order) (string, error)
|
||||
GenerateJWTOrderInquiry(inquiry *entity.OrderInquiry) (string, error)
|
||||
ValidateJWTOrderInquiry(tokenString string) (int64, string, error)
|
||||
ValidateJWTOrder(tokenString string) (int64, int64, error)
|
||||
ValidateResetPassword(tokenString string) (int64, error)
|
||||
ParseAndValidateJWT(token string) (*entity.JWTAuthClaims, error)
|
||||
GenerateJWTWithdraw(req *entity.WalletWithdrawRequest) (string, error)
|
||||
ValidateJWTWithdraw(tokenString string) (*entity.WalletWithdrawRequest, error)
|
||||
GenerateJWTCustomer(user *entity.Customer) (string, error)
|
||||
ParseAndValidateJWTCustomer(tokenString string) (*entity.JWTAuthClaimsCustomer, error)
|
||||
}
|
||||
|
||||
type User interface {
|
||||
Create(ctx context.Context, user *entity.UserDB) (*entity.UserDB, error)
|
||||
CreateWithTx(ctx context.Context, tx *gorm.DB, user *entity.UserDB) (*entity.UserDB, error)
|
||||
GetAllUsers(ctx context.Context, req entity.UserSearch) (entity.UserList, int, error)
|
||||
GetAllCustomer(ctx context.Context, req entity.CustomerSearch) (entity.CustomerList, int, error)
|
||||
GetUserByID(ctx context.Context, id int64) (*entity.UserDB, error)
|
||||
GetPartnerAdmin(ctx context.Context, partnerID int64) (*entity.UserDB, error)
|
||||
GetUserByEmail(ctx context.Context, email string) (*entity.UserDB, error)
|
||||
UpdateUser(ctx context.Context, user *entity.UserDB) (*entity.UserDB, error)
|
||||
UpdateUserWithTx(ctx context.Context, tx *gorm.DB, user *entity.UserDB) (*entity.UserDB, error)
|
||||
CountUsersByRoleAndSiteOrPartner(ctx context.Context, roleID int, siteID *int64) (int, error)
|
||||
}
|
||||
|
||||
type Studio interface {
|
||||
CreateStudio(ctx context.Context, studio *entity.StudioDB) (*entity.StudioDB, error)
|
||||
UpdateStudio(ctx context.Context, studio *entity.StudioDB) (*entity.StudioDB, error)
|
||||
GetStudioByID(ctx context.Context, id int64) (*entity.StudioDB, error)
|
||||
SearchStudios(ctx context.Context, req entity.StudioSearch) (entity.StudioList, int, error)
|
||||
}
|
||||
|
||||
type Product interface {
|
||||
CreateProduct(ctx context.Context, product *entity.ProductDB) (*entity.ProductDB, error)
|
||||
UpdateProduct(ctx context.Context, product *entity.ProductDB) (*entity.ProductDB, error)
|
||||
GetProductByID(ctx context.Context, id int64) (*entity.ProductDB, error)
|
||||
GetProductByPartnerIDAndSiteID(ctx context.Context, partnerID, siteID int64) (entity.ProductList, error)
|
||||
GetAllProducts(ctx context.Context, req entity.ProductSearch) (entity.ProductList, int, error)
|
||||
DeleteProduct(ctx context.Context, id int64) error
|
||||
GetProductsByIDs(ctx context.Context, ids []int64, partnerID int64) ([]*entity.ProductDB, error)
|
||||
GetProductsBySiteID(ctx context.Context, siteID int64) (entity.ProductList, error)
|
||||
}
|
||||
|
||||
type Order interface {
|
||||
Create(ctx context.Context, order *entity.Order) (*entity.Order, error)
|
||||
FindByID(ctx context.Context, id int64) (*entity.Order, error)
|
||||
FindPrintDetailByID(ctx context.Context, id int64) (*entity.OrderPrintDetail, error)
|
||||
FindByQRCode(ctx context.Context, refID string) (*entity.Order, error)
|
||||
Update(ctx context.Context, order *entity.Order) (*entity.Order, error)
|
||||
SetOrderStatus(ctx context.Context, db *gorm.DB, orderID int64, status string) error
|
||||
GetAllHystoryOrders(ctx context.Context, req entity.OrderSearch) (entity.HistoryOrderList, int, error)
|
||||
SumAmount(ctx mycontext.Context, req entity.OrderSearch) (*entity.OrderDB, error)
|
||||
CountSoldOfTicket(ctx mycontext.Context, req entity.OrderSearch) (*entity.TicketSoldDB, error)
|
||||
GetDailySalesMetrics(ctx context.Context, req entity.OrderSearch) ([]entity.ProductDailySales, error)
|
||||
GetPaymentTypeDistribution(ctx context.Context, req entity.OrderSearch) ([]entity.PaymentTypeDistribution, error)
|
||||
}
|
||||
|
||||
type OSSRepository interface {
|
||||
UploadFile(ctx context.Context, fileName string, fileContent []byte) (fileUrl string, err error)
|
||||
GetPublicURL(fileName string) string
|
||||
}
|
||||
|
||||
type PartnerRepository interface {
|
||||
Create(ctx context.Context, branch *entity.PartnerDB) (*entity.PartnerDB, error)
|
||||
CreateWithTx(ctx context.Context, tx *gorm.DB, Partner *entity.PartnerDB) (*entity.PartnerDB, error)
|
||||
UpdateWithTx(ctx context.Context, tx *gorm.DB, Partner *entity.PartnerDB) (*entity.PartnerDB, error)
|
||||
Update(ctx context.Context, branch *entity.PartnerDB) (*entity.PartnerDB, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.PartnerDB, error)
|
||||
GetAll(ctx context.Context, req entity.PartnerSearch) (entity.PartnerList, int, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
type SiteRepository interface {
|
||||
Upsert(ctx context.Context, site *entity.Site) (*entity.Site, error)
|
||||
Create(ctx context.Context, branch *entity.SiteDB) (*entity.SiteDB, error)
|
||||
Update(ctx context.Context, branch *entity.SiteDB) (*entity.SiteDB, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.SiteDB, error)
|
||||
GetAll(ctx context.Context, req entity.SiteSearch) (entity.SiteList, int, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
Count(ctx mycontext.Context, req entity.SiteSearch) (*entity.SiteCountDB, error)
|
||||
GetNearestSites(ctx context.Context, latitude, longitude, radius float64) ([]entity.SiteProductInfo, error)
|
||||
SearchSites(ctx context.Context, search *entity.DiscoverySearch) ([]entity.SiteProductInfo, int64, error)
|
||||
}
|
||||
|
||||
type WalletRepository interface {
|
||||
Create(ctx context.Context, tx *gorm.DB, wallet *entity.Wallet) (*entity.Wallet, error)
|
||||
Update(ctx context.Context, db *gorm.DB, wallet *entity.Wallet) (*entity.Wallet, error)
|
||||
GetByPartnerID(ctx context.Context, db *gorm.DB, partnerID int64) (*entity.Wallet, error)
|
||||
GetForUpdate(ctx context.Context, tx *gorm.DB, partnerID int64) (*entity.Wallet, error)
|
||||
}
|
||||
|
||||
type Midtrans interface {
|
||||
CreatePayment(order entity.MidtransRequest) (*entity.MidtransResponse, error)
|
||||
CreateQrisPayment(order entity.MidtransRequest) (*entity.MidtransQrisResponse, error)
|
||||
}
|
||||
|
||||
type Payment interface {
|
||||
Create(ctx context.Context, payment *entity.Payment) (*entity.Payment, error)
|
||||
Update(ctx context.Context, payment *entity.Payment) (*entity.Payment, error)
|
||||
UpdateWithTx(ctx context.Context, tx *gorm.DB, payment *entity.Payment) (*entity.Payment, error)
|
||||
FindByOrderAndPartnerID(ctx context.Context, orderID, partnerID int64) (*entity.Payment, error)
|
||||
FindByReferenceID(ctx context.Context, db *gorm.DB, referenceID string) (*entity.Payment, error)
|
||||
}
|
||||
|
||||
type EmailService interface {
|
||||
SendEmailTransactional(ctx context.Context, param entity.SendEmailNotificationParam) error
|
||||
}
|
||||
|
||||
type License interface {
|
||||
Create(ctx context.Context, license *entity.LicenseDB) (*entity.LicenseDB, error)
|
||||
Update(ctx context.Context, license *entity.LicenseDB) (*entity.LicenseDB, error)
|
||||
FindByID(ctx context.Context, id string) (*entity.LicenseDB, error)
|
||||
GetAll(ctx context.Context, limit, offset int, statusFilter string) ([]*entity.LicenseGetAll, int64, error)
|
||||
FindByPartnerIDMaxEndDate(ctx context.Context, partnerID *int64) (*entity.LicenseDB, error)
|
||||
}
|
||||
|
||||
type TransactionRepository interface {
|
||||
FindByID(ctx context.Context, id string) (*entity.Transaction, error)
|
||||
Create(ctx context.Context, trx *gorm.DB, transaction *entity.Transaction) (*entity.Transaction, error)
|
||||
GetTransactionList(ctx mycontext.Context, req entity.TransactionSearch) ([]*entity.TransactionList, int, error)
|
||||
Update(ctx context.Context, trx *gorm.DB, transaction *entity.Transaction) (*entity.Transaction, error)
|
||||
}
|
||||
|
||||
type LinkQu interface {
|
||||
CreateQrisPayment(linkQuRequest entity.LinkQuRequest) (*entity.LinkQuQRISResponse, error)
|
||||
CreatePaymentVA(linkQuRequest entity.LinkQuRequest) (*entity.LinkQuPaymentVAResponse, error)
|
||||
CheckPaymentStatus(partnerReff string) (*entity.LinkQuCheckStatusResponse, error)
|
||||
}
|
||||
|
||||
type PaymentGateway interface {
|
||||
CreatePayment(request entity.PaymentRequest) (*entity.PaymentResponse, error)
|
||||
CreateQRISPayment(request entity.PaymentRequest) (*entity.PaymentResponse, error)
|
||||
CreatePaymentVA(request entity.PaymentRequest) (*entity.PaymentResponse, error)
|
||||
}
|
||||
|
||||
type Trx interface {
|
||||
Begin(ctx context.Context, opts ...*sql.TxOptions) (*gorm.DB, error)
|
||||
Commit(session *gorm.DB) *gorm.DB
|
||||
Rollback(session *gorm.DB) *gorm.DB
|
||||
}
|
||||
@@ -1,282 +0,0 @@
|
||||
package sites
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SiteRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSiteRepository(db *gorm.DB) *SiteRepository {
|
||||
return &SiteRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *SiteRepository) Upsert(ctx context.Context, site *entity.Site) (*entity.Site, error) {
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if site.ID != 0 {
|
||||
// Update site
|
||||
if err := tx.Save(site).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Create new site
|
||||
if err := tx.Create(site).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(site.Products) > 0 {
|
||||
for i := range site.Products {
|
||||
if site.Products[i].ID != 0 {
|
||||
if err := tx.Save(&site.Products[i]).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := tx.Create(&site.Products[i]).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when upserting site", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return site, nil
|
||||
}
|
||||
|
||||
func (r *SiteRepository) Create(ctx context.Context, site *entity.SiteDB) (*entity.SiteDB, error) {
|
||||
err := r.db.Create(site).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when creating site", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return site, nil
|
||||
}
|
||||
|
||||
func (r *SiteRepository) Update(ctx context.Context, site *entity.SiteDB) (*entity.SiteDB, error) {
|
||||
if err := r.db.Save(site).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating site", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return site, nil
|
||||
}
|
||||
|
||||
func (r *SiteRepository) GetByID(ctx context.Context, id int64) (*entity.SiteDB, error) {
|
||||
site := new(entity.SiteDB)
|
||||
if err := r.db.Preload("Products").First(site, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting site by ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return site, nil
|
||||
}
|
||||
|
||||
func (r *SiteRepository) GetAll(ctx context.Context, req entity.SiteSearch) (entity.SiteList, int, error) {
|
||||
var sites []*entity.SiteDB
|
||||
var total int64
|
||||
|
||||
query := r.db
|
||||
query = query.Where("deleted_at IS NULL")
|
||||
|
||||
if req.Status != "" {
|
||||
query = query.Where("status = ?", req.Status)
|
||||
}
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.PartnerID != nil {
|
||||
query = query.Where("partner_id = ?", req.PartnerID)
|
||||
}
|
||||
|
||||
if req.SiteID != nil {
|
||||
query = query.Where("id = ?", req.SiteID)
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&sites).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting all sites", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if err := r.db.Model(&entity.SiteDB{}).Where(query).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when counting sites", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return sites, int(total), nil
|
||||
}
|
||||
|
||||
func (r *SiteRepository) Delete(ctx context.Context, id int64) error {
|
||||
site := new(entity.SiteDB)
|
||||
site.ID = id
|
||||
if err := r.db.Delete(site).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SiteRepository) Count(ctx mycontext.Context, req entity.SiteSearch) (*entity.SiteCountDB, error) {
|
||||
count := new(entity.SiteCountDB)
|
||||
|
||||
query := r.db.Table("sites").
|
||||
Select("count(*) as count")
|
||||
|
||||
if !req.IsAdmin {
|
||||
query = query.Where("partner_id = ?", req.PartnerID)
|
||||
}
|
||||
|
||||
if err := query.Scan(&count).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get count sites", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (r *SiteRepository) GetNearestSites(ctx context.Context, latitude, longitude, radius float64) ([]entity.SiteProductInfo, error) {
|
||||
const limit = 5
|
||||
var siteProducts []entity.SiteProductInfo
|
||||
|
||||
distanceQuery := `
|
||||
(6371 * acos(cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude))))
|
||||
`
|
||||
|
||||
// Primary query for sites within the radius
|
||||
err := r.db.WithContext(ctx).Raw(`
|
||||
SELECT s.id AS site_id, s.name AS site_name, s.region, s.regency, s.partner_id, s.image, s.address, s.location_link, s.description,
|
||||
s.highlight, s.contact_person, s.tnc, s.additional_info, s.status, s.is_season_ticket, s.is_discount_active,
|
||||
s.latitude, s.longitude, s.created_at, s.updated_at,
|
||||
`+distanceQuery+` AS distance,
|
||||
p.id AS product_id, p.name AS product_name, p.type AS product_type, p.price AS product_price,
|
||||
p.is_weekend_ticket, p.is_season_ticket, p.status AS product_status, p.description AS product_description
|
||||
FROM sites s
|
||||
LEFT JOIN (
|
||||
SELECT *, ROW_NUMBER() OVER (PARTITION BY site_id ORDER BY price ASC) AS rn
|
||||
FROM products
|
||||
) p ON s.id = p.site_id AND p.rn = 1
|
||||
WHERE `+distanceQuery+` < ? and s.deleted_at IS NULL and s.status = 'Active'
|
||||
ORDER BY distance
|
||||
LIMIT ?`,
|
||||
latitude, longitude, latitude, latitude, longitude, latitude, radius, limit).Scan(&siteProducts).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If fewer than 5 sites found, fetch additional ones regardless of distance
|
||||
if len(siteProducts) < limit {
|
||||
additionalLimit := limit - len(siteProducts)
|
||||
err = r.db.WithContext(ctx).Raw(`
|
||||
SELECT s.id AS site_id, s.name AS site_name, s.region, s.regency, s.partner_id, s.image, s.address, s.location_link, s.description,
|
||||
s.highlight, s.contact_person, s.tnc, s.additional_info, s.status, s.is_season_ticket, s.is_discount_active,
|
||||
s.latitude, s.longitude, s.created_at, s.updated_at,
|
||||
`+distanceQuery+` AS distance,
|
||||
p.id AS product_id, p.name AS product_name, p.type AS product_type, p.price AS product_price,
|
||||
p.is_weekend_ticket, p.is_season_ticket, p.status AS product_status, p.description AS product_description
|
||||
FROM sites s
|
||||
LEFT JOIN (
|
||||
SELECT *, ROW_NUMBER() OVER (PARTITION BY site_id ORDER BY price ASC) AS rn
|
||||
FROM products
|
||||
) p ON s.id = p.site_id AND p.rn = 1
|
||||
WHERE s.deleted_at IS NULL and s.status = 'Active'
|
||||
ORDER BY distance
|
||||
LIMIT ?`,
|
||||
latitude, longitude, latitude, additionalLimit).Scan(&siteProducts).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return siteProducts, nil
|
||||
}
|
||||
|
||||
func (r *SiteRepository) SearchSites(ctx context.Context, search *entity.DiscoverySearch) ([]entity.SiteProductInfo, int64, error) {
|
||||
var siteProducts []entity.SiteProductInfo
|
||||
var total int64
|
||||
|
||||
// Adding wildcard for partial matching
|
||||
searchName := "%" + search.Name + "%"
|
||||
|
||||
// Base conditions and parameters
|
||||
conditions := "s.name ILIKE ?"
|
||||
params := []interface{}{searchName}
|
||||
|
||||
// Add region filtering if region is provided
|
||||
if search.Region != "" {
|
||||
conditions += " AND s.region = ?"
|
||||
params = append(params, search.Region)
|
||||
}
|
||||
|
||||
if search.Status != "" {
|
||||
conditions += " AND s.status = ?"
|
||||
params = append(params, search.Status)
|
||||
}
|
||||
|
||||
if search.Discover != "" {
|
||||
conditions += " AND s.region ILIKE ?"
|
||||
params = append(params, "%"+search.Discover+"%")
|
||||
}
|
||||
|
||||
// Count query to get the total number of matching records
|
||||
countQuery := `
|
||||
SELECT COUNT(*)
|
||||
FROM sites s
|
||||
WHERE ` + conditions
|
||||
err := r.db.WithContext(ctx).Raw(countQuery, params...).Scan(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Add limit and offset for the data query
|
||||
dataParams := append(params, search.Limit, search.Offset)
|
||||
|
||||
// Primary query for sites matching name and region, with pagination
|
||||
dataQuery := `
|
||||
SELECT s.id AS site_id, s.name AS site_name, s.region, s.regency, s.partner_id, s.image, s.address, s.location_link, s.description,
|
||||
s.highlight, s.contact_person, s.tnc, s.additional_info, s.status, s.is_season_ticket, s.is_discount_active,
|
||||
s.latitude, s.longitude, s.created_at, s.updated_at,
|
||||
p.id AS product_id, p.name AS product_name, p.type AS product_type, p.price AS product_price,
|
||||
p.is_weekend_ticket, p.is_season_ticket, p.status AS product_status, p.description AS product_description
|
||||
FROM sites s
|
||||
LEFT JOIN (
|
||||
SELECT *, ROW_NUMBER() OVER (PARTITION BY site_id ORDER BY price ASC) AS rn
|
||||
FROM products
|
||||
) p ON s.id = p.site_id AND p.rn = 1
|
||||
WHERE ` + conditions + ` and s.deleted_at IS NULL and s.status = 'Active'
|
||||
ORDER BY s.name
|
||||
LIMIT ? OFFSET ?
|
||||
`
|
||||
err = r.db.WithContext(ctx).Raw(dataQuery, dataParams...).Scan(&siteProducts).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return siteProducts, total, nil
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TransactionManager struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewTransactionManager(db *gorm.DB) *TransactionManager {
|
||||
return &TransactionManager{db: db}
|
||||
}
|
||||
|
||||
func (tm *TransactionManager) Begin(ctx context.Context, opts ...*sql.TxOptions) (*gorm.DB, error) {
|
||||
tx := tm.db.Begin(opts...)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func (tm *TransactionManager) Commit(session *gorm.DB) *gorm.DB {
|
||||
return session.Commit()
|
||||
}
|
||||
|
||||
func (tm *TransactionManager) Rollback(session *gorm.DB) *gorm.DB {
|
||||
return session.Rollback()
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package transactions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TransactionRepository provides methods to perform CRUD operations on transactions.
|
||||
type TransactionRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewTransactionRepository(db *gorm.DB) *TransactionRepository {
|
||||
return &TransactionRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates a new transaction in the database.
|
||||
func (r *TransactionRepository) Create(ctx context.Context, trx *gorm.DB, transaction *entity.Transaction) (*entity.Transaction, error) {
|
||||
// Create the transaction record
|
||||
if err := trx.WithContext(ctx).Create(transaction).Error; err != nil {
|
||||
zap.L().Error("error when creating transaction", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Retrieve the created transaction using the same transaction context
|
||||
var createdTransaction entity.Transaction
|
||||
if err := trx.WithContext(ctx).First(&createdTransaction, "id = ?", transaction.ID).Error; err != nil {
|
||||
zap.L().Error("error when fetching newly created transaction", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return &createdTransaction, nil
|
||||
}
|
||||
|
||||
// Update updates an existing transaction in the database.
|
||||
func (r *TransactionRepository) Update(ctx context.Context, trx *gorm.DB, transaction *entity.Transaction) (*entity.Transaction, error) {
|
||||
if err := trx.WithContext(ctx).Save(transaction).Error; err != nil {
|
||||
zap.L().Error("error when updating transaction", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return transaction, nil
|
||||
}
|
||||
|
||||
func (r *TransactionRepository) FindByID(ctx context.Context, id string) (*entity.Transaction, error) {
|
||||
var transaction entity.Transaction
|
||||
if err := r.db.WithContext(ctx).First(&transaction, "id = ?", id).Error; err != nil {
|
||||
zap.L().Error("error when finding transaction by ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return &transaction, nil
|
||||
}
|
||||
|
||||
func (r *TransactionRepository) Delete(ctx context.Context, id string) error {
|
||||
if err := r.db.WithContext(ctx).Delete(&entity.Transaction{}, "id = ?", id).Error; err != nil {
|
||||
zap.L().Error("error when deleting transaction", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *TransactionRepository) FindByPartnerID(ctx context.Context, partnerID int64) ([]entity.Transaction, error) {
|
||||
var transactions []entity.Transaction
|
||||
if err := r.db.WithContext(ctx).Where("partner_id = ?", partnerID).Find(&transactions).Error; err != nil {
|
||||
zap.L().Error("error when finding transactions by partner ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
func (r *TransactionRepository) FindByStatus(ctx context.Context, status string) ([]entity.Transaction, error) {
|
||||
var transactions []entity.Transaction
|
||||
if err := r.db.WithContext(ctx).Where("status = ?", status).Find(&transactions).Error; err != nil {
|
||||
zap.L().Error("error when finding transactions by status", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
// UpdateStatus updates the status of a transaction by its ID.
|
||||
func (r *TransactionRepository) UpdateStatus(ctx context.Context, id string, status string) (*entity.Transaction, error) {
|
||||
transaction, err := r.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transaction.Status = status
|
||||
if err := r.db.WithContext(ctx).Save(transaction).Error; err != nil {
|
||||
zap.L().Error("error when updating transaction status", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return transaction, nil
|
||||
}
|
||||
|
||||
// ListTransactions retrieves a list of transactions with optional filters for pagination and sorting.
|
||||
func (r *TransactionRepository) ListTransactions(ctx context.Context, offset int, limit int, status string, transactionType string) ([]entity.Transaction, int64, error) {
|
||||
var transactions []entity.Transaction
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entity.Transaction{}).Order("created_at DESC")
|
||||
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
if transactionType != "" {
|
||||
query = query.Where("transaction_type = ?", transactionType)
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
zap.L().Error("error when counting transactions", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if offset >= 0 {
|
||||
query = query.Offset(offset)
|
||||
}
|
||||
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
|
||||
if err := query.Find(&transactions).Error; err != nil {
|
||||
zap.L().Error("error when listing transactions", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return transactions, total, nil
|
||||
}
|
||||
|
||||
func (r *TransactionRepository) GetTransactionList(ctx mycontext.Context, req entity.TransactionSearch) ([]*entity.TransactionList, int, error) {
|
||||
var transactions []*entity.TransactionList
|
||||
var total int64
|
||||
|
||||
query := r.db.Table("transactions t").
|
||||
Select("t.id, t.transaction_type, t.status, t.created_at, s.name as site_name, p.name as partner_name, t.amount, t.fee, t.total").
|
||||
Joins("left join sites s on t.site_id = s.id").
|
||||
Joins("left join partners p on t.partner_id = p.id")
|
||||
|
||||
if req.SiteID != nil {
|
||||
query = query.Where("t.site_id = ?", req.SiteID)
|
||||
}
|
||||
|
||||
if req.Type != "" {
|
||||
query = query.Where("t.transaction_type = ?", req.Type)
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
query = query.Where("t.status = ?", req.Status)
|
||||
}
|
||||
|
||||
if req.Date != "" {
|
||||
query = query.Where("DATE(t.created_at) = ?", req.Date)
|
||||
}
|
||||
|
||||
if req.PartnerID != nil {
|
||||
query = query.Where("t.partner_id = ?", req.PartnerID)
|
||||
}
|
||||
|
||||
query = query.Order("t.created_at DESC")
|
||||
|
||||
query = query.Count(&total)
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
err := query.Find(&transactions).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return transactions, int(total), nil
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package trx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type GormTransactionManager struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewGormTransactionManager(db *gorm.DB) *GormTransactionManager {
|
||||
return &GormTransactionManager{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (tm *GormTransactionManager) Begin(ctx context.Context, opts ...*sql.TxOptions) (*gorm.DB, error) {
|
||||
tx := tm.db.Begin(opts...)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func (tm *GormTransactionManager) Commit(tx *gorm.DB) *gorm.DB {
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (tm *GormTransactionManager) Rollback(tx *gorm.DB) *gorm.DB {
|
||||
return tx.Rollback()
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/common/mycontext"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UndianRepo interface {
|
||||
GetUndianEventByID(ctx mycontext.Context, id int64) (*entity.UndianEventDB, error)
|
||||
GetActiveUndianEvents(ctx mycontext.Context) ([]*entity.UndianEventDB, error)
|
||||
GetActiveUndianEventsWithPrizes(ctx mycontext.Context, customerID int64) ([]*entity.UndianEventDB, error)
|
||||
GetCustomerVouchersByEventIDs(ctx mycontext.Context, customerID int64, eventIDs []int64) ([]*entity.UndianVoucherDB, error)
|
||||
CreateUndianVouchers(ctx mycontext.Context, vouchers []*entity.UndianVoucherDB) error
|
||||
GetNextVoucherSequence(ctx mycontext.Context) (int64, error)
|
||||
GetNextVoucherSequenceBatch(ctx mycontext.Context, count int) (int64, error)
|
||||
}
|
||||
|
||||
type undianRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewUndianRepository(db *gorm.DB) UndianRepo {
|
||||
return &undianRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *undianRepository) GetUndianEventByID(ctx mycontext.Context, id int64) (*entity.UndianEventDB, error) {
|
||||
event := new(entity.UndianEventDB)
|
||||
if err := r.db.WithContext(ctx).First(event, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get undian event by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return event, nil
|
||||
}
|
||||
|
||||
func (r *undianRepository) GetActiveUndianEvents(ctx mycontext.Context) ([]*entity.UndianEventDB, error) {
|
||||
var events []*entity.UndianEventDB
|
||||
now := time.Now()
|
||||
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("status = 'active' AND start_date <= ? AND end_date >= ?", now, now).
|
||||
Order("created_at DESC").
|
||||
Find(&events).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get active undian events", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func (r *undianRepository) GetActiveUndianEventsWithPrizes(ctx mycontext.Context, customerID int64) ([]*entity.UndianEventDB, error) {
|
||||
var events []*entity.UndianEventDB
|
||||
now := time.Now()
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Preload("Prizes", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("rank ASC")
|
||||
}).
|
||||
Where("status = 'active' AND start_date <= ? AND end_date >= ?", now, now).
|
||||
Order("created_at DESC")
|
||||
|
||||
// If customer ID is provided, preload only that customer's vouchers
|
||||
if customerID > 0 {
|
||||
query = query.Preload("Vouchers", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Where("customer_id = ?", customerID).Order("created_at ASC")
|
||||
})
|
||||
} else {
|
||||
// If no customer ID, don't load any vouchers (or load all if needed)
|
||||
query = query.Preload("Vouchers", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Where("1 = 0") // This loads no vouchers
|
||||
})
|
||||
}
|
||||
|
||||
if err := query.Find(&events).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get active undian events with prizes",
|
||||
zap.Int64("customerID", customerID),
|
||||
zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func (r *undianRepository) GetCustomerVouchersByEventIDs(ctx mycontext.Context, customerID int64, eventIDs []int64) ([]*entity.UndianVoucherDB, error) {
|
||||
var vouchers []*entity.UndianVoucherDB
|
||||
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("customer_id = ? AND undian_event_id IN ?", customerID, eventIDs).
|
||||
Order("undian_event_id ASC, created_at ASC").
|
||||
Find(&vouchers).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get customer vouchers by event IDs",
|
||||
zap.Int64("customerID", customerID),
|
||||
zap.Int64s("eventIDs", eventIDs),
|
||||
zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return vouchers, nil
|
||||
}
|
||||
|
||||
func (r *undianRepository) CreateUndianVouchers(ctx mycontext.Context, vouchers []*entity.UndianVoucherDB) error {
|
||||
err := r.db.WithContext(ctx).Create(&vouchers).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create undian vouchers", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *undianRepository) GetNextVoucherSequence(ctx mycontext.Context) (int64, error) {
|
||||
var sequence int64
|
||||
|
||||
err := r.db.WithContext(ctx).Raw("SELECT nextval('voucher_sequence')").Scan(&sequence).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get next voucher sequence", zap.Error(err))
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return sequence, nil
|
||||
}
|
||||
|
||||
func (r *undianRepository) GetNextVoucherSequenceBatch(ctx mycontext.Context, count int) (int64, error) {
|
||||
var startSequence int64
|
||||
|
||||
query := fmt.Sprintf("SELECT nextval('voucher_sequence') + %d - %d", count-1, count-1)
|
||||
err := r.db.WithContext(ctx).Raw(query).Scan(&startSequence).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get batch voucher sequence", zap.Error(err))
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return startSequence, nil
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserRepositoryImpl struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewUserRepository(db *gorm.DB) *UserRepositoryImpl {
|
||||
return &UserRepositoryImpl{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) Create(ctx context.Context, user *entities.User) error {
|
||||
return r.db.WithContext(ctx).Create(user).Error
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.User, error) {
|
||||
var user entities.User
|
||||
err := r.db.WithContext(ctx).First(&user, "id = ?", id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) GetByEmail(ctx context.Context, email string) (*entities.User, error) {
|
||||
var user entities.User
|
||||
err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) GetByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.User, error) {
|
||||
var users []*entities.User
|
||||
err := r.db.WithContext(ctx).Where("organization_id = ?", organizationID).Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) GetByRole(ctx context.Context, role entities.UserRole) ([]*entities.User, error) {
|
||||
var users []*entities.User
|
||||
err := r.db.WithContext(ctx).Where("role = ?", role).Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) GetActiveUsers(ctx context.Context, organizationID uuid.UUID) ([]*entities.User, error) {
|
||||
var users []*entities.User
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND is_active = ?", organizationID, true).
|
||||
Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) Update(ctx context.Context, user *entities.User) error {
|
||||
return r.db.WithContext(ctx).Save(user).Error
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&entities.User{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) UpdatePassword(ctx context.Context, id uuid.UUID, passwordHash string) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.User{}).
|
||||
Where("id = ?", id).
|
||||
Update("password_hash", passwordHash).Error
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) UpdateActiveStatus(ctx context.Context, id uuid.UUID, isActive bool) error {
|
||||
return r.db.WithContext(ctx).Model(&entities.User{}).
|
||||
Where("id = ?", id).
|
||||
Update("is_active", isActive).Error
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.User, int64, error) {
|
||||
var users []*entities.User
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.User{})
|
||||
|
||||
for key, value := range filters {
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := query.Limit(limit).Offset(offset).Find(&users).Error
|
||||
return users, total, err
|
||||
}
|
||||
|
||||
func (r *UserRepositoryImpl) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&entities.User{})
|
||||
|
||||
for key, value := range filters {
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewUserRepository(db *gorm.DB) *UserRepository {
|
||||
return &UserRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, user *entity.UserDB) (*entity.UserDB, error) {
|
||||
tx := r.db.Begin()
|
||||
|
||||
user.ID = 0
|
||||
if err := tx.Select("name", "email", "password", "status", "created_by", "nik", "user_type", "phone_number").Create(user).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "creating user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.First(user, user.ID).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "retrieving user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if user.UserType != "CUSTOMER" {
|
||||
userRole := user.ToUserRoleDB()
|
||||
if err := tx.Create(userRole).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "creating user role", err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "committing transaction", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) CreateWithTx(ctx context.Context, tx *gorm.DB, user *entity.UserDB) (*entity.UserDB, error) {
|
||||
user.ID = 0
|
||||
if err := tx.Select("name", "email", "password", "status", "created_by", "nik", "user_type", "phone_number").Create(user).Error; err != nil {
|
||||
logError(ctx, "creating user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.First(user, user.ID).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "retrieving user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userRole := user.ToUserRoleDB()
|
||||
if err := tx.Create(userRole).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "creating user role", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (b *UserRepository) GetAllUsers(ctx context.Context, req entity.UserSearch) (entity.UserList, int, error) {
|
||||
var users []*entity.UserDB
|
||||
var total int64
|
||||
|
||||
query := b.db.Table("users").
|
||||
Select("users.id, users.email, users.name, users.status, users.created_at, users.updated_at, ur.role_id, r.role_name, ur.partner_id, b.name as partner_name").
|
||||
Joins("LEFT JOIN user_roles ur ON users.id = ur.user_id").
|
||||
Joins("LEFT JOIN roles r ON ur.role_id = r.role_id").
|
||||
Joins("LEFT JOIN partners b ON ur.partner_id = b.id").
|
||||
Where("users.deleted_at is null").
|
||||
Where("users.user_type != ?", "CUSTOMER")
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("users.name ILIKE ? or users.email ILIKE ? or r.role_name ILIKE ? or b.name ILIKE ? ", "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("users.name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.RoleID > 0 {
|
||||
query = query.Where("ur.role_id = ? ", req.RoleID)
|
||||
}
|
||||
|
||||
if req.PartnerID > 0 {
|
||||
query = query.Where("ur.partner_id = ? ", req.PartnerID)
|
||||
}
|
||||
|
||||
if req.SiteID > 0 {
|
||||
query = query.Where("ur.site_id = ? ", req.SiteID)
|
||||
}
|
||||
|
||||
// Get the total count without applying the limit and offset.
|
||||
if err := query.Model(&entity.UserDB{}).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count users", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Apply pagination.
|
||||
query = query.Offset(req.Offset).Limit(req.Limit)
|
||||
|
||||
if err := query.Scan(&users).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all users", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return users, int(total), nil
|
||||
}
|
||||
|
||||
func (b *UserRepository) GetAllCustomer(ctx context.Context, req entity.CustomerSearch) (entity.CustomerList, int, error) {
|
||||
var users []*entity.UserDB
|
||||
var total int64
|
||||
|
||||
query := b.db.Table("customers").
|
||||
Select("customers.id, customers.email, customers.name, customers.phone as phone_number")
|
||||
|
||||
if err := query.Model(&entity.UserDB{}).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count users", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Apply pagination.
|
||||
query = query.Offset(req.Offset).Limit(req.Limit)
|
||||
|
||||
if err := query.Scan(&users).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all users", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return users, int(total), nil
|
||||
}
|
||||
|
||||
func (b *UserRepository) GetUserByID(ctx context.Context, id int64) (*entity.UserDB, error) {
|
||||
var user *entity.UserDB
|
||||
|
||||
query := b.db.Table("users").
|
||||
Select("users.id, users.email,users.phone_number,users.nik, users.password , users.name, users.status, users.created_at, users.updated_at, ur.role_id, r.role_name, ur.partner_id, ur.site_id, b.name as partner_name").
|
||||
Joins("LEFT JOIN user_roles ur ON users.id = ur.user_id").
|
||||
Joins("LEFT JOIN roles r ON ur.role_id = r.role_id").
|
||||
Joins("LEFT JOIN partners b ON ur.partner_id = b.id").
|
||||
Where("users.id = ?", id)
|
||||
|
||||
if err := query.Scan(&user).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get user", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (b *UserRepository) GetPartnerAdmin(ctx context.Context, partnerID int64) (*entity.UserDB, error) {
|
||||
var user *entity.UserDB
|
||||
|
||||
partnerAdmin := 3
|
||||
|
||||
query := b.db.Table("users").
|
||||
Select("users.id, users.email,users.phone_number,users.nik, users.password , users.name, users.status, users.created_at, users.updated_at, ur.role_id, r.role_name, ur.partner_id, b.name as partner_name").
|
||||
Joins("LEFT JOIN user_roles ur ON users.id = ur.user_id").
|
||||
Joins("LEFT JOIN roles r ON ur.role_id = r.role_id").
|
||||
Joins("LEFT JOIN partners b ON ur.partner_id = b.id").
|
||||
Where("ur.partner_id = ?", partnerID).
|
||||
Where("ur.role_id = ?", partnerAdmin)
|
||||
|
||||
if err := query.Scan(&user).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get user", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (b *UserRepository) GetUserByEmail(ctx context.Context, email string) (*entity.UserDB, error) {
|
||||
var user *entity.UserDB
|
||||
|
||||
query := b.db.Table("users").
|
||||
Select("users.id, users.email, users.name, users.status, users.created_at, users.updated_at, ur.role_id, r.role_name, ur.partner_id, b.name as partner_name").
|
||||
Joins("LEFT JOIN user_roles ur ON users.id = ur.user_id").
|
||||
Joins("LEFT JOIN roles r ON ur.role_id = r.role_id").
|
||||
Joins("LEFT JOIN partners b ON ur.partner_id = b.id").
|
||||
Where("users.email = ?", email)
|
||||
|
||||
if err := query.Scan(&user).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get user", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) UpdateUser(ctx context.Context, user *entity.UserDB) (*entity.UserDB, error) {
|
||||
tx := r.db.Begin()
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
if err := tx.Select("name", "email", "password", "status", "deleted_at", "updated_by", "nik", "phone_number").Save(user).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "update user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userRole := user.ToUserRoleDB()
|
||||
if err := tx.Model(userRole).Where("user_id = ?", user.ID).Updates(userRole).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "update user role", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "committing transaction", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) UpdateUserWithTx(ctx context.Context, tx *gorm.DB, user *entity.UserDB) (*entity.UserDB, error) {
|
||||
if err := tx.Select("name", "email", "nik", "phone_number", "password", "status", "deleted_at", "updated_by").Save(user).Error; err != nil {
|
||||
logError(ctx, "update user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userRole := user.ToUserRoleDB()
|
||||
if err := tx.Model(userRole).Where("user_id = ?", user.ID).Updates(userRole).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "update user role", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func logError(ctx context.Context, action string, err error) {
|
||||
logger.ContextLogger(ctx).Error("error when "+action, zap.Error(err))
|
||||
}
|
||||
|
||||
func (r *UserRepository) CountUsersByRoleAndSiteOrPartner(ctx context.Context, roleID int, siteID *int64) (int, error) {
|
||||
var count int64
|
||||
|
||||
query := r.db.Table("users").
|
||||
Joins("LEFT JOIN user_roles ur ON users.id = ur.user_id").
|
||||
Where("ur.role_id = ?", roleID)
|
||||
|
||||
if siteID != nil {
|
||||
query = query.Where("ur.site_id = ?", siteID)
|
||||
}
|
||||
|
||||
if err := query.Count(&count).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when counting users by role and site/partner", zap.Error(err))
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return int(count), nil
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"enaklo-pos-be/internal/common/logger"
|
||||
"enaklo-pos-be/internal/entity"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type WalletRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewWalletRepository(db *gorm.DB) *WalletRepository {
|
||||
return &WalletRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *WalletRepository) Create(ctx context.Context, tx *gorm.DB, wallet *entity.Wallet) (*entity.Wallet, error) {
|
||||
err := tx.Create(wallet).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when creating wallet", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return wallet, nil
|
||||
}
|
||||
|
||||
func (r *WalletRepository) Update(ctx context.Context, db *gorm.DB, wallet *entity.Wallet) (*entity.Wallet, error) {
|
||||
if err := db.Save(wallet).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating wallet", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return wallet, nil
|
||||
}
|
||||
|
||||
func (r *WalletRepository) GetByPartnerID(ctx context.Context, db *gorm.DB, partnerID int64) (*entity.Wallet, error) {
|
||||
if db == nil {
|
||||
db = r.db
|
||||
}
|
||||
|
||||
wallet := new(entity.Wallet)
|
||||
if err := db.WithContext(ctx).Where("partner_id = ?", partnerID).First(wallet).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding wallet by partner ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return wallet, nil
|
||||
}
|
||||
|
||||
func (r *WalletRepository) GetByID(ctx context.Context, id int64) (*entity.Wallet, error) {
|
||||
wallet := new(entity.Wallet)
|
||||
if err := r.db.First(wallet, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting wallet by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return wallet, nil
|
||||
}
|
||||
|
||||
func (r *WalletRepository) GetForUpdate(ctx context.Context, tx *gorm.DB, partnerID int64) (*entity.Wallet, error) {
|
||||
if tx == nil {
|
||||
tx = r.db
|
||||
}
|
||||
|
||||
query := tx.WithContext(ctx).Where("partner_id = ?", partnerID).
|
||||
Clauses(clause.Locking{Strength: "UPDATE"})
|
||||
|
||||
wallet := new(entity.Wallet)
|
||||
if err := query.First(wallet).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when finding balance by partner ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return wallet, nil
|
||||
}
|
||||
|
||||
func (r *WalletRepository) GetAll(ctx context.Context) ([]*entity.Wallet, error) {
|
||||
var wallets []*entity.Wallet
|
||||
if err := r.db.Find(&wallets).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting all wallets", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return wallets, nil
|
||||
}
|
||||
|
||||
func (r *WalletRepository) Delete(ctx context.Context, id int64) error {
|
||||
wallet := new(entity.Wallet)
|
||||
wallet.ID = id
|
||||
if err := r.db.Delete(wallet).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when deleting wallet", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user