diff --git a/internal/app/app.go b/internal/app/app.go index 0e04b7e..9ea2e47 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -165,6 +165,7 @@ func (a *App) Initialize(cfg *config.Config) error { services.customerOrderPaymentService, services.customerWalletService, services.customerDeviceService, + services.customerOutletService, a.redisClient, ) @@ -403,6 +404,7 @@ type processors struct { walletTransferProcessor *processor.WalletTransferProcessor walletTraceProcessor *processor.WalletTraceProcessor customerDeviceProcessor *processor.CustomerDeviceProcessor + customerOutletProcessor *processor.CustomerOutletProcessor } func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processors { @@ -484,6 +486,7 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor walletTransferProcessor: walletTransferProcessor, walletTraceProcessor: processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(a.db)), customerDeviceProcessor: customerDeviceProcessor, + customerOutletProcessor: processor.NewCustomerOutletProcessor(repository.NewCustomerOutletRepository(a.db), loyaltySettingsProcessor), walletAdminProcessor: processor.NewWalletAdminProcessor(repository.NewWalletAdminRepository(a.db), repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), loyaltySettingsProcessor, repos.txManager), } } @@ -534,6 +537,7 @@ type services struct { customerOrderPaymentService *service.CustomerOrderPaymentServiceImpl customerWalletService *service.CustomerWalletServiceImpl customerDeviceService *service.CustomerDeviceServiceImpl + customerOutletService *service.CustomerOutletServiceImpl } func (a *App) initServices(processors *processors, repos *repositories, cfg *config.Config) *services { @@ -622,6 +626,7 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con customerOrderPaymentService: service.NewCustomerOrderPaymentService(processors.orderProcessor), customerWalletService: service.NewCustomerWalletService(processors.walletExchangeProcessor, processors.walletTransferProcessor), customerDeviceService: service.NewCustomerDeviceService(processors.customerDeviceProcessor), + customerOutletService: service.NewCustomerOutletService(processors.customerOutletProcessor), } } diff --git a/internal/handler/customer_outlet_handler.go b/internal/handler/customer_outlet_handler.go new file mode 100644 index 0000000..9bd9245 --- /dev/null +++ b/internal/handler/customer_outlet_handler.go @@ -0,0 +1,26 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" +) + +// CustomerOutletHandler serves GET /customer/outlets. +type CustomerOutletHandler struct { + outlets service.CustomerOutletService +} + +func NewCustomerOutletHandler(outlets service.CustomerOutletService) *CustomerOutletHandler { + return &CustomerOutletHandler{outlets: outlets} +} + +// List returns the active outlets of the customer's organization. +func (h *CustomerOutletHandler) List(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerOutletHandler::List") + if !ok { + return + } + util.HandleResponse(c.Writer, c.Request, h.outlets.List(c.Request.Context(), customerID), "CustomerOutletHandler::List") +} diff --git a/internal/models/customer_outlet.go b/internal/models/customer_outlet.go new file mode 100644 index 0000000..191266d --- /dev/null +++ b/internal/models/customer_outlet.go @@ -0,0 +1,16 @@ +package models + +import "github.com/google/uuid" + +// CustomerOutlet is one outlet in GET /customer/outlets: where the customer can shop, +// and what the outlet does with EnakPoint and EnakCoin. +type CustomerOutlet struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Address *string `json:"address"` + // The cashier accepts EnakPoint as payment here. + AcceptsPointPayment bool `json:"accepts_point_payment"` + // Orders here earn EnakPoint / EnakCoin. + EarnsPoints bool `json:"earns_points"` + EarnsCoins bool `json:"earns_coins"` +} diff --git a/internal/processor/customer_outlet_processor.go b/internal/processor/customer_outlet_processor.go new file mode 100644 index 0000000..79c65a1 --- /dev/null +++ b/internal/processor/customer_outlet_processor.go @@ -0,0 +1,49 @@ +package processor + +import ( + "context" + + "github.com/google/uuid" + + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// CustomerOutletProcessor lists the outlets the customer app shows: the active +// outlets of the customer's organization, where their wallet can be used (K4). +type CustomerOutletProcessor struct { + repo repository.CustomerOutletRepository + settings outletSettingsReader +} + +func NewCustomerOutletProcessor(repo repository.CustomerOutletRepository, settings outletSettingsReader) *CustomerOutletProcessor { + return &CustomerOutletProcessor{repo: repo, settings: settings} +} + +// List is GET /customer/outlets. +func (p *CustomerOutletProcessor) List(ctx context.Context, customerID uuid.UUID) ([]models.CustomerOutlet, error) { + organizationID, err := p.repo.CustomerOrganizationID(ctx, customerID) + if err != nil { + return nil, err + } + outlets, err := p.repo.ListActiveOutlets(ctx, organizationID) + if err != nil { + return nil, err + } + list := make([]models.CustomerOutlet, 0, len(outlets)) + for _, o := range outlets { + settings, err := p.settings.Outlet(ctx, o.ID) + if err != nil { + return nil, err + } + list = append(list, models.CustomerOutlet{ + ID: o.ID, + Name: o.Name, + Address: o.Address, + AcceptsPointPayment: settings.PointPayment.AcceptPayment, + EarnsPoints: settings.Point.Enabled, + EarnsCoins: settings.Coin.Enabled, + }) + } + return list, nil +} diff --git a/internal/processor/customer_outlet_processor_test.go b/internal/processor/customer_outlet_processor_test.go new file mode 100644 index 0000000..8f05519 --- /dev/null +++ b/internal/processor/customer_outlet_processor_test.go @@ -0,0 +1,77 @@ +package processor + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +type customerOutletRepoFake struct { + orgs map[uuid.UUID]uuid.UUID + outlets map[uuid.UUID][]repository.CustomerOutlet +} + +func (f customerOutletRepoFake) CustomerOrganizationID(_ context.Context, id uuid.UUID) (uuid.UUID, error) { + org, ok := f.orgs[id] + if !ok { + return uuid.Nil, repository.ErrWalletNotFound + } + return org, nil +} + +func (f customerOutletRepoFake) ListActiveOutlets(_ context.Context, org uuid.UUID) ([]repository.CustomerOutlet, error) { + return f.outlets[org], nil +} + +type outletSettingsFake map[uuid.UUID]models.OutletLoyaltySettings + +func (f outletSettingsFake) Outlet(_ context.Context, id uuid.UUID) (*models.OutletLoyaltySettings, error) { + s := f[id] + return &s, nil +} + +func TestCustomerOutlets_ListsTheCustomersOrganizationWithLoyaltyFlags(t *testing.T) { + customer, org, other := uuid.New(), uuid.New(), uuid.New() + kemang, blokm := uuid.New(), uuid.New() + addr := "Jl. Kemang Raya 10" + repo := customerOutletRepoFake{ + orgs: map[uuid.UUID]uuid.UUID{customer: org}, + outlets: map[uuid.UUID][]repository.CustomerOutlet{ + org: {{ID: blokm, Name: "Blok M"}, {ID: kemang, Name: "Kemang", Address: &addr}}, + other: {{ID: uuid.New(), Name: "Not mine"}}, + }, + } + settings := outletSettingsFake{ + kemang: { + Point: models.LoyaltyEarnSettings{Enabled: true}, + PointPayment: models.LoyaltyPointPaymentSettings{AcceptPayment: true}, + }, + } + + got, err := NewCustomerOutletProcessor(repo, settings).List(context.Background(), customer) + require.NoError(t, err) + assert.Equal(t, []models.CustomerOutlet{ + {ID: blokm, Name: "Blok M"}, + {ID: kemang, Name: "Kemang", Address: &addr, AcceptsPointPayment: true, EarnsPoints: true}, + }, got) +} + +func TestCustomerOutlets_UnknownCustomer(t *testing.T) { + _, err := NewCustomerOutletProcessor(customerOutletRepoFake{}, outletSettingsFake{}).List(context.Background(), uuid.New()) + assert.ErrorIs(t, err, repository.ErrWalletNotFound) +} + +func TestCustomerOutlets_NoOutletsIsAnEmptyList(t *testing.T) { + customer := uuid.New() + repo := customerOutletRepoFake{orgs: map[uuid.UUID]uuid.UUID{customer: uuid.New()}} + got, err := NewCustomerOutletProcessor(repo, outletSettingsFake{}).List(context.Background(), customer) + require.NoError(t, err) + assert.NotNil(t, got) + assert.Empty(t, got) +} diff --git a/internal/repository/customer_outlet_repository.go b/internal/repository/customer_outlet_repository.go new file mode 100644 index 0000000..9013548 --- /dev/null +++ b/internal/repository/customer_outlet_repository.go @@ -0,0 +1,60 @@ +package repository + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// CustomerOutlet is what the customer app may see of an outlet. +type CustomerOutlet struct { + ID uuid.UUID + Name string + Address *string +} + +// CustomerOutletRepository reads the outlets a customer can visit: the active outlets +// of their organization. +type CustomerOutletRepository interface { + // CustomerOrganizationID returns ErrWalletNotFound when the customer does not exist. + CustomerOrganizationID(ctx context.Context, customerID uuid.UUID) (uuid.UUID, error) + // ListActiveOutlets returns the organization's active outlets, by name. + ListActiveOutlets(ctx context.Context, organizationID uuid.UUID) ([]CustomerOutlet, error) +} + +type customerOutletRepository struct { + db *gorm.DB +} + +func NewCustomerOutletRepository(db *gorm.DB) CustomerOutletRepository { + return &customerOutletRepository{db: db} +} + +func (r *customerOutletRepository) CustomerOrganizationID(ctx context.Context, customerID uuid.UUID) (uuid.UUID, error) { + var row struct{ OrganizationID uuid.UUID } + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("customers").Select("organization_id").Where("id = ?", customerID).Take(&row).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return uuid.Nil, ErrWalletNotFound + } + return uuid.Nil, fmt.Errorf("failed to get customer organization: %w", err) + } + return row.OrganizationID, nil +} + +func (r *customerOutletRepository) ListActiveOutlets(ctx context.Context, organizationID uuid.UUID) ([]CustomerOutlet, error) { + var outlets []CustomerOutlet + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("outlets").Select("id, name, address"). + Where("organization_id = ? AND is_active = ?", organizationID, true). + Order("name, id"). + Scan(&outlets).Error + if err != nil { + return nil, fmt.Errorf("failed to list outlets: %w", err) + } + return outlets, nil +} diff --git a/internal/router/router.go b/internal/router/router.go index f72a8c5..cf77c39 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -61,12 +61,13 @@ type Router struct { customerOrderPaymentHandler *handler.CustomerOrderPaymentHandler customerWalletHandler *handler.CustomerWalletHandler customerDeviceHandler *handler.CustomerDeviceHandler + customerOutletHandler *handler.CustomerOutletHandler authMiddleware *middleware.AuthMiddleware customerAuthMiddleware *middleware.CustomerAuthMiddleware redisClient *redis.Client } -func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authService service.AuthService, authMiddleware *middleware.AuthMiddleware, userService *service.UserServiceImpl, userValidator *validator.UserValidatorImpl, organizationService service.OrganizationService, organizationValidator validator.OrganizationValidator, outletService service.OutletService, outletValidator validator.OutletValidator, outletSettingService service.OutletSettingService, categoryService service.CategoryService, categoryValidator validator.CategoryValidator, productService service.ProductService, productValidator validator.ProductValidator, productVariantService service.ProductVariantService, productVariantValidator validator.ProductVariantValidator, inventoryService service.InventoryService, inventoryValidator validator.InventoryValidator, orderService service.OrderService, orderValidator validator.OrderValidator, fileService service.FileService, fileValidator validator.FileValidator, customerService service.CustomerService, customerValidator validator.CustomerValidator, paymentMethodService service.PaymentMethodService, paymentMethodValidator validator.PaymentMethodValidator, analyticsService *service.AnalyticsServiceImpl, reportService service.ReportService, tableService *service.TableServiceImpl, tableValidator *validator.TableValidator, unitService handler.UnitService, ingredientService handler.IngredientService, productRecipeService service.ProductRecipeService, vendorService service.VendorService, vendorValidator validator.VendorValidator, purchaseOrderService service.PurchaseOrderService, purchaseOrderValidator validator.PurchaseOrderValidator, purchaseCategoryService service.PurchaseCategoryService, purchaseCategoryValidator validator.PurchaseCategoryValidator, unitConverterService service.IngredientUnitConverterService, unitConverterValidator validator.IngredientUnitConverterValidator, chartOfAccountTypeService service.ChartOfAccountTypeService, chartOfAccountTypeValidator validator.ChartOfAccountTypeValidator, chartOfAccountService service.ChartOfAccountService, chartOfAccountValidator validator.ChartOfAccountValidator, accountService service.AccountService, accountValidator validator.AccountValidator, orderIngredientTransactionService service.OrderIngredientTransactionService, orderIngredientTransactionValidator validator.OrderIngredientTransactionValidator, gamificationService service.GamificationService, gamificationValidator validator.GamificationValidator, rewardService service.RewardService, rewardValidator validator.RewardValidator, campaignService service.CampaignService, campaignValidator validator.CampaignValidator, customerAuthService service.CustomerAuthService, customerAuthValidator validator.CustomerAuthValidator, customerPointsService service.CustomerPointsService, spinGameService service.SpinGameService, customerAuthMiddleware *middleware.CustomerAuthMiddleware, userDeviceService service.UserDeviceService, userDeviceValidator validator.UserDeviceValidator, notificationService service.NotificationService, notificationValidator validator.NotificationValidator, productOutletPriceService service.ProductOutletPriceService, productOutletPriceValidator validator.ProductOutletPriceValidator, selfOrderHandler *handler.SelfOrderHandler, expenseService *service.ExpenseServiceImpl, expenseValidator *validator.ExpenseValidatorImpl, cashAdvanceService service.CashAdvanceService, cashAdvanceValidator validator.CashAdvanceValidator, walletAdminService service.WalletAdminService, walletValidator validator.WalletValidator, loyaltySettingsService service.LoyaltySettingsService, customerPinService service.CustomerPinService, pointPaymentService service.PointPaymentService, customerOrderPaymentService service.CustomerOrderPaymentService, customerWalletService service.CustomerWalletService, customerDeviceService service.CustomerDeviceService, redisClient *redis.Client) *Router { +func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authService service.AuthService, authMiddleware *middleware.AuthMiddleware, userService *service.UserServiceImpl, userValidator *validator.UserValidatorImpl, organizationService service.OrganizationService, organizationValidator validator.OrganizationValidator, outletService service.OutletService, outletValidator validator.OutletValidator, outletSettingService service.OutletSettingService, categoryService service.CategoryService, categoryValidator validator.CategoryValidator, productService service.ProductService, productValidator validator.ProductValidator, productVariantService service.ProductVariantService, productVariantValidator validator.ProductVariantValidator, inventoryService service.InventoryService, inventoryValidator validator.InventoryValidator, orderService service.OrderService, orderValidator validator.OrderValidator, fileService service.FileService, fileValidator validator.FileValidator, customerService service.CustomerService, customerValidator validator.CustomerValidator, paymentMethodService service.PaymentMethodService, paymentMethodValidator validator.PaymentMethodValidator, analyticsService *service.AnalyticsServiceImpl, reportService service.ReportService, tableService *service.TableServiceImpl, tableValidator *validator.TableValidator, unitService handler.UnitService, ingredientService handler.IngredientService, productRecipeService service.ProductRecipeService, vendorService service.VendorService, vendorValidator validator.VendorValidator, purchaseOrderService service.PurchaseOrderService, purchaseOrderValidator validator.PurchaseOrderValidator, purchaseCategoryService service.PurchaseCategoryService, purchaseCategoryValidator validator.PurchaseCategoryValidator, unitConverterService service.IngredientUnitConverterService, unitConverterValidator validator.IngredientUnitConverterValidator, chartOfAccountTypeService service.ChartOfAccountTypeService, chartOfAccountTypeValidator validator.ChartOfAccountTypeValidator, chartOfAccountService service.ChartOfAccountService, chartOfAccountValidator validator.ChartOfAccountValidator, accountService service.AccountService, accountValidator validator.AccountValidator, orderIngredientTransactionService service.OrderIngredientTransactionService, orderIngredientTransactionValidator validator.OrderIngredientTransactionValidator, gamificationService service.GamificationService, gamificationValidator validator.GamificationValidator, rewardService service.RewardService, rewardValidator validator.RewardValidator, campaignService service.CampaignService, campaignValidator validator.CampaignValidator, customerAuthService service.CustomerAuthService, customerAuthValidator validator.CustomerAuthValidator, customerPointsService service.CustomerPointsService, spinGameService service.SpinGameService, customerAuthMiddleware *middleware.CustomerAuthMiddleware, userDeviceService service.UserDeviceService, userDeviceValidator validator.UserDeviceValidator, notificationService service.NotificationService, notificationValidator validator.NotificationValidator, productOutletPriceService service.ProductOutletPriceService, productOutletPriceValidator validator.ProductOutletPriceValidator, selfOrderHandler *handler.SelfOrderHandler, expenseService *service.ExpenseServiceImpl, expenseValidator *validator.ExpenseValidatorImpl, cashAdvanceService service.CashAdvanceService, cashAdvanceValidator validator.CashAdvanceValidator, walletAdminService service.WalletAdminService, walletValidator validator.WalletValidator, loyaltySettingsService service.LoyaltySettingsService, customerPinService service.CustomerPinService, pointPaymentService service.PointPaymentService, customerOrderPaymentService service.CustomerOrderPaymentService, customerWalletService service.CustomerWalletService, customerDeviceService service.CustomerDeviceService, customerOutletService service.CustomerOutletService, redisClient *redis.Client) *Router { return &Router{ config: cfg, @@ -119,6 +120,7 @@ func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authSer customerOrderPaymentHandler: handler.NewCustomerOrderPaymentHandler(customerOrderPaymentService), customerWalletHandler: handler.NewCustomerWalletHandler(customerWalletService), customerDeviceHandler: handler.NewCustomerDeviceHandler(customerDeviceService), + customerOutletHandler: handler.NewCustomerOutletHandler(customerOutletService), redisClient: redisClient, } } @@ -179,6 +181,7 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { customer.POST("/wallet/transfer", r.customerWalletHandler.Transfer) customer.PUT("/devices", r.customerDeviceHandler.Register) customer.DELETE("/devices/:device_id", r.customerDeviceHandler.Unregister) + customer.GET("/outlets", r.customerOutletHandler.List) customer.POST("/orders/:id/pay-with-points", r.customerOrderPaymentHandler.PayWithPoints) // PIN that approves moving EnakPoint and EnakCoin (docs/prd-point-coin.md F11) customer.GET("/pin/status", r.customerPinHandler.Status) diff --git a/internal/router/router_test.go b/internal/router/router_test.go index 40db753..75cafc7 100644 --- a/internal/router/router_test.go +++ b/internal/router/router_test.go @@ -44,6 +44,7 @@ func TestAllRoutesRegister(t *testing.T) { "POST /api/v1/customer/wallet/transfer", "PUT /api/v1/customer/devices", "DELETE /api/v1/customer/devices/:device_id", + "GET /api/v1/customer/outlets", "GET /api/v1/orders/:id/point-payment/preview", "POST /api/v1/customer/orders/:id/pay-with-points", "GET /api/v1/customer/pin/status", diff --git a/internal/service/customer_outlet_service.go b/internal/service/customer_outlet_service.go new file mode 100644 index 0000000..3322588 --- /dev/null +++ b/internal/service/customer_outlet_service.go @@ -0,0 +1,40 @@ +package service + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +// CustomerOutletService serves the outlets list of the customer app. +type CustomerOutletService interface { + List(ctx context.Context, customerID uuid.UUID) *contract.Response +} + +type CustomerOutletServiceImpl struct { + outlets *processor.CustomerOutletProcessor +} + +func NewCustomerOutletService(outlets *processor.CustomerOutletProcessor) *CustomerOutletServiceImpl { + return &CustomerOutletServiceImpl{outlets: outlets} +} + +func (s *CustomerOutletServiceImpl) List(ctx context.Context, customerID uuid.UUID) *contract.Response { + outlets, err := s.outlets.List(ctx, customerID) + if err != nil { + code := constants.InternalServerErrorCode + if errors.Is(err, repository.ErrWalletNotFound) { + code = constants.NotFoundErrorCode + } + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.RequestEntity, err.Error()), + }) + } + return contract.BuildSuccessResponse(outlets) +}