From a3cb7dd5fd27649eba533202751437ab29ff49a8 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 18:12:26 +0700 Subject: [PATCH 01/12] fix(customer-auth): register customers into the app's organization Registration put every new customer into a hardcoded organization id, which does not exist in staging, so set-password failed on the fk_customers_organization foreign key with a 500. POST /customer-auth/register/start now takes organization_id, the organization the app is built for. It must be a UUID of an existing organization, checked before the OTP is sent; it is kept in the OTP session and set-password creates the customer there. A registration started before this change has no organization in its session and is asked to start again. Co-Authored-By: Claude Opus 5.5 --- internal/contract/customer_auth_contract.go | 3 +++ internal/processor/customer_auth_processor.go | 24 +++++++++++++++++-- .../repository/customer_auth_repository.go | 12 ++++++++++ internal/validator/customer_auth_validator.go | 7 ++++++ 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/internal/contract/customer_auth_contract.go b/internal/contract/customer_auth_contract.go index 47547d5..b7501f7 100644 --- a/internal/contract/customer_auth_contract.go +++ b/internal/contract/customer_auth_contract.go @@ -16,6 +16,9 @@ type RegisterStartRequest struct { PhoneNumber string `json:"phone_number" binding:"required"` Name string `json:"name" binding:"required"` BirthDate string `json:"birth_date" binding:"required"` + // The organization (brand) the customer registers with. A customer belongs to one + // organization; the app sends the one it is built for. + OrganizationID string `json:"organization_id" binding:"required"` } type RegisterVerifyOtpRequest struct { diff --git a/internal/processor/customer_auth_processor.go b/internal/processor/customer_auth_processor.go index b2c15b6..57356b0 100644 --- a/internal/processor/customer_auth_processor.go +++ b/internal/processor/customer_auth_processor.go @@ -3,6 +3,7 @@ package processor import ( "context" "fmt" + "strings" "time" "apskel-pos-be/internal/contract" @@ -142,6 +143,20 @@ func (p *customerAuthProcessor) StartRegistration(ctx context.Context, req *cont return nil, fmt.Errorf("phone number already registered") } + // The customer joins the organization the app is built for. Check it exists now, + // before an OTP is sent, rather than failing on a foreign key at the last step. + organizationID, err := uuid.Parse(strings.TrimSpace(req.OrganizationID)) + if err != nil { + return nil, fmt.Errorf("organization_id must be a valid UUID") + } + orgExists, err := p.customerAuthRepo.OrganizationExists(ctx, organizationID) + if err != nil { + return nil, err + } + if !orgExists { + return nil, fmt.Errorf("organization not found") + } + // Generate registration token and create OTP session registrationToken := uuid.New().String() @@ -156,6 +171,7 @@ func (p *customerAuthProcessor) StartRegistration(ctx context.Context, req *cont "registration_token": registrationToken, "name": req.Name, "birth_date": req.BirthDate, + "organization_id": organizationID.String(), "step": "otp_sent", } @@ -294,10 +310,14 @@ func (p *customerAuthProcessor) SetPassword(ctx context.Context, req *contract.R return nil, fmt.Errorf("invalid birth date format: %w", err) } - defaultOrgID := uuid.MustParse("87bec7c1-e274-4f66-bac5-84e632208470") // This should be configurable + orgIDStr, _ := otpSession.Metadata["organization_id"].(string) + organizationID, err := uuid.Parse(orgIDStr) + if err != nil { + return nil, fmt.Errorf("invalid registration data: organization not found, start the registration again") + } customer := &entities.Customer{ - OrganizationID: defaultOrgID, + OrganizationID: organizationID, Name: name, PhoneNumber: &otpSession.PhoneNumber, BirthDate: &birthDate, diff --git a/internal/repository/customer_auth_repository.go b/internal/repository/customer_auth_repository.go index c2132cd..58fd1f6 100644 --- a/internal/repository/customer_auth_repository.go +++ b/internal/repository/customer_auth_repository.go @@ -6,6 +6,7 @@ import ( "apskel-pos-be/internal/entities" + "github.com/google/uuid" "gorm.io/gorm" ) @@ -16,6 +17,8 @@ type CustomerAuthRepository interface { UpdateCustomer(ctx context.Context, customer *entities.Customer) error CheckPhoneNumberExists(ctx context.Context, phoneNumber string) (bool, error) SetCustomerPassword(ctx context.Context, customerID string, passwordHash string) error + // OrganizationExists reports whether an organization with this id exists. + OrganizationExists(ctx context.Context, organizationID uuid.UUID) (bool, error) } type customerAuthRepository struct { @@ -78,3 +81,12 @@ func (r *customerAuthRepository) SetCustomerPassword(ctx context.Context, custom } return nil } + +func (r *customerAuthRepository) OrganizationExists(ctx context.Context, organizationID uuid.UUID) (bool, error) { + var count int64 + err := r.db.WithContext(ctx).Table("organizations").Where("id = ?", organizationID).Count(&count).Error + if err != nil { + return false, fmt.Errorf("failed to check organization: %w", err) + } + return count > 0, nil +} diff --git a/internal/validator/customer_auth_validator.go b/internal/validator/customer_auth_validator.go index 7497eab..51df18f 100644 --- a/internal/validator/customer_auth_validator.go +++ b/internal/validator/customer_auth_validator.go @@ -5,6 +5,8 @@ import ( "regexp" "strings" + "github.com/google/uuid" + "apskel-pos-be/internal/constants" "apskel-pos-be/internal/contract" ) @@ -68,6 +70,11 @@ func (v *CustomerAuthValidatorImpl) ValidateRegisterStartRequest(req *contract.R return errors.New("name cannot exceed 100 characters"), constants.ValidationErrorCode } + // Validate organization + if _, err := uuid.Parse(strings.TrimSpace(req.OrganizationID)); err != nil { + return errors.New("organization_id must be a valid UUID"), constants.ValidationErrorCode + } + // Validate birth date if strings.TrimSpace(req.BirthDate) == "" { return errors.New("birth date is required"), constants.ValidationErrorCode -- 2.54.0 From 8bf2fe55850d91201461fc883c99e239d19f58a0 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 18:16:31 +0700 Subject: [PATCH 02/12] fix(customer-auth): make organization_id optional at registration Requiring organization_id broke the current app, which does not send it. When it is left out and the database has exactly one organization, the customer now joins that one, so the app works unchanged. A sent organization_id must still exist, and with several organizations and none sent registration is refused with a clear message. Co-Authored-By: Claude Opus 5.5 --- internal/contract/customer_auth_contract.go | 5 +- internal/processor/customer_auth_processor.go | 47 +++++++++++++++---- .../repository/customer_auth_repository.go | 11 +++++ internal/validator/customer_auth_validator.go | 6 ++- 4 files changed, 55 insertions(+), 14 deletions(-) diff --git a/internal/contract/customer_auth_contract.go b/internal/contract/customer_auth_contract.go index b7501f7..56d28dc 100644 --- a/internal/contract/customer_auth_contract.go +++ b/internal/contract/customer_auth_contract.go @@ -17,8 +17,9 @@ type RegisterStartRequest struct { Name string `json:"name" binding:"required"` BirthDate string `json:"birth_date" binding:"required"` // The organization (brand) the customer registers with. A customer belongs to one - // organization; the app sends the one it is built for. - OrganizationID string `json:"organization_id" binding:"required"` + // organization. Optional: when it is left out and the database has exactly one + // organization, the customer joins that one. + OrganizationID string `json:"organization_id,omitempty"` } type RegisterVerifyOtpRequest struct { diff --git a/internal/processor/customer_auth_processor.go b/internal/processor/customer_auth_processor.go index 57356b0..02b59f9 100644 --- a/internal/processor/customer_auth_processor.go +++ b/internal/processor/customer_auth_processor.go @@ -143,19 +143,12 @@ func (p *customerAuthProcessor) StartRegistration(ctx context.Context, req *cont return nil, fmt.Errorf("phone number already registered") } - // The customer joins the organization the app is built for. Check it exists now, - // before an OTP is sent, rather than failing on a foreign key at the last step. - organizationID, err := uuid.Parse(strings.TrimSpace(req.OrganizationID)) - if err != nil { - return nil, fmt.Errorf("organization_id must be a valid UUID") - } - orgExists, err := p.customerAuthRepo.OrganizationExists(ctx, organizationID) + // Resolve the organization before an OTP is sent, rather than failing on a foreign + // key at the last step. + organizationID, err := p.registrationOrganization(ctx, req.OrganizationID) if err != nil { return nil, err } - if !orgExists { - return nil, fmt.Errorf("organization not found") - } // Generate registration token and create OTP session registrationToken := uuid.New().String() @@ -458,3 +451,37 @@ func (p *customerAuthProcessor) ResendOtp(ctx context.Context, req *contract.Res } // Helper functions - OTP generation is now handled by OtpProcessor + +// registrationOrganization is the organization a new customer joins: the one the app +// sent, which must exist, or, when the app sent none, the only organization there is. +// With several organizations and none sent there is no way to choose, so it refuses. +func (p *customerAuthProcessor) registrationOrganization(ctx context.Context, requested string) (uuid.UUID, error) { + requested = strings.TrimSpace(requested) + if requested != "" { + id, err := uuid.Parse(requested) + if err != nil { + return uuid.Nil, fmt.Errorf("organization_id must be a valid UUID") + } + exists, err := p.customerAuthRepo.OrganizationExists(ctx, id) + if err != nil { + return uuid.Nil, err + } + if !exists { + return uuid.Nil, fmt.Errorf("organization not found") + } + return id, nil + } + + ids, err := p.customerAuthRepo.OrganizationIDs(ctx, 2) + if err != nil { + return uuid.Nil, err + } + switch len(ids) { + case 1: + return ids[0], nil + case 0: + return uuid.Nil, fmt.Errorf("no organization exists to register customers into") + default: + return uuid.Nil, fmt.Errorf("organization_id is required: there is more than one organization") + } +} diff --git a/internal/repository/customer_auth_repository.go b/internal/repository/customer_auth_repository.go index 58fd1f6..56319d9 100644 --- a/internal/repository/customer_auth_repository.go +++ b/internal/repository/customer_auth_repository.go @@ -19,6 +19,8 @@ type CustomerAuthRepository interface { SetCustomerPassword(ctx context.Context, customerID string, passwordHash string) error // OrganizationExists reports whether an organization with this id exists. OrganizationExists(ctx context.Context, organizationID uuid.UUID) (bool, error) + // OrganizationIDs returns up to limit organization ids. + OrganizationIDs(ctx context.Context, limit int) ([]uuid.UUID, error) } type customerAuthRepository struct { @@ -90,3 +92,12 @@ func (r *customerAuthRepository) OrganizationExists(ctx context.Context, organiz } return count > 0, nil } + +func (r *customerAuthRepository) OrganizationIDs(ctx context.Context, limit int) ([]uuid.UUID, error) { + var ids []uuid.UUID + err := r.db.WithContext(ctx).Table("organizations").Order("created_at").Limit(limit).Pluck("id", &ids).Error + if err != nil { + return nil, fmt.Errorf("failed to list organizations: %w", err) + } + return ids, nil +} diff --git a/internal/validator/customer_auth_validator.go b/internal/validator/customer_auth_validator.go index 51df18f..a62f459 100644 --- a/internal/validator/customer_auth_validator.go +++ b/internal/validator/customer_auth_validator.go @@ -71,8 +71,10 @@ func (v *CustomerAuthValidatorImpl) ValidateRegisterStartRequest(req *contract.R } // Validate organization - if _, err := uuid.Parse(strings.TrimSpace(req.OrganizationID)); err != nil { - return errors.New("organization_id must be a valid UUID"), constants.ValidationErrorCode + if orgID := strings.TrimSpace(req.OrganizationID); orgID != "" { + if _, err := uuid.Parse(orgID); err != nil { + return errors.New("organization_id must be a valid UUID"), constants.ValidationErrorCode + } } // Validate birth date -- 2.54.0 From c1ec6a3dfde9e745e8bff2c53ebe678b849fb447 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 19:21:13 +0700 Subject: [PATCH 03/12] feat(customer): list the customer's outlets Adds GET /customer/outlets for the customer app: the active outlets of the customer's organization, where their EnakPoint and EnakCoin can be used, sorted by name. Each carries its name and address, and from the outlet's loyalty settings whether the cashier accepts EnakPoint and whether orders there earn EnakPoint or EnakCoin. Nothing internal (printer settings, tax rate) is exposed. The outlets list under /outlets needs a staff token, so the app had no way to show where the wallet works. Co-Authored-By: Claude Opus 5.5 --- internal/app/app.go | 5 ++ internal/handler/customer_outlet_handler.go | 26 +++++++ internal/models/customer_outlet.go | 16 ++++ .../processor/customer_outlet_processor.go | 49 ++++++++++++ .../customer_outlet_processor_test.go | 77 +++++++++++++++++++ .../repository/customer_outlet_repository.go | 60 +++++++++++++++ internal/router/router.go | 5 +- internal/router/router_test.go | 1 + internal/service/customer_outlet_service.go | 40 ++++++++++ 9 files changed, 278 insertions(+), 1 deletion(-) create mode 100644 internal/handler/customer_outlet_handler.go create mode 100644 internal/models/customer_outlet.go create mode 100644 internal/processor/customer_outlet_processor.go create mode 100644 internal/processor/customer_outlet_processor_test.go create mode 100644 internal/repository/customer_outlet_repository.go create mode 100644 internal/service/customer_outlet_service.go 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) +} -- 2.54.0 From a24d5f0561793191d9081c983389c0cdccaea8c5 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 19:36:35 +0700 Subject: [PATCH 04/12] feat(customer): order history and detail for the customer app Adds GET /customer/orders and GET /customer/orders/:id for the customer app: the orders linked to the logged-in customer across their organization's outlets, newest first, paginated (limit 1-100, default 20). The list shows the order number, outlet, type, status, total, item count, void/refund flags and the EnakPoint and EnakCoin it earned. The detail adds the amounts, the items with product and variant names, weight and unit for weighed lines, modifiers and notes, and the payments with the method and, for EnakPoint, the points used. Costs, cashier and other internal fields are left out. Another customer's order answers 404 like one that does not exist. Co-Authored-By: Claude Opus 5.5 --- internal/app/app.go | 5 + internal/handler/customer_order_handler.go | 49 ++++++ internal/models/customer_order.go | 74 +++++++++ .../processor/customer_order_processor.go | 157 ++++++++++++++++++ .../customer_order_processor_test.go | 145 ++++++++++++++++ .../repository/customer_order_repository.go | 157 ++++++++++++++++++ internal/router/router.go | 6 +- internal/router/router_test.go | 2 + internal/service/customer_order_service.go | 57 +++++++ 9 files changed, 651 insertions(+), 1 deletion(-) create mode 100644 internal/handler/customer_order_handler.go create mode 100644 internal/models/customer_order.go create mode 100644 internal/processor/customer_order_processor.go create mode 100644 internal/processor/customer_order_processor_test.go create mode 100644 internal/repository/customer_order_repository.go create mode 100644 internal/service/customer_order_service.go diff --git a/internal/app/app.go b/internal/app/app.go index 9ea2e47..e477e73 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -166,6 +166,7 @@ func (a *App) Initialize(cfg *config.Config) error { services.customerWalletService, services.customerDeviceService, services.customerOutletService, + services.customerOrderService, a.redisClient, ) @@ -405,6 +406,7 @@ type processors struct { walletTraceProcessor *processor.WalletTraceProcessor customerDeviceProcessor *processor.CustomerDeviceProcessor customerOutletProcessor *processor.CustomerOutletProcessor + customerOrderProcessor *processor.CustomerOrderProcessor } func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processors { @@ -487,6 +489,7 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor walletTraceProcessor: processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(a.db)), customerDeviceProcessor: customerDeviceProcessor, customerOutletProcessor: processor.NewCustomerOutletProcessor(repository.NewCustomerOutletRepository(a.db), loyaltySettingsProcessor), + customerOrderProcessor: processor.NewCustomerOrderProcessor(repository.NewCustomerOrderRepository(a.db), earningProcessor), walletAdminProcessor: processor.NewWalletAdminProcessor(repository.NewWalletAdminRepository(a.db), repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), loyaltySettingsProcessor, repos.txManager), } } @@ -538,6 +541,7 @@ type services struct { customerWalletService *service.CustomerWalletServiceImpl customerDeviceService *service.CustomerDeviceServiceImpl customerOutletService *service.CustomerOutletServiceImpl + customerOrderService *service.CustomerOrderServiceImpl } func (a *App) initServices(processors *processors, repos *repositories, cfg *config.Config) *services { @@ -627,6 +631,7 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con customerWalletService: service.NewCustomerWalletService(processors.walletExchangeProcessor, processors.walletTransferProcessor), customerDeviceService: service.NewCustomerDeviceService(processors.customerDeviceProcessor), customerOutletService: service.NewCustomerOutletService(processors.customerOutletProcessor), + customerOrderService: service.NewCustomerOrderService(processors.customerOrderProcessor), } } diff --git a/internal/handler/customer_order_handler.go b/internal/handler/customer_order_handler.go new file mode 100644 index 0000000..3874676 --- /dev/null +++ b/internal/handler/customer_order_handler.go @@ -0,0 +1,49 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" +) + +// CustomerOrderHandler serves the customer app's order history. +type CustomerOrderHandler struct { + orders service.CustomerOrderService +} + +func NewCustomerOrderHandler(orders service.CustomerOrderService) *CustomerOrderHandler { + return &CustomerOrderHandler{orders: orders} +} + +// List is GET /customer/orders?page=&limit=. +func (h *CustomerOrderHandler) List(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerOrderHandler::List") + if !ok { + return + } + var query models.ListCustomerOrdersQuery + if err := c.ShouldBindQuery(&query); err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "page and limit must be whole numbers"), + }), "CustomerOrderHandler::List") + return + } + util.HandleResponse(c.Writer, c.Request, h.orders.List(c.Request.Context(), customerID, query), "CustomerOrderHandler::List") +} + +// Detail is GET /customer/orders/:id. +func (h *CustomerOrderHandler) Detail(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerOrderHandler::Detail") + if !ok { + return + } + orderID, ok := parseUUIDParam(c, "id", "CustomerOrderHandler::Detail") + if !ok { + return + } + util.HandleResponse(c.Writer, c.Request, h.orders.Detail(c.Request.Context(), customerID, orderID), "CustomerOrderHandler::Detail") +} diff --git a/internal/models/customer_order.go b/internal/models/customer_order.go new file mode 100644 index 0000000..c5e5fad --- /dev/null +++ b/internal/models/customer_order.go @@ -0,0 +1,74 @@ +package models + +import ( + "time" + + "github.com/google/uuid" +) + +// CustomerOrderSummary is one order in GET /customer/orders. +type CustomerOrderSummary struct { + ID uuid.UUID `json:"id"` + OrderNumber string `json:"order_number"` + OutletID uuid.UUID `json:"outlet_id"` + OutletName string `json:"outlet_name"` + OrderType string `json:"order_type"` + Status string `json:"status"` + PaymentStatus string `json:"payment_status"` + TotalAmount float64 `json:"total_amount"` + ItemCount int64 `json:"item_count"` + IsVoid bool `json:"is_void"` + IsRefund bool `json:"is_refund"` + // EnakPoint and EnakCoin the order earned; 0 when it earned nothing. + PointsEarned int64 `json:"points_earned"` + CoinsEarned int64 `json:"coins_earned"` + CreatedAt time.Time `json:"created_at"` +} + +// CustomerOrderDetail is GET /customer/orders/:id. +type CustomerOrderDetail struct { + CustomerOrderSummary + TableNumber *string `json:"table_number"` + Subtotal float64 `json:"subtotal"` + DiscountAmount float64 `json:"discount_amount"` + TaxAmount float64 `json:"tax_amount"` + RefundAmount float64 `json:"refund_amount"` + Items []CustomerOrderItem `json:"items"` + Payments []CustomerOrderPayment `json:"payments"` +} + +type CustomerOrderItem struct { + ID uuid.UUID `json:"id"` + ProductID uuid.UUID `json:"product_id"` + ProductName string `json:"product_name"` + VariantName *string `json:"variant_name"` + Quantity int `json:"quantity"` + // Set for products sold by weight, in UnitName. + Weight *float64 `json:"weight,omitempty"` + UnitName *string `json:"unit_name,omitempty"` + UnitPrice float64 `json:"unit_price"` + TotalPrice float64 `json:"total_price"` + RefundQuantity int `json:"refund_quantity"` + Modifiers []map[string]interface{} `json:"modifiers"` + Notes *string `json:"notes,omitempty"` + Status string `json:"status"` +} + +type CustomerOrderPayment struct { + ID uuid.UUID `json:"id"` + MethodName string `json:"method_name"` + MethodType string `json:"method_type"` + Amount float64 `json:"amount"` + Status string `json:"status"` + RefundAmount float64 `json:"refund_amount"` + // Set for a payment with EnakPoint. + PointsUsed *int64 `json:"points_used,omitempty"` + PointValue *float64 `json:"point_value,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +// ListCustomerOrdersQuery is GET /customer/orders. +type ListCustomerOrdersQuery struct { + Page int `form:"page"` + Limit int `form:"limit"` +} diff --git a/internal/processor/customer_order_processor.go b/internal/processor/customer_order_processor.go new file mode 100644 index 0000000..3a44014 --- /dev/null +++ b/internal/processor/customer_order_processor.go @@ -0,0 +1,157 @@ +package processor + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +const ( + customerOrdersPageLimit = 20 + customerOrdersMaxLimit = 100 +) + +type orderEarnedReader interface { + EarnedByOrders(ctx context.Context, orderIDs []uuid.UUID) (map[uuid.UUID]OrderEarned, error) +} + +// CustomerOrderProcessor serves the customer app's order history: the customer's own +// orders only, without costs or staff details. +type CustomerOrderProcessor struct { + repo repository.CustomerOrderRepository + earned orderEarnedReader +} + +func NewCustomerOrderProcessor(repo repository.CustomerOrderRepository, earned orderEarnedReader) *CustomerOrderProcessor { + return &CustomerOrderProcessor{repo: repo, earned: earned} +} + +// List is GET /customer/orders: the customer's orders across all outlets, newest first. +func (p *CustomerOrderProcessor) List(ctx context.Context, customerID uuid.UUID, query models.ListCustomerOrdersQuery) (*models.PaginatedResponse[models.CustomerOrderSummary], error) { + page, limit := query.Page, query.Limit + if page == 0 { + page = 1 + } + if limit == 0 { + limit = customerOrdersPageLimit + } + if page < 1 || limit < 1 || limit > customerOrdersMaxLimit { + return nil, fmt.Errorf("%w: page must be at least 1 and limit between 1 and %d", ErrInvalidWalletQuery, customerOrdersMaxLimit) + } + + rows, total, err := p.repo.ListOrders(ctx, customerID, (page-1)*limit, limit) + if err != nil { + return nil, err + } + ids := make([]uuid.UUID, 0, len(rows)) + for _, r := range rows { + ids = append(ids, r.ID) + } + earned, err := p.earned.EarnedByOrders(ctx, ids) + if err != nil { + return nil, err + } + data := make([]models.CustomerOrderSummary, 0, len(rows)) + for _, r := range rows { + data = append(data, customerOrderSummary(r, earned[r.ID])) + } + return &models.PaginatedResponse[models.CustomerOrderSummary]{ + Data: data, + Pagination: models.Pagination{ + Page: page, + Limit: limit, + Total: total, + TotalPages: int((total + int64(limit) - 1) / int64(limit)), + }, + }, nil +} + +// Detail is GET /customer/orders/:id. Another customer's order is +// repository.ErrCustomerOrderNotFound, like one that does not exist. +func (p *CustomerOrderProcessor) Detail(ctx context.Context, customerID, orderID uuid.UUID) (*models.CustomerOrderDetail, error) { + row, err := p.repo.GetOrder(ctx, customerID, orderID) + if err != nil { + return nil, err + } + items, err := p.repo.ListItems(ctx, orderID) + if err != nil { + return nil, err + } + payments, err := p.repo.ListPayments(ctx, orderID) + if err != nil { + return nil, err + } + earned, err := p.earned.EarnedByOrders(ctx, []uuid.UUID{orderID}) + if err != nil { + return nil, err + } + + detail := &models.CustomerOrderDetail{ + CustomerOrderSummary: customerOrderSummary(*row, earned[orderID]), + TableNumber: row.TableNumber, + Subtotal: row.Subtotal, + DiscountAmount: row.DiscountAmount, + TaxAmount: row.TaxAmount, + RefundAmount: row.RefundAmount, + Items: make([]models.CustomerOrderItem, 0, len(items)), + Payments: make([]models.CustomerOrderPayment, 0, len(payments)), + } + for _, it := range items { + modifiers := []map[string]interface{}(it.Modifiers) + if modifiers == nil { + modifiers = []map[string]interface{}{} + } + detail.Items = append(detail.Items, models.CustomerOrderItem{ + ID: it.ID, + ProductID: it.ProductID, + ProductName: it.ProductName, + VariantName: it.VariantName, + Quantity: it.Quantity, + Weight: it.Weight, + UnitName: it.UnitName, + UnitPrice: it.UnitPrice, + TotalPrice: it.TotalPrice, + RefundQuantity: it.RefundQuantity, + Modifiers: modifiers, + Notes: it.Notes, + Status: it.Status, + }) + } + for _, pay := range payments { + detail.Payments = append(detail.Payments, models.CustomerOrderPayment{ + ID: pay.ID, + MethodName: pay.MethodName, + MethodType: pay.MethodType, + Amount: pay.Amount, + Status: pay.Status, + RefundAmount: pay.RefundAmount, + PointsUsed: pay.PointsUsed, + PointValue: pay.PointValue, + CreatedAt: pay.CreatedAt, + }) + } + return detail, nil +} + +func customerOrderSummary(r repository.CustomerOrderRow, earned OrderEarned) models.CustomerOrderSummary { + return models.CustomerOrderSummary{ + ID: r.ID, + OrderNumber: r.OrderNumber, + OutletID: r.OutletID, + OutletName: r.OutletName, + OrderType: r.OrderType, + Status: r.Status, + PaymentStatus: r.PaymentStatus, + TotalAmount: r.TotalAmount, + ItemCount: r.ItemCount, + IsVoid: r.IsVoid, + IsRefund: r.IsRefund, + PointsEarned: earned.Points, + CoinsEarned: earned.Coins, + CreatedAt: r.CreatedAt, + } +} diff --git a/internal/processor/customer_order_processor_test.go b/internal/processor/customer_order_processor_test.go new file mode 100644 index 0000000..380e9ad --- /dev/null +++ b/internal/processor/customer_order_processor_test.go @@ -0,0 +1,145 @@ +package processor + +import ( + "context" + "testing" + "time" + + "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 customerOrderRepoFake struct { + owner map[uuid.UUID]uuid.UUID // order -> customer + orders []repository.CustomerOrderRow + items map[uuid.UUID][]repository.CustomerOrderItemRow + payments map[uuid.UUID][]repository.CustomerOrderPaymentRow + offset int + limit int +} + +func (f *customerOrderRepoFake) ListOrders(_ context.Context, customerID uuid.UUID, offset, limit int) ([]repository.CustomerOrderRow, int64, error) { + f.offset, f.limit = offset, limit + var mine []repository.CustomerOrderRow + for _, o := range f.orders { + if f.owner[o.ID] == customerID { + mine = append(mine, o) + } + } + return mine, int64(len(mine)), nil +} + +func (f *customerOrderRepoFake) GetOrder(_ context.Context, customerID, orderID uuid.UUID) (*repository.CustomerOrderRow, error) { + for _, o := range f.orders { + if o.ID == orderID && f.owner[o.ID] == customerID { + c := o + return &c, nil + } + } + return nil, repository.ErrCustomerOrderNotFound +} + +func (f *customerOrderRepoFake) ListItems(_ context.Context, orderID uuid.UUID) ([]repository.CustomerOrderItemRow, error) { + return f.items[orderID], nil +} + +func (f *customerOrderRepoFake) ListPayments(_ context.Context, orderID uuid.UUID) ([]repository.CustomerOrderPaymentRow, error) { + return f.payments[orderID], nil +} + +type earnedFake map[uuid.UUID]OrderEarned + +func (f earnedFake) EarnedByOrders(_ context.Context, ids []uuid.UUID) (map[uuid.UUID]OrderEarned, error) { + out := map[uuid.UUID]OrderEarned{} + for _, id := range ids { + if e, ok := f[id]; ok { + out[id] = e + } + } + return out, nil +} + +func newCustomerOrderTest() (*customerOrderRepoFake, uuid.UUID, uuid.UUID, uuid.UUID) { + customer, other := uuid.New(), uuid.New() + mine, theirs := uuid.New(), uuid.New() + repo := &customerOrderRepoFake{ + owner: map[uuid.UUID]uuid.UUID{mine: customer, theirs: other}, + orders: []repository.CustomerOrderRow{ + {ID: mine, OrderNumber: "ORD-1", OutletName: "Gokuna 1", Status: "completed", PaymentStatus: "completed", Subtotal: 90000, TotalAmount: 99000, ItemCount: 2, CreatedAt: time.Now()}, + {ID: theirs, OrderNumber: "ORD-2"}, + }, + } + return repo, customer, mine, theirs +} + +func TestCustomerOrders_ListShowsOnlyTheCustomersOrdersWithEarning(t *testing.T) { + repo, customer, mine, _ := newCustomerOrderTest() + p := NewCustomerOrderProcessor(repo, earnedFake{mine: {Points: 900, Coins: 3}}) + + got, err := p.List(context.Background(), customer, models.ListCustomerOrdersQuery{Page: 2, Limit: 10}) + require.NoError(t, err) + require.Len(t, got.Data, 1) + assert.Equal(t, "ORD-1", got.Data[0].OrderNumber) + assert.Equal(t, int64(900), got.Data[0].PointsEarned) + assert.Equal(t, int64(3), got.Data[0].CoinsEarned) + assert.Equal(t, 10, repo.offset, "page 2 of 10 skips the first 10") + assert.Equal(t, 10, repo.limit) + assert.Equal(t, 2, got.Pagination.Page) +} + +func TestCustomerOrders_ListDefaultsAndLimits(t *testing.T) { + repo, customer, _, _ := newCustomerOrderTest() + p := NewCustomerOrderProcessor(repo, earnedFake{}) + + got, err := p.List(context.Background(), customer, models.ListCustomerOrdersQuery{}) + require.NoError(t, err) + assert.Equal(t, 1, got.Pagination.Page) + assert.Equal(t, 20, got.Pagination.Limit) + + for _, q := range []models.ListCustomerOrdersQuery{{Page: -1}, {Limit: 101}, {Limit: -5}} { + _, err := p.List(context.Background(), customer, q) + assert.ErrorIs(t, err, ErrInvalidWalletQuery, "%+v", q) + } +} + +func TestCustomerOrders_DetailHasItemsPaymentsAndEarning(t *testing.T) { + repo, customer, mine, _ := newCustomerOrderTest() + variant, unit := "Large", "ons" + weight := 4.2 + points, value := int64(12500), 1.0 + repo.items = map[uuid.UUID][]repository.CustomerOrderItemRow{ + mine: { + {ProductName: "Kopi Susu", VariantName: &variant, Quantity: 2, UnitPrice: 25000, TotalPrice: 50000, Status: "completed"}, + {ProductName: "Ikan Tude", Quantity: 1, Weight: &weight, UnitName: &unit, UnitPrice: 4500, TotalPrice: 18900, Status: "completed"}, + }, + } + repo.payments = map[uuid.UUID][]repository.CustomerOrderPaymentRow{ + mine: { + {MethodName: "EnakPoint", MethodType: "point", Amount: 12500, Status: "completed", PointsUsed: &points, PointValue: &value}, + {MethodName: "Cash", MethodType: "cash", Amount: 86500, Status: "completed"}, + }, + } + p := NewCustomerOrderProcessor(repo, earnedFake{mine: {Points: 865}}) + + got, err := p.Detail(context.Background(), customer, mine) + require.NoError(t, err) + assert.Equal(t, "Gokuna 1", got.OutletName) + assert.Equal(t, float64(90000), got.Subtotal) + assert.Equal(t, int64(865), got.PointsEarned) + require.Len(t, got.Items, 2) + assert.Equal(t, "Large", *got.Items[0].VariantName) + assert.Equal(t, []map[string]interface{}{}, got.Items[0].Modifiers, "no modifiers is an empty list, not null") + assert.Equal(t, 4.2, *got.Items[1].Weight) + require.Len(t, got.Payments, 2) + assert.Equal(t, int64(12500), *got.Payments[0].PointsUsed) +} + +func TestCustomerOrders_AnotherCustomersOrderIsNotFound(t *testing.T) { + repo, customer, _, theirs := newCustomerOrderTest() + _, err := NewCustomerOrderProcessor(repo, earnedFake{}).Detail(context.Background(), customer, theirs) + assert.ErrorIs(t, err, repository.ErrCustomerOrderNotFound) +} diff --git a/internal/repository/customer_order_repository.go b/internal/repository/customer_order_repository.go new file mode 100644 index 0000000..f6bf8d2 --- /dev/null +++ b/internal/repository/customer_order_repository.go @@ -0,0 +1,157 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/entities" +) + +// ErrCustomerOrderNotFound means the order does not exist or belongs to another +// customer; the two are not told apart. +var ErrCustomerOrderNotFound = errors.New("order not found") + +// CustomerOrderRow is one order as the customer app lists it. +type CustomerOrderRow struct { + ID uuid.UUID + OrderNumber string + OutletID uuid.UUID + OutletName string + OrderType string + TableNumber *string + Status string + PaymentStatus string + Subtotal float64 + DiscountAmount float64 + TaxAmount float64 + TotalAmount float64 + RefundAmount float64 + IsVoid bool + IsRefund bool + ItemCount int64 + CreatedAt time.Time +} + +// CustomerOrderItemRow is one line of an order, without costs. +type CustomerOrderItemRow struct { + ID uuid.UUID + ProductID uuid.UUID + ProductName string + VariantName *string + Quantity int + Weight *float64 + UnitName *string + UnitPrice float64 + TotalPrice float64 + RefundQuantity int + Modifiers entities.Modifiers `gorm:"type:jsonb"` + Notes *string + Status string +} + +// CustomerOrderPaymentRow is one payment of an order. +type CustomerOrderPaymentRow struct { + ID uuid.UUID + MethodName string + MethodType string + Amount float64 + Status string + RefundAmount float64 + PointsUsed *int64 + PointValue *float64 + CreatedAt time.Time +} + +// CustomerOrderRepository reads a customer's own orders for the customer app. Every +// read is scoped to the customer, so one customer can never see another's order. +type CustomerOrderRepository interface { + // ListOrders returns a page of the customer's orders, newest first, and the total. + ListOrders(ctx context.Context, customerID uuid.UUID, offset, limit int) ([]CustomerOrderRow, int64, error) + // GetOrder returns ErrCustomerOrderNotFound unless the order is the customer's. + GetOrder(ctx context.Context, customerID, orderID uuid.UUID) (*CustomerOrderRow, error) + ListItems(ctx context.Context, orderID uuid.UUID) ([]CustomerOrderItemRow, error) + ListPayments(ctx context.Context, orderID uuid.UUID) ([]CustomerOrderPaymentRow, error) +} + +type customerOrderRepository struct { + db *gorm.DB +} + +func NewCustomerOrderRepository(db *gorm.DB) CustomerOrderRepository { + return &customerOrderRepository{db: db} +} + +const customerOrderColumns = `o.id, o.order_number, o.outlet_id, COALESCE(ol.name, '') AS outlet_name, + o.order_type, o.table_number, o.status, o.payment_status, o.subtotal, o.discount_amount, + o.tax_amount, o.total_amount, o.refund_amount, o.is_void, o.is_refund, + (SELECT COUNT(*) FROM order_items oi WHERE oi.order_id = o.id) AS item_count, o.created_at` + +func (r *customerOrderRepository) ListOrders(ctx context.Context, customerID uuid.UUID, offset, limit int) ([]CustomerOrderRow, int64, error) { + db := DBFromContext(ctx, r.db).WithContext(ctx) + var total int64 + if err := db.Table("orders").Where("customer_id = ?", customerID).Count(&total).Error; err != nil { + return nil, 0, fmt.Errorf("failed to count customer orders: %w", err) + } + var rows []CustomerOrderRow + err := db.Raw(`SELECT `+customerOrderColumns+` + FROM orders o LEFT JOIN outlets ol ON ol.id = o.outlet_id + WHERE o.customer_id = ? + ORDER BY o.created_at DESC, o.id + LIMIT ? OFFSET ?`, customerID, limit, offset).Scan(&rows).Error + if err != nil { + return nil, 0, fmt.Errorf("failed to list customer orders: %w", err) + } + return rows, total, nil +} + +func (r *customerOrderRepository) GetOrder(ctx context.Context, customerID, orderID uuid.UUID) (*CustomerOrderRow, error) { + var rows []CustomerOrderRow + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`SELECT `+customerOrderColumns+` + FROM orders o LEFT JOIN outlets ol ON ol.id = o.outlet_id + WHERE o.id = ? AND o.customer_id = ?`, orderID, customerID).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to get customer order: %w", err) + } + if len(rows) == 0 { + return nil, ErrCustomerOrderNotFound + } + return &rows[0], nil +} + +func (r *customerOrderRepository) ListItems(ctx context.Context, orderID uuid.UUID) ([]CustomerOrderItemRow, error) { + var rows []CustomerOrderItemRow + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT oi.id, oi.product_id, COALESCE(p.name, '') AS product_name, pv.name AS variant_name, + oi.quantity, oi.weight, COALESCE(u.abbreviation, u.name) AS unit_name, + oi.unit_price, oi.total_price, oi.refund_quantity, oi.modifiers, oi.notes, oi.status + FROM order_items oi + LEFT JOIN products p ON p.id = oi.product_id + LEFT JOIN product_variants pv ON pv.id = oi.product_variant_id + LEFT JOIN units u ON u.id = oi.unit_id + WHERE oi.order_id = ? + ORDER BY oi.created_at, oi.id`, orderID).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list order items: %w", err) + } + return rows, nil +} + +func (r *customerOrderRepository) ListPayments(ctx context.Context, orderID uuid.UUID) ([]CustomerOrderPaymentRow, error) { + var rows []CustomerOrderPaymentRow + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT pay.id, COALESCE(pm.name, '') AS method_name, COALESCE(pm.type, '') AS method_type, + pay.amount, pay.status, pay.refund_amount, pay.points_used, pay.point_value, pay.created_at + FROM payments pay + LEFT JOIN payment_methods pm ON pm.id = pay.payment_method_id + WHERE pay.order_id = ? + ORDER BY pay.created_at, pay.id`, orderID).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list order payments: %w", err) + } + return rows, nil +} diff --git a/internal/router/router.go b/internal/router/router.go index cf77c39..55bc014 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -62,12 +62,13 @@ type Router struct { customerWalletHandler *handler.CustomerWalletHandler customerDeviceHandler *handler.CustomerDeviceHandler customerOutletHandler *handler.CustomerOutletHandler + customerOrderHandler *handler.CustomerOrderHandler 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, customerOutletService service.CustomerOutletService, 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, customerOrderService service.CustomerOrderService, redisClient *redis.Client) *Router { return &Router{ config: cfg, @@ -121,6 +122,7 @@ func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authSer customerWalletHandler: handler.NewCustomerWalletHandler(customerWalletService), customerDeviceHandler: handler.NewCustomerDeviceHandler(customerDeviceService), customerOutletHandler: handler.NewCustomerOutletHandler(customerOutletService), + customerOrderHandler: handler.NewCustomerOrderHandler(customerOrderService), redisClient: redisClient, } } @@ -182,6 +184,8 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { customer.PUT("/devices", r.customerDeviceHandler.Register) customer.DELETE("/devices/:device_id", r.customerDeviceHandler.Unregister) customer.GET("/outlets", r.customerOutletHandler.List) + customer.GET("/orders", r.customerOrderHandler.List) + customer.GET("/orders/:id", r.customerOrderHandler.Detail) 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 75cafc7..18a39f5 100644 --- a/internal/router/router_test.go +++ b/internal/router/router_test.go @@ -45,6 +45,8 @@ func TestAllRoutesRegister(t *testing.T) { "PUT /api/v1/customer/devices", "DELETE /api/v1/customer/devices/:device_id", "GET /api/v1/customer/outlets", + "GET /api/v1/customer/orders", + "GET /api/v1/customer/orders/:id", "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_order_service.go b/internal/service/customer_order_service.go new file mode 100644 index 0000000..50019c5 --- /dev/null +++ b/internal/service/customer_order_service.go @@ -0,0 +1,57 @@ +package service + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +// CustomerOrderService serves the customer app's order history. +type CustomerOrderService interface { + List(ctx context.Context, customerID uuid.UUID, query models.ListCustomerOrdersQuery) *contract.Response + Detail(ctx context.Context, customerID, orderID uuid.UUID) *contract.Response +} + +type CustomerOrderServiceImpl struct { + orders *processor.CustomerOrderProcessor +} + +func NewCustomerOrderService(orders *processor.CustomerOrderProcessor) *CustomerOrderServiceImpl { + return &CustomerOrderServiceImpl{orders: orders} +} + +func (s *CustomerOrderServiceImpl) List(ctx context.Context, customerID uuid.UUID, query models.ListCustomerOrdersQuery) *contract.Response { + orders, err := s.orders.List(ctx, customerID, query) + if err != nil { + return customerOrderErrorResponse(err) + } + return contract.BuildSuccessResponse(orders) +} + +func (s *CustomerOrderServiceImpl) Detail(ctx context.Context, customerID, orderID uuid.UUID) *contract.Response { + order, err := s.orders.Detail(ctx, customerID, orderID) + if err != nil { + return customerOrderErrorResponse(err) + } + return contract.BuildSuccessResponse(order) +} + +func customerOrderErrorResponse(err error) *contract.Response { + code := constants.InternalServerErrorCode + switch { + case errors.Is(err, repository.ErrCustomerOrderNotFound): + code = constants.NotFoundErrorCode + case errors.Is(err, processor.ErrInvalidWalletQuery): + code = constants.ValidationErrorCode + } + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.RequestEntity, err.Error()), + }) +} -- 2.54.0 From f16a5da9517181d2acf560267c367e1290aecf00 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 19:39:52 +0700 Subject: [PATCH 05/12] docs(customer): mobile app guide, outlets, order history and registration Adds docs/mobile-customer-enakpoint.md, written as a brief for building the customer app: the UI rules, the API conventions, each screen with its requests and responses, push handling, PIN flows, paying at the cashier, exchange, transfer, games, what was removed, and a checklist. It covers the new GET /customer/outlets, GET /customer/orders and /customer/orders/:id, and the optional organization_id at registration, which the API reference now lists too. Co-Authored-By: Claude Opus 5.5 --- docs/api-enakpoint.md | 5 + docs/mobile-customer-enakpoint.md | 614 ++++++++++++++++++++++++++++++ 2 files changed, 619 insertions(+) create mode 100644 docs/mobile-customer-enakpoint.md diff --git a/docs/api-enakpoint.md b/docs/api-enakpoint.md index 1aeb01b..0f168b1 100644 --- a/docs/api-enakpoint.md +++ b/docs/api-enakpoint.md @@ -41,6 +41,11 @@ Semua endpoint EnakPoint (`POINT`, bisa bayar order) dan EnakCoin (`COIN`, untuk | GET | `/customer/wallet/expiring` | Saldo yang akan kedaluwarsa, per currency dan tanggal | | PUT | `/customer/devices` | Daftarkan token FCM device | | DELETE | `/customer/devices/:device_id` | Hapus device saat logout | +| GET | `/customer/outlets` | Outlet aktif di organisasi customer, dengan `accepts_point_payment`, `earns_points`, `earns_coins` | +| GET | `/customer/orders` | Riwayat order customer (`page`, `limit`), dengan `points_earned` / `coins_earned` | +| GET | `/customer/orders/:id` | Detail order: item, pembayaran, EnakPoint yang dipakai; order customer lain → `404` | + +Registrasi (`POST /customer-auth/register/start`) menerima `organization_id` opsional: bila tidak dikirim dan hanya ada satu organisasi, customer masuk ke organisasi itu. Contoh request dan response lengkap untuk outlet dan order ada di [`mobile-customer-enakpoint.md`](./mobile-customer-enakpoint.md) §4.4–§4.5. ### GET /customer/wallet diff --git a/docs/mobile-customer-enakpoint.md b/docs/mobile-customer-enakpoint.md new file mode 100644 index 0000000..1c7a8d2 --- /dev/null +++ b/docs/mobile-customer-enakpoint.md @@ -0,0 +1,614 @@ +# Prompt: fitur EnakPoint & EnakCoin di Mobile App Customer + +Kamu mengerjakan aplikasi mobile untuk **customer** (bukan kasir, bukan backoffice). +Tugasmu: membangun fitur loyalitas EnakPoint & EnakCoin di aplikasi, memakai API backend +yang sudah jadi dan dijelaskan di dokumen ini. Jangan mengarang endpoint, field, atau +aturan yang tidak tertulis di sini; kalau ada yang kurang jelas, tanyakan dulu. + +--- + +## 1. Konteks bisnis + +| | EnakPoint (`POINT`) | EnakCoin (`COIN`) | +|---|---|---| +| Didapat dari | Belanja (order lunas), koreksi admin, tukar EnakCoin | Belanja, koreksi admin | +| Dipakai untuk | **Membayar order** | **Main game**, ditukar ke EnakPoint | +| Bisa dikirim ke customer lain | Ya | Ya | +| Bisa kedaluwarsa | Ya, bila owner mengaktifkan | Ya, bila owner mengaktifkan | + +Tidak ada lagi "token". Semua yang dulu token sekarang EnakCoin, dan endpoint serta +field bernama token sudah dihapus dari API. + +### Aturan yang wajib dipatuhi di UI + +1. **Semua jumlah bilangan bulat.** Tidak ada desimal pada EnakPoint atau EnakCoin. +2. **Saldo bukan uang.** Nilai rupiah EnakPoint selalu ditulis **"setara potongan + Rp …"**, tidak pernah "saldo Rp …" atau "uang". Tidak ada fitur tarik tunai. +3. **PIN 6 digit wajib** untuk: membuat kode bayar, tukar + EnakCoin, dan transfer. **Main game tidak butuh PIN.** Melihat saldo dan riwayat + tidak butuh PIN. +4. **PIN terpisah dari password login** dan selalu dikirim sebagai **string** (supaya + nol di depan tidak hilang). Jangan pernah menyimpan PIN di perangkat, log, atau + analytics. +5. **Satu akun customer = satu organisasi.** Saldo berlaku di semua outlet organisasi itu. +6. **Waktu memakai WIB.** Tanggal kedaluwarsa berarti saldo masih bisa dipakai sampai + 23:59:59 WIB di tanggal itu. + +--- + +## 2. Koneksi ke API + +- Base URL: `/api/v1` +- Semua endpoint customer: header `Authorization: Bearer ` +- Semua jumlah di request dan response berupa integer. + +### Registrasi customer + +`POST /api/v1/customer-auth/register/start` menerima `organization_id` (opsional): + +```json +{ "phone_number": "0812…", "name": "Budi", "birth_date": "2000-01-31", "organization_id": "648b96a0-1d1d-414e-baee-37e9d6317b4e" } +``` + +- Customer terdaftar di satu organisasi, dan saldonya berlaku di semua outlet organisasi itu. +- Bila `organization_id` tidak dikirim dan backend hanya punya satu organisasi, customer + otomatis masuk ke organisasi itu. Bila ada lebih dari satu, registrasi ditolak + ("organization_id is required"), jadi sebaiknya app selalu mengirimnya dari config per + environment/brand. +- `organization_id` yang dikirim harus ada; bila tidak, registrasi ditolak sebelum OTP dikirim. +- Wallet customer baru belum punya baris sampai saldo pertama kali bergerak; + `GET /customer/wallet` tetap menjawab saldo 0. + +### Format response + +Sukses: + +```json +{ "success": true, "data": { … }, "errors": null } +``` + +Gagal: + +```json +{ "success": false, "data": null, "errors": [{ "code": "304", "entity": "wallet_service", "cause": "wallet move refused: not enough EnakCoin" }] } +``` + +| `errors[0].code` | HTTP | Arti | Yang dilakukan app | +|---|---|---|---| +| `303`, `310` | 400 | Request tidak lengkap / salah format | Bug di app; tampilkan pesan umum | +| `304` | 400 | Ditolak aturan bisnis | Tampilkan pesan yang ramah (lihat tiap fitur); `cause` berbahasa Inggris, jangan tampilkan mentah | +| `404` | 404 | Tidak ditemukan | Tampilkan "tidak ditemukan" | +| `429` | 429 | Minta OTP terlalu cepat | Tampilkan hitung mundur sebelum boleh minta lagi | +| `PIN_NOT_SET` | 403 | Belum punya PIN | Buka alur buat PIN (§6.2) | +| `PIN_INVALID` | 400 | PIN salah | §6.5 | +| `PIN_LOCKED` | 423 | PIN terkunci | §6.5 | +| `TRANSFER_BLOCKED` | 403 | Transfer ditahan setelah reset PIN | §6.5 | +| `900` | 500 | Error server | "Terjadi kesalahan, coba lagi" | + +### Idempotency-Key + +Endpoint **tukar** dan **transfer** wajib header `Idempotency-Key` (string unik, maks. +50 karakter, mis. UUID v4). + +- Buat **satu key baru saat customer menekan tombol konfirmasi**. +- Bila request gagal karena jaringan/timeout, **kirim ulang dengan key yang sama**. + Server mengembalikan hasil pertama dengan `"replayed": true` dan tidak memotong saldo + dua kali. +- Jangan pakai ulang key untuk transaksi yang berbeda; server menolaknya (`304`). + +--- + +## 3. Layar yang perlu dibuat + +| Layar | Endpoint utama | Butuh PIN | +|---|---|---| +| Beranda wallet | `GET /customer/wallet` | – | +| Riwayat mutasi | `GET /customer/wallet/transactions` | – | +| Saldo akan kedaluwarsa | `GET /customer/wallet/expiring` | – | +| Daftar outlet | `GET /customer/outlets` | – | +| Riwayat order + detail | `GET /customer/orders`, `GET /customer/orders/:id` | – | +| Kode bayar (angka + QR) | `POST /customer/wallet/payment-code` | Ya | +| Tukar EnakCoin | `GET …/exchange/preview`, `POST /customer/wallet/exchange` | Ya | +| Transfer | `GET …/transfer/recipient`, `POST /customer/wallet/transfer` | Ya | +| PIN (buat, ganti, lupa) | `/customer/pin/*` | – | +| Game | `POST /customer/spin` | – | +| (latar belakang) registrasi push | `PUT` / `DELETE /customer/devices` | – | + +--- + +## 4. Beranda wallet, riwayat, kedaluwarsa + +### 4.1 Beranda — `GET /customer/wallet` + +```json +{ + "point_balance": 12500, + "coin_balance": 8, + "point_value": 1, + "point_discount_value": 12500, + "nearest_expiring": { + "point": { "amount": 150, "date": "2026-12-31" }, + "coin": null + }, + "recent_transactions": [ /* sama dengan item riwayat §4.2, maksimal 5 */ ] +} +``` + +Tampilkan: +- Saldo EnakPoint (`point_balance`) dengan keterangan "setara potongan Rp + {point_discount_value}" (format ribuan Indonesia: `Rp 12.500`). +- Saldo EnakCoin (`coin_balance`). +- Bila `nearest_expiring.point` / `.coin` tidak `null`: banner "{amount} EnakPoint akan + kedaluwarsa pada {date}" yang membuka layar §4.3. +- 5 mutasi terakhir dari `recent_transactions`, dengan tautan "Lihat semua" ke §4.2. +- Tombol aksi: Bayar di kasir (§7.1), Tukar EnakCoin (§8.1), Transfer (§8.2), Main game (§9). + +Muat ulang beranda setelah setiap transaksi dan saat menerima push (§5). + +Field `total_points`, `points_history`, `last_updated` di response ini **deprecated**; +jangan dipakai. + +### 4.2 Riwayat — `GET /customer/wallet/transactions` + +Query (semua opsional): + +| Query | Contoh | Keterangan | +|---|---|---| +| `page` | `1` | Mulai dari 1 | +| `limit` | `20` | 1–100, default 20 | +| `currency` | `POINT` | `POINT` atau `COIN`; untuk tab EnakPoint / EnakCoin | +| `type` | `EARN,PAYMENT` | Satu atau beberapa tipe dipisah koma, untuk filter | +| `from`, `to` | `2026-09-01` | Tanggal WIB, inklusif | + +```json +{ + "data": [ + { + "id": "…", + "currency": "POINT", + "type": "EARN", + "amount": 875, + "balance_after": 12500, + "description": "Belanja #ORD-0123 di Outlet Kemang", + "source": { "type": "ORDER", "id": "…" }, + "outlet_id": "…", + "group_id": null, + "expires_at": "2026-12-31T23:59:59+07:00", + "lots": [{ "amount": 875, "remaining": 875, "expires_at": "2026-12-31T23:59:59+07:00" }], + "created_at": "2026-09-30T12:01:00Z" + } + ], + "pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 } +} +``` + +Aturan tampilan: +- `amount` bertanda: positif tampil hijau dengan `+`, negatif merah dengan `−`. +- `description` sudah siap tampil (nama lawan transfer sudah disamarkan). Tampilkan apa + adanya. +- Mutasi masuk yang punya `expires_at` menampilkan "Berlaku sampai {tanggal}". +- Infinite scroll memakai `pagination.total_pages`. +- Riwayat tidak pernah berubah atau hilang; koreksi muncul sebagai baris baru. + +Label tipe: + +| `type` | Label | Arah | +|---|---|---| +| `EARN` | Dari belanja | + | +| `EARN_REVERSAL` | Dibatalkan (order di-void/refund) | − | +| `PAYMENT` | Bayar pesanan | − | +| `PAYMENT_REFUND` | Pengembalian pembayaran | + | +| `EXCHANGE_OUT` | Ditukar ke EnakPoint | − | +| `EXCHANGE_IN` | Hasil tukar EnakCoin | + | +| `TRANSFER_OUT` | Transfer keluar | − | +| `TRANSFER_IN` | Transfer masuk | + | +| `GAME_SPEND` | Main game | − | +| `EXPIRE` | Kedaluwarsa | − | +| `ADJUSTMENT` | Koreksi | + / − | +| `MIGRATION` | Saldo awal | + | + +### 4.3 Akan kedaluwarsa — `GET /customer/wallet/expiring` + +```json +{ + "point": [ + { "amount": 150, "date": "2026-10-31" }, + { "amount": 200, "date": "2026-12-31" } + ], + "coin": [] +} +``` + +Daftar per tanggal, paling dekat di atas. Daftar kosong: tampilkan "Tidak ada saldo +yang akan kedaluwarsa". Saldo yang kedaluwarsa hangus tanpa kompensasi. + +--- + +### 4.4 Daftar outlet — `GET /customer/outlets` + +Outlet aktif di organisasi customer, tempat saldo EnakPoint & EnakCoin berlaku. Urut +berdasarkan nama. + +```json +[ + { + "id": "…", + "name": "Gokuna Kemang", + "address": "Jl. Kemang Raya 10", + "accepts_point_payment": true, + "earns_points": true, + "earns_coins": false + } +] +``` + +- `address` bisa `null`. +- `accepts_point_payment`: kasir di outlet ini menerima pembayaran EnakPoint. Pakai + untuk label "Bisa bayar pakai EnakPoint". +- `earns_points` / `earns_coins`: belanja di outlet ini memberi EnakPoint / EnakCoin. +- Belum ada telepon, koordinat, atau jam buka; data itu belum disimpan di backend. + + +### 4.5 Riwayat order — `GET /customer/orders` dan `GET /customer/orders/:id` + +Order milik customer yang login di semua outlet organisasinya, terbaru di atas. Order +hanya masuk ke sini bila kasir mengaitkannya ke customer. + +`GET /api/v1/customer/orders?page=1&limit=20` (`limit` 1–100, default 20): + +```json +{ + "data": [ + { + "id": "…", + "order_number": "ORD-0123", + "outlet_id": "…", + "outlet_name": "Gokuna 1", + "order_type": "dine_in", + "status": "completed", + "payment_status": "completed", + "total_amount": 99000, + "item_count": 2, + "is_void": false, + "is_refund": false, + "points_earned": 865, + "coins_earned": 3, + "created_at": "2026-09-30T12:01:00Z" + } + ], + "pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 } +} +``` + +`GET /api/v1/customer/orders/{id}` mengembalikan field yang sama, ditambah: + +```json +{ + "table_number": "A3", + "subtotal": 90000, + "discount_amount": 0, + "tax_amount": 9000, + "refund_amount": 0, + "items": [ + { + "id": "…", + "product_id": "…", + "product_name": "Kopi Susu", + "variant_name": "Large", + "quantity": 2, + "unit_price": 25000, + "total_price": 50000, + "refund_quantity": 0, + "modifiers": [], + "status": "completed" + }, + { + "id": "…", + "product_id": "…", + "product_name": "Ikan Tude", + "variant_name": null, + "quantity": 1, + "weight": 4.2, + "unit_name": "ons", + "unit_price": 4500, + "total_price": 18900, + "refund_quantity": 0, + "modifiers": [], + "status": "completed" + } + ], + "payments": [ + { "id": "…", "method_name": "EnakPoint", "method_type": "point", "amount": 12500, "status": "completed", "refund_amount": 0, "points_used": 12500, "point_value": 1, "created_at": "…" }, + { "id": "…", "method_name": "Cash", "method_type": "cash", "amount": 86500, "status": "completed", "refund_amount": 0, "created_at": "…" } + ] +} +``` + +- Order customer lain atau yang tidak ada → `404`. +- `points_earned` / `coins_earned`: yang didapat dari order ini; 0 bila tidak ada. +- Item timbangan membawa `weight` dan `unit_name`; tampilkan "1 × 4,2 ons". +- Pembayaran EnakPoint membawa `points_used`; tampilkan "EnakPoint 12.500 (Rp 12.500)". +- Order yang `is_void` atau `is_refund` tetap tampil, beri label "Dibatalkan" / + "Direfund". + + +## 5. Notifikasi push (FCM) + +### 5.1 Registrasi device + +Setelah login berhasil **dan** setiap kali FCM memberi token baru (`onTokenRefresh`): + +`PUT /api/v1/customer/devices` + +```json +{ "device_id": "", "fcm_token": "", "platform": "android", "app_version": "2.4.0" } +``` + +- `device_id` wajib, stabil untuk satu instalasi (simpan di secure storage). +- `platform`: `android`, `ios`, atau `web`. +- Saat **logout**, panggil `DELETE /api/v1/customer/devices/{device_id}` sebelum + menghapus token login, supaya HP itu tidak lagi menerima notifikasi akun ini. + +Tanpa registrasi ini, customer tidak menerima push apa pun. + +### 5.2 Tipe push + +Semua nilai di `data` berupa string. + +| `data.type` | Kapan | Isi `data` lain | Aksi saat di-tap | +|---|---|---|---| +| `WALLET_TRANSFER_IN` | Menerima transfer | `transaction_id`, `group_id`, `currency`, `amount` | Buka riwayat, sorot transaksi itu | +| `WALLET_EXPIRING` | Beberapa hari sebelum saldo hangus | `currency`, `amount`, `expiry_date` | Buka layar kedaluwarsa (§4.3) | +| `WALLET_EXPIRED` | Saldo baru saja hangus | `currency`, `amount` | Buka riwayat | +| `PIN_LOCKED` | PIN terkunci setelah 5 kali salah | `locked_until` (RFC3339 UTC) | Buka layar lupa PIN (§6.4) | + +Saat app terbuka dan menerima push wallet, muat ulang beranda. + +--- + +## 6. PIN + +### 6.1 Kapan diminta + +Jangan minta PIN saat registrasi. Minta saat customer **pertama kali** melakukan aksi +yang butuh PIN. Cek dengan: + +`GET /api/v1/customer/pin/status` → `{ "has_pin": false, "locked_until": null, "transfer_blocked_until": null }` + +Bila `has_pin: false`, arahkan ke alur buat PIN, lalu kembali ke aksi semula. + +### 6.2 Buat PIN + +1. `POST /api/v1/customer/pin/otp` dengan `{ "purpose": "pin_setup" }`. + Response: `{ "purpose": "pin_setup", "otp_token": "…", "expires_at": "…" }`. + OTP dikirim ke WhatsApp customer. +2. Customer memasukkan kode OTP, lalu PIN dua kali. +3. `POST /api/v1/customer/pin` dengan + `{ "otp_token": "…", "otp_code": "123456", "pin": "482913", "confirm_pin": "482913" }`. + Response: status PIN. + +Validasi di app sebelum kirim (server juga memeriksa, jawab `304`): +- Tepat 6 digit angka, dan konfirmasi sama. +- Bukan satu digit berulang (`111111`). +- Bukan berurutan naik/turun (`123456`, `654321`). +- Bukan tanggal lahir customer (`DDMMYY` atau `YYMMDD`). + +Minta OTP lagi terlalu cepat → `429`: tampilkan hitung mundur. + +### 6.3 Ganti PIN + +`PUT /api/v1/customer/pin` dengan `{ "old_pin": "…", "pin": "…", "confirm_pin": "…" }`. + +### 6.4 Lupa PIN + +1. `POST /customer/pin/otp` dengan `{ "purpose": "pin_reset" }`. +2. `POST /customer/pin/reset` dengan `{ "otp_token", "otp_code", "pin", "confirm_pin" }`. + +Reset juga membuka PIN yang terkunci. Setelah reset, **transfer keluar ditahan 24 jam**; +bayar dan tukar tetap bisa. Beri tahu customer hal ini di layar sukses. + +### 6.5 Menangani error PIN + +Semua endpoint yang menerima `pin` bisa menjawab error PIN. Pada error ini **`data` +tidak `null`**: + +```json +{ "success": false, "data": { "code": "PIN_INVALID", "remaining_attempts": 3 }, "errors": [ … ] } +``` + +| `data.code` | Field tambahan | Tampilan | +|---|---|---| +| `PIN_NOT_SET` | – | Buka alur buat PIN (§6.2) | +| `PIN_INVALID` | `remaining_attempts` | "PIN salah, sisa {n} percobaan." Kosongkan input PIN | +| `PIN_LOCKED` | `locked_until` | "PIN terkunci sampai {jam}." Tombol "Lupa PIN" | +| `TRANSFER_BLOCKED` | `transfer_blocked_until` | "Transfer bisa dilakukan lagi pada {waktu}." | + +5 kali salah berturut-turut mengunci PIN 30 menit; selama terkunci PIN yang benar pun +ditolak. Penghitung ada di server, jadi jangan membuat penghitung sendiri di app. + +--- + +## 7. Membayar dengan EnakPoint + +App customer tidak membuat atau membayar order; order hanya bisa dilihat (§4.5). +EnakPoint hanya dipakai membayar di kasir, lewat kode bayar dari app. Jangan membangun +layar checkout atau memanggil `POST /customer/orders/:id/pay-with-points`. + +### 7.1 Di kasir — kode bayar + +Customer tidak pernah mengetik PIN di mesin kasir. Alurnya: + +1. Customer membuka "Bayar di kasir" dan memasukkan PIN. +2. `POST /api/v1/customer/wallet/payment-code` dengan `{ "pin": "482913" }`: + + ```json + { "code": "482913", "qr_payload": "enakpoint:482913", "expires_at": "2026-09-30T05:02:00Z" } + ``` + +3. Tampilkan `code` besar (angka) **dan** QR dari `qr_payload` (string apa adanya). +4. Tampilkan hitung mundur ke `expires_at` (2 menit). Setelah habis, sembunyikan kode + dan tampilkan tombol "Buat kode baru". +5. Kasir memindai/mengetik kode dan memilih jumlah EnakPoint. App tidak menerima + callback; setelah customer kembali ke beranda, muat ulang saldo. + +Kode sekali pakai. Membuat kode baru membatalkan kode lama. + +### 7.2 Refund + +Bila order yang dibayar EnakPoint dibatalkan atau direfund, EnakPoint kembali sebagai +EnakPoint (tidak pernah tunai) dan muncul di riwayat sebagai `PAYMENT_REFUND`. + +--- + +## 8. Tukar dan transfer + +### 8.1 Tukar EnakCoin → EnakPoint + +1. Customer mengetik jumlah EnakCoin. Panggil preview (debounce saat mengetik): + + `GET /api/v1/customer/wallet/exchange/preview?coins=30` + + ```json + { "coin_amount": 10, "point_amount": 3, "coin_balance": 35, "coins": 30, "points": 9, "valid": true } + ``` + + - Kurs: `coin_amount` EnakCoin = `point_amount` EnakPoint. Tampilkan "10 EnakCoin = + 3 EnakPoint". + - Bila `valid: false`, tampilkan `reason` sebagai alasan dan nonaktifkan tombol. Jumlah + harus kelipatan `coin_amount`. + - Tampilkan "Kamu akan mendapat {points} EnakPoint". + +2. Konfirmasi (tukar tidak bisa dibatalkan) → minta PIN → + + `POST /api/v1/customer/wallet/exchange` + header `Idempotency-Key` + + ```json + { "coins": 30, "pin": "482913" } + ``` + + ```json + { + "group_id": "…", + "coins": 30, + "points": 9, + "coin_amount": 10, + "point_amount": 3, + "lots": [{ "amount": 9, "expires_at": "2026-12-31T23:59:59+07:00" }], + "coin_balance": 5, + "point_balance": 9, + "replayed": false + } + ``` + +3. Layar sukses: saldo baru, dan bila `lots[].expires_at` ada, "EnakPoint ini berlaku + sampai {tanggal}". + +### 8.2 Transfer + +1. Pilih mata uang (EnakPoint / EnakCoin), isi nomor HP penerima dan jumlah. +2. Cek penerima: + + `GET /api/v1/customer/wallet/transfer/recipient?phone=081234561234` + + ```json + { "name": "Bu*** Sa***", "phone_number": "08**-****-1234" } + ``` + + | Hasil | Tampilan | + |---|---| + | Sukses | "Kirim ke Bu*** Sa*** (08**-****-1234)?" | + | `404` | "Nomor ini tidak terdaftar" | + | `304` | "Tidak bisa mengirim ke nomor ini" (diri sendiri, akun nonaktif) | + +3. Konfirmasi (transfer final, tidak bisa dibatalkan) → minta PIN → + + `POST /api/v1/customer/wallet/transfer` + header `Idempotency-Key` + + ```json + { "currency": "POINT", "amount": 120, "recipient_phone": "081234561234", "pin": "482913" } + ``` + + ```json + { + "group_id": "…", + "currency": "POINT", + "amount": 120, + "recipient": { "name": "Bu*** Sa***", "phone_number": "08**-****-1234" }, + "lots": [ + { "amount": 100, "expires_at": "2026-12-31T23:59:59+07:00" }, + { "amount": 20, "expires_at": null } + ], + "balance": 30, + "replayed": false + } + ``` + +4. Layar sukses: saldo tersisa (`balance`). Bila ada `lots[].expires_at`, tampilkan + "Saldo yang dikirim berlaku sampai {tanggal}" (tanggal kedaluwarsa ikut terbawa ke + penerima). + +Penolakan `304` yang mungkin: transfer dimatikan owner, di bawah minimal, di atas +maksimal per transaksi, melewati batas harian (reset tengah malam WIB), saldo tidak +cukup. Tampilkan pesan umum "Transfer tidak bisa diproses" plus alasan yang sesuai +bila bisa dikenali. Bila kena `TRANSFER_BLOCKED`, ikuti §6.5. + +Penerima mendapat push `WALLET_TRANSFER_IN`. + +--- + +## 9. Game (memakai EnakCoin) + +`POST /api/v1/customer/spin` dengan `{ "spin_id": "" }`. Tanpa PIN. + +```json +{ + "game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" }, + "prize_won": { "id": "…", "name": "Voucher 10rb" }, + "coins_remaining": 7 +} +``` + +- Setiap game punya biaya sendiri: `metadata.coin_cost` pada data game dari + `GET /api/v1/customer/games` (atau `GET /customer/ferris-wheel`), default 1 bila kosong. + Tampilkan biaya sebelum main, dan nonaktifkan tombol bila `coin_balance` kurang. +- `304`: EnakCoin kurang, game nonaktif, atau hadiah baru saja habis. Tidak ada + EnakCoin yang terpotong; tampilkan pesan dan biarkan customer mencoba lagi. +- Setelah main, perbarui saldo EnakCoin dari `coins_remaining`. + +--- + +## 10. Yang sudah dihapus / deprecated + +Sudah **dihapus** dari API (jangan dipanggil, akan error / tidak ada): + +| Lama | Pengganti | +|---|---| +| `GET /customer/tokens` | `GET /customer/wallet` → `coin_balance` | +| `total_tokens`, `tokens_history` | `coin_balance`, `GET /customer/wallet/transactions?currency=COIN` | +| `token_used`, `tokens_remaining` di response game | `coins_used`, `coins_remaining` | + +Masih ada tapi **deprecated** (akan dihapus, jangan dipakai di kode baru): + +| Lama | Pengganti | +|---|---| +| `GET /customer/points` | `GET /customer/wallet` → `point_balance` | +| `total_points`, `points_history`, `last_updated` di `/customer/wallet` | `point_balance`, `recent_transactions` | + +--- + +## 11. Checklist selesai + +- [ ] Beranda menampilkan saldo EnakPoint ("setara potongan Rp …"), EnakCoin, dan banner kedaluwarsa terdekat. +- [ ] Riwayat dengan tab per mata uang, filter tipe/tanggal, infinite scroll, label tipe sesuai §4.2. +- [ ] Layar saldo akan kedaluwarsa. +- [ ] Registrasi device FCM setelah login dan saat token berganti; unregister saat logout. +- [ ] Penanganan tap untuk keempat tipe push. +- [ ] PIN diminta hanya saat aksi yang membutuhkan; alur buat, ganti, dan lupa PIN lewat OTP. +- [ ] Keempat error PIN ditangani di semua layar yang meminta PIN. +- [ ] Kode bayar: angka + QR, hitung mundur 2 menit, tombol buat ulang. +- [ ] Tukar dengan preview, kelipatan kurs, konfirmasi, `Idempotency-Key`, retry dengan key sama. +- [ ] Transfer dengan cek penerima tersamar, konfirmasi, `Idempotency-Key`, retry dengan key sama. +- [ ] Game memakai `coins_used` / `coins_remaining` dan menampilkan biaya per game. +- [ ] Riwayat order dengan pagination dan layar detail (item, pembayaran, EnakPoint/EnakCoin yang didapat). +- [ ] Tidak ada pemakaian endpoint atau field di §10. +- [ ] PIN tidak pernah disimpan, di-log, atau dikirim ke analytics. -- 2.54.0 From c9654a387a2a447d022393af84a16cdadfff41e7 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 22:59:44 +0700 Subject: [PATCH 06/12] fix(migrations): keep every payment method type in use Production allows edc and delivery payment methods through a payment_methods_type_check changed outside the migrations, and has rows of both. 000094 rewrote the constraint with only cash, card, digital_wallet and point, so it failed on production (in its transaction, leaving the database dirty at 94 with nothing applied). 000094 now keeps edc and delivery, down included, and also allows qr, which the code accepts but no constraint did. 000098 sets the same list where the old 000094 already ran, as on staging. Co-Authored-By: Claude Opus 5.5 --- migrations/000094_add_point_payment_method.down.sql | 2 +- migrations/000094_add_point_payment_method.up.sql | 5 +++-- .../000098_allow_edc_delivery_payment_methods.down.sql | 2 ++ .../000098_allow_edc_delivery_payment_methods.up.sql | 7 +++++++ 4 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 migrations/000098_allow_edc_delivery_payment_methods.down.sql create mode 100644 migrations/000098_allow_edc_delivery_payment_methods.up.sql diff --git a/migrations/000094_add_point_payment_method.down.sql b/migrations/000094_add_point_payment_method.down.sql index dd86218..4bffcee 100644 --- a/migrations/000094_add_point_payment_method.down.sql +++ b/migrations/000094_add_point_payment_method.down.sql @@ -13,4 +13,4 @@ DROP INDEX IF EXISTS uq_payment_methods_point_per_organization; ALTER TABLE payment_methods DROP CONSTRAINT IF EXISTS payment_methods_type_check; ALTER TABLE payment_methods ADD CONSTRAINT payment_methods_type_check - CHECK (type IN ('cash', 'card', 'digital_wallet')); + CHECK (type IN ('cash', 'card', 'digital_wallet', 'qr', 'edc', 'delivery')); diff --git a/migrations/000094_add_point_payment_method.up.sql b/migrations/000094_add_point_payment_method.up.sql index e39899e..eab3509 100644 --- a/migrations/000094_add_point_payment_method.up.sql +++ b/migrations/000094_add_point_payment_method.up.sql @@ -1,10 +1,11 @@ -- Paying with EnakPoint (docs/prd-point-coin.md F9, §8, §10.5). --- A new payment method type. Every organization has exactly one method of it, made by +-- A new payment method type, next to the existing ones (edc and delivery were added to +-- the constraint outside the migrations). Every organization has exactly one method of it, made by -- the system, which cannot be deleted or change type. ALTER TABLE payment_methods DROP CONSTRAINT IF EXISTS payment_methods_type_check; ALTER TABLE payment_methods ADD CONSTRAINT payment_methods_type_check - CHECK (type IN ('cash', 'card', 'digital_wallet', 'point')); + CHECK (type IN ('cash', 'card', 'digital_wallet', 'qr', 'edc', 'delivery', 'point')); CREATE UNIQUE INDEX uq_payment_methods_point_per_organization ON payment_methods(organization_id) WHERE type = 'point'; diff --git a/migrations/000098_allow_edc_delivery_payment_methods.down.sql b/migrations/000098_allow_edc_delivery_payment_methods.down.sql new file mode 100644 index 0000000..d3eedb5 --- /dev/null +++ b/migrations/000098_allow_edc_delivery_payment_methods.down.sql @@ -0,0 +1,2 @@ +-- Nothing to undo: 000094 now allows the same types. +SELECT 1; diff --git a/migrations/000098_allow_edc_delivery_payment_methods.up.sql b/migrations/000098_allow_edc_delivery_payment_methods.up.sql new file mode 100644 index 0000000..c831678 --- /dev/null +++ b/migrations/000098_allow_edc_delivery_payment_methods.up.sql @@ -0,0 +1,7 @@ +-- Production also has edc and delivery payment methods, allowed by a constraint changed +-- outside the migrations, and the code also accepts qr, which no constraint allowed. +-- 000094 first rewrote the constraint without them, which +-- failed on production and, where it ran, dropped them. Keep every type in use. +ALTER TABLE payment_methods DROP CONSTRAINT IF EXISTS payment_methods_type_check; +ALTER TABLE payment_methods ADD CONSTRAINT payment_methods_type_check + CHECK (type IN ('cash', 'card', 'digital_wallet', 'qr', 'edc', 'delivery', 'point')); -- 2.54.0 From 892575202b26afd3e5f01d5e9ca205425ec005e2 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 23:29:17 +0700 Subject: [PATCH 07/12] fix(orders): keep the customer a new order is created for CreateOrderContractToModel never copied customer_id, so every order from POST /orders was saved without a customer. Paying it then earned no EnakPoint or EnakCoin (skipped as NO_CUSTOMER, which is not logged). The customer must now belong to the order's organization, as SetOrderCustomer already requires: it is who earns once the order is paid, and orders.customer_id has no foreign key. A nil UUID means no customer. Co-Authored-By: Claude Opus 5.5 --- internal/processor/order_processor.go | 14 +++++++++++++- internal/transformer/order_transformer.go | 1 + internal/transformer/order_transformer_test.go | 14 ++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/internal/processor/order_processor.go b/internal/processor/order_processor.go index bea796c..60ad0f4 100644 --- a/internal/processor/order_processor.go +++ b/internal/processor/order_processor.go @@ -316,6 +316,18 @@ func resolveLineQuantity(product *entities.Product, quantity int, weight *float6 } func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.CreateOrderRequest, organizationID uuid.UUID) (*models.OrderResponse, error) { + // The order's customer earns EnakPoint and EnakCoin once it is paid, so it must be + // one of the organization's own; orders.customer_id has no foreign key to catch it. + customerID := req.CustomerID + if customerID != nil && *customerID == uuid.Nil { + customerID = nil + } + if customerID != nil { + if _, err := p.customerRepo.GetByIDAndOrganization(ctx, *customerID, organizationID); err != nil { + return nil, fmt.Errorf("customer not found or does not belong to the organization: %w", err) + } + } + orderNumber, err := p.orderRepo.GetNextOrderNumber(ctx, organizationID, req.OutletID) if err != nil { return nil, fmt.Errorf("failed to generate order number: %w", err) @@ -401,7 +413,7 @@ func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.Create OrganizationID: organizationID, OutletID: req.OutletID, UserID: req.UserID, - CustomerID: req.CustomerID, + CustomerID: customerID, OrderNumber: orderNumber, TableNumber: req.TableNumber, OrderType: entities.OrderType(req.OrderType), diff --git a/internal/transformer/order_transformer.go b/internal/transformer/order_transformer.go index 5bd19ba..2ed1194 100644 --- a/internal/transformer/order_transformer.go +++ b/internal/transformer/order_transformer.go @@ -27,6 +27,7 @@ func CreateOrderContractToModel(req *contract.CreateOrderRequest) *models.Create return &models.CreateOrderRequest{ OutletID: req.OutletID, UserID: req.UserID, + CustomerID: req.CustomerID, TableID: req.TableID, TableNumber: req.TableNumber, OrderType: constants.OrderType(req.OrderType), diff --git a/internal/transformer/order_transformer_test.go b/internal/transformer/order_transformer_test.go index 5c55afd..4c6fcde 100644 --- a/internal/transformer/order_transformer_test.go +++ b/internal/transformer/order_transformer_test.go @@ -32,6 +32,20 @@ func TestCreateOrderContractToModelCarriesWeight(t *testing.T) { require.Equal(t, weight, *result.OrderItems[0].Weight) } +func TestCreateOrderContractToModelCarriesCustomer(t *testing.T) { + customerID := uuid.New() + + result := CreateOrderContractToModel(&contract.CreateOrderRequest{ + OutletID: uuid.New(), + UserID: uuid.New(), + CustomerID: &customerID, + OrderItems: []contract.CreateOrderItemRequest{{ProductID: uuid.New(), Quantity: 1}}, + }) + + require.NotNil(t, result.CustomerID, "the order's customer is who earns EnakPoint and EnakCoin") + require.Equal(t, customerID, *result.CustomerID) +} + func TestAddToOrderContractToModelCarriesWeight(t *testing.T) { weight := 0.8 -- 2.54.0 From b0ef226af1ef865d017df34eb18c7f3a0e57f4c7 Mon Sep 17 00:00:00 2001 From: efrilm Date: Thu, 1 Oct 2026 22:26:44 +0700 Subject: [PATCH 08/12] feat: add printer types --- docs/migrasi-printer-types.md | 143 +++ docs/prd-point-coin.md | 1038 +++++++++++++++++ docs/tasks-point-coin.md | 438 +++++++ internal/contract/order_contract.go | 2 +- internal/contract/product_contract.go | 6 +- internal/entities/product.go | 65 +- internal/mappers/order_mapper.go | 2 +- internal/mappers/product_mapper.go | 25 +- .../product_mapper_printer_types_test.go | 102 ++ internal/models/order.go | 2 +- internal/models/product.go | 8 +- internal/processor/order_add_items_test.go | 46 + internal/processor/order_processor.go | 30 +- .../processor/product_recipe_processor.go | 2 +- .../product_ingredient_repository.go | 12 +- .../product_repository_printer_types_test.go | 48 + internal/transformer/inventory_transformer.go | 5 +- internal/transformer/order_transformer.go | 3 +- .../order_transformer_printer_types_test.go | 50 + internal/transformer/product_transformer.go | 6 +- internal/validator/product_validator.go | 22 +- .../product_validator_printer_types_test.go | 35 + ...099_add_printer_types_to_products.down.sql | 8 + ...00099_add_printer_types_to_products.up.sql | 12 + postman.json | 4 +- 25 files changed, 2048 insertions(+), 66 deletions(-) create mode 100644 docs/migrasi-printer-types.md create mode 100644 docs/prd-point-coin.md create mode 100644 docs/tasks-point-coin.md create mode 100644 internal/mappers/product_mapper_printer_types_test.go create mode 100644 internal/processor/order_add_items_test.go create mode 100644 internal/repository/product_repository_printer_types_test.go create mode 100644 internal/transformer/order_transformer_printer_types_test.go create mode 100644 internal/validator/product_validator_printer_types_test.go create mode 100644 migrations/000099_add_printer_types_to_products.down.sql create mode 100644 migrations/000099_add_printer_types_to_products.up.sql diff --git a/docs/migrasi-printer-types.md b/docs/migrasi-printer-types.md new file mode 100644 index 0000000..48b2683 --- /dev/null +++ b/docs/migrasi-printer-types.md @@ -0,0 +1,143 @@ +# Migrasi printer_type ke printer_types + +1 Oktober 2026 + +## Ringkasan + +`printer_type` (string) dihapus dan diganti `printer_types` (array string), sehingga satu produk bisa dicetak ke lebih dari satu printer. Contohnya "Paket Makan Minum" dengan `["kitchen", "bar"]` tercetak di kitchen dan bar sekaligus. + +Ini breaking change. Setelah backend baru dirilis, client yang masih membaca `printer_type` tidak menerima printer apa pun. Karena itu app POS dan dashboard harus diupdate lebih dulu, lihat [Urutan rilis](#database-dan-urutan-rilis). + +Yang perlu bertindak: + +- **App POS**: baca `printer_types` dan cetak tiap item ke semua printer di dalamnya. +- **Dashboard admin**: ganti pilihan printer di form produk jadi multi-select yang mengirim `printer_types`. + +## Perubahan response + +`printer_type` hilang dari semua response dan digantikan `printer_types`, yang nilainya selalu array dan tidak pernah `null`. + +| Endpoint | Letak field | +| --- | --- | +| `POST /api/v1/products`, `PUT /api/v1/products/:id`, `GET /api/v1/products`, `GET /api/v1/products/all`, `GET /api/v1/products/:id` | objek produk | +| `POST /api/v1/orders`, `GET /api/v1/orders`, `GET /api/v1/orders/:id`, `PUT /api/v1/orders/:id` | `order_items[]` | +| `POST /api/v1/orders/:id/add-items` | `added_items[]` dan `updated_order.order_items[]` | +| `POST /api/v1/self-order/orders`, `GET /api/v1/self-order/orders/:session_id` | `order_items[]` | +| `/api/v1/product-recipes` (semua yang mengembalikan recipe) | `product` | +| `/api/v1/inventory` | `product`, selalu `[]` karena produk di sini hanya berisi id dan nama | + +Contoh satu item di `order_items[]`: + +```json +{ + "product_name": "Paket Makan Minum", + "printer_types": ["kitchen", "bar"], + "print_to_checker": true +} +``` + +Aturan nilainya: + +- `printer_types: []` artinya produk tidak dicetak ke printer mana pun. +- Urutan printer sesuai yang disimpan admin, tanpa duplikat. +- Void, refund, payment, split bill, dan set customer tidak membawa data printer, sama seperti sebelumnya. + +## Perubahan request produk + +`POST /api/v1/products` dan `PUT /api/v1/products/:id` menerima `printer_types` sebagai pengganti `printer_type`. Kalau `printer_type` masih dikirim, field itu diabaikan tanpa error. + +```json +{ + "name": "Paket Makan Minum", + "category_id": "", + "price": 25000, + "printer_types": ["kitchen", "bar"] +} +``` + +| Request | `printer_types` yang dikirim | Hasil | +| --- | --- | --- | +| Create | tidak dikirim | `["kitchen"]` | +| Create | `["kitchen", "bar"]` | `["kitchen", "bar"]` | +| Create | `[]` atau hanya string kosong | `["kitchen"]` | +| Update | tidak dikirim | tidak berubah | +| Update | `["bar"]` | `["bar"]`, seluruh daftar diganti | +| Update | `[]` | `[]`, produk tidak dicetak ke mana pun | + +Sebelum disimpan, spasi di awal dan akhir tiap entri dibuang, lalu entri kosong dan duplikat dihapus. Urutan dipertahankan. + +Tiap entri maksimal 50 karakter. Kalau lebih, request ditolak dengan error code `310` dan pesan `each printer_types entry cannot exceed 50 characters`. + +## Migrasi app POS + +App POS harus mengirim tiap item ke semua printer di `printer_types`, sehingga satu item bisa muncul di lebih dari satu tiket. + +1. Ganti `printer_type` dengan `printer_types` (list string) di model order item dan produk. +2. Selama backend lama masih jalan, `printer_types` belum ada di response. Pakai `[printer_type]` kalau `printer_types` tidak ada, supaya app baru bisa dirilis sebelum backend. +3. Saat mencetak, kelompokkan item per printer dengan mengulang setiap entri `printer_types` milik item. +4. Item dengan `printer_types: []` tidak dicetak ke printer station mana pun. +5. `print_to_checker` tidak berubah dan tetap diperlakukan terpisah. +6. Untuk tambahan pesanan dari `POST /api/v1/orders/:id/add-items`, cetak dari `added_items[]`. + +```text +tiket = {} +untuk setiap item di order_items: + printers = item.printer_types ?? [item.printer_type] // fallback hanya untuk backend lama + untuk setiap printer di printers: + tiket[printer].tambah(item) +untuk setiap (printer, items) di tiket: + cetak items ke printer +``` + +Perbaikan di `added_items[]`: sebelumnya field ini selalu berisi `product_name` dan printer kosong, serta `print_to_checker: true`. Sekarang isinya lengkap seperti item di `updated_order.order_items[]`, dengan urutan sesuai request. Kalau app selama ini mengakali dengan mencari item baru di `updated_order`, cara itu bisa diganti dengan `added_items[]` langsung. + +## Migrasi dashboard + +Form produk di dashboard harus memakai multi-select printer dan selalu mengirim daftar lengkapnya lewat `printer_types`. + +1. Ganti dropdown printer tunggal dengan multi-select, misalnya checkbox, berisi pilihan printer yang sama. +2. Saat membuka form edit, isi pilihan dari `printer_types`. Selama backend lama masih jalan, pakai `[printer_type]` kalau `printer_types` tidak ada. +3. Saat menyimpan, kirim `printer_types` berisi semua printer yang dipilih. +4. Selama backend lama masih jalan, kirim juga `printer_type` berisi printer pertama. Backend lama hanya membaca `printer_type`, dan backend baru mengabaikannya. +5. Di daftar produk, tampilkan semua printer dari `printer_types`. + +Backend tidak membatasi nilai printer. Nilainya harus sama persis dengan nama printer yang dikenal app POS, termasuk huruf besar dan kecilnya. + +Create dengan `printer_types: []` tetap menghasilkan `["kitchen"]`. Produk tanpa printer dibuat dulu, lalu di-update dengan `printer_types: []`. + +## Database dan urutan rilis + +Migration `000099_add_printer_types_to_products` menambah kolom `products.printer_types` (JSONB, `NOT NULL`, default `["kitchen"]`), mengisinya dari `printer_type`, lalu menghapus kolom `printer_type` beserta index-nya. + +- Produk dengan `printer_type` berisi nilai menjadi `[printer_type]`. +- Produk dengan `printer_type` `NULL` atau kosong menjadi `[]`. + +Urutan rilis: + +1. Rilis app POS baru, yang membaca `printer_types` dengan fallback ke `printer_type`, ke semua outlet. +2. Rilis dashboard baru, yang mengirim `printer_types` dan `printer_type`. +3. Jalankan migration `000099` tepat sebelum deploy backend baru. Di antara keduanya, backend lama gagal menyimpan produk karena kolom `printer_type` sudah tidak ada. +4. Setelah backend baru jalan, dashboard boleh berhenti mengirim `printer_type`, dan fallback di app POS boleh dihapus. +5. Atur produk multi-printer, misalnya "Paket Makan Minum" ke `["kitchen", "bar"]`. + +Outlet yang masih memakai app POS lama setelah langkah 3 tidak menerima printer untuk semua item. Pastikan langkah 1 sudah selesai di semua outlet. + +Rollback: jalankan down migration dan deploy backend lama bersamaan. Down migration membuat ulang kolom `printer_type` berisi printer pertama, lalu menghapus `printer_types`, jadi yang hilang hanya printer tambahan. + +## Checklist + +- [ ] App POS baru (dengan fallback) terpasang di semua outlet +- [ ] Dashboard baru mengirim `printer_types` dan `printer_type` +- [ ] Migration `000099` dan backend baru dirilis di staging +- [ ] Uji "Paket Makan Minum" dengan `["kitchen", "bar"]` tercetak di dua printer, saat order baru dan saat tambah pesanan +- [ ] Migration `000099` dan backend baru dirilis di production +- [ ] Dashboard berhenti mengirim `printer_type` +- [ ] Fallback `printer_type` di app POS dihapus + +## FAQ + +**Kenapa `printer_type` dihapus, bukan dipertahankan?** Supaya hanya ada satu sumber data printer. Dua field yang menyimpan hal yang sama bisa saling berbeda. + +**Apakah kitchen dan bar menerima tiket yang sama?** Ya. Keduanya mencetak "Paket Makan Minum" lengkap dengan varian dan modifier-nya. Memecah isi paket per station butuh fitur bundle, yang di luar rilis ini. + +**Apakah nilai printer dibatasi?** Tidak. Nilainya string bebas sampai 50 karakter, dan harus sama dengan nama printer di app POS. diff --git a/docs/prd-point-coin.md b/docs/prd-point-coin.md new file mode 100644 index 0000000..5af5fbd --- /dev/null +++ b/docs/prd-point-coin.md @@ -0,0 +1,1038 @@ +# PRD: EnakPoint & EnakCoin + +**Status:** Draft +**Tanggal:** 2026-09-29 +**Scope:** Wallet customer (EnakPoint & EnakCoin), earning dari order, pembayaran order +dengan EnakPoint, exchange EnakCoin → EnakPoint, transfer antar customer, kedaluwarsa +saldo, PIN customer, pengaturan per outlet dan per organisasi, migrasi dari Token +**Out of scope:** Penukaran reward, tier otomatis, eksekusi campaign rules (lihat §11) + +--- + +## 1. Latar Belakang + +Sistem saat ini punya dua saldo customer: **Point** (`customer_points`) dan **Token** +(`customer_tokens`, per jenis `SPIN` / `RAFFLE` / `MINIGAME`). Keduanya baru sebatas +tabel dan endpoint baca: + +- Tidak ada jalur yang menambah saldo. Order selesai tidak menghasilkan apa pun. +- `AddPoints` / `DeductPoints` masih `not implemented`. +- Tidak ada riwayat transaksi. "History" di `/customer/points` sebenarnya adalah baris + saldo itu sendiri. +- Token hanya dipakai untuk spin game, dan pemotongannya tidak atomik (repository tidak + memakai `DBFromContext`, jumlah baris ter-update tidak dicek). +- Point belum bisa dipakai untuk apa pun, termasuk membayar. + +PRD ini mendefinisikan ulang saldo customer menjadi **EnakPoint** dan **EnakCoin**, +lengkap dengan cara mendapatkannya, memakainya, memindahkannya, masa berlakunya, dan +jejak auditnya. + +--- + +## 2. Tujuan + +1. Customer mendapat EnakPoint dan EnakCoin otomatis dari order yang lunas, dengan + besaran yang diatur **per outlet**. +2. Customer bisa **membayar order dengan EnakPoint**, penuh atau sebagian. EnakCoin + tidak bisa dipakai membayar. +3. Customer bisa menukar EnakCoin ke EnakPoint, satu arah, dengan kurs yang bisa diatur + (default **1 EnakCoin = 1 EnakPoint**). +4. Customer bisa mentransfer EnakPoint dan EnakCoin ke customer lain. +5. EnakPoint dan EnakCoin bisa **kedaluwarsa**, dengan masa berlaku yang diatur sendiri + oleh owner. +6. Setiap perubahan saldo tercatat di ledger, lengkap dengan asal dan tujuannya + **sampai ke tiap butir**, dan bisa diaudit serta direkonsiliasi dengan saldo. + +### Bukan tujuan + +- Menukar EnakPoint ke EnakCoin. Exchange hanya satu arah. +- Membayar dengan EnakCoin. +- Menunaikan EnakPoint/EnakCoin dalam bentuk apa pun (lihat K7). Ini larangan, bukan + fitur yang ditunda. + +--- + +## 3. Istilah + +| Istilah | Kode | Arti | +|---|---|---| +| **EnakPoint** | `POINT` | Saldo yang bernilai rupiah. Satu-satunya saldo yang bisa dipakai membayar order. | +| **EnakCoin** | `COIN` | Pengganti Token. **Mata uang untuk bermain game** (spin, ferris wheel, raffle, minigame, dan game berikutnya). Bisa ditukar ke EnakPoint. **Tidak bisa** dipakai membayar. | +| **Wallet** | – | Saldo EnakPoint dan EnakCoin milik satu customer. | +| **Ledger** | – | Catatan setiap mutasi saldo. Saldo wallet = jumlah seluruh mutasi di ledger. | +| **Lot** | `wallet_lots` | Satu "paket" saldo yang masuk bersamaan, dengan asal dan tanggal kedaluwarsa sendiri. Saldo wallet = jumlah sisa semua lot. | +| **Nilai EnakPoint** | `point_value` | Nilai rupiah dari 1 EnakPoint saat dipakai membayar. Default Rp 1. | +| **Kurs exchange** | – | Berapa EnakCoin ditukar menjadi berapa EnakPoint. Default 1 : 1. | +| **Basis earning** | – | Nominal order yang dipakai untuk menghitung EnakPoint/EnakCoin yang didapat. | + +Di dokumen ini, "Point" dan "Coin" adalah singkatan dari EnakPoint dan EnakCoin. + +--- + +## 4. Keputusan Inti + +**K1 — Token diganti EnakCoin, dan EnakCoin hanya satu jenis.** +Jenis `SPIN` / `RAFFLE` / `MINIGAME` dihapus. **Semua game memakai EnakCoin yang +sama**. Tidak ada lagi saldo terpisah per jenis game, dan game baru tidak menambah jenis +saldo baru. Biaya main diatur per game (F8). + +**K2 — Hanya EnakPoint yang bisa dipakai membayar.** +EnakPoint didaftarkan sebagai payment method, sejajar dengan cash, kartu, dan e-wallet. +EnakCoin tidak punya payment method, dan ledger menolak mutasi pembayaran bercurrency +`COIN` di level database (§8). Customer yang ingin memakai EnakCoin untuk belanja harus +menukarnya dulu ke EnakPoint (F4). + +**K3 — Exchange hanya EnakCoin → EnakPoint. Kurs bisa diatur, default 1 : 1.** +Kurs diatur per organisasi (F2) dalam bentuk bilangan bulat "X EnakCoin = Y EnakPoint", +dengan default 1 : 1. Mengubah kurs langsung mengubah nilai seluruh EnakCoin yang +beredar, jadi perubahan kurs berlaku ke depan saja, kurs yang dipakai dibekukan di +setiap exchange, dan setiap perubahan tercatat (F2). + +> **Implikasi.** Karena EnakCoin bisa menjadi EnakPoint, dan EnakPoint bernilai +> rupiah, maka **setiap EnakCoin yang diberikan secara efektif juga bernilai rupiah**: +> `nilai 1 EnakCoin = (Y / X) × nilai EnakPoint`. Besaran earning EnakCoin (F1) dan +> hadiah EnakCoin di game perlu dihitung sebagai biaya, sama seperti EnakPoint. + +**K4 — Wallet, nilai EnakPoint, kurs, dan kedaluwarsa berada di level organisasi. +Earning di level outlet.** +`customers` sudah terikat ke `organization_id`, dan `customers.phone_number` unik secara +global, sehingga satu nomor telepon adalah satu customer di satu organisasi (Q7, +diputuskan). Saldo berlaku di semua outlet dalam organisasi tersebut. Karena itu nilai +EnakPoint, kurs exchange, dan aturan kedaluwarsa **harus sama di semua outlet** dan +diatur per organisasi. Outlet hanya menentukan berapa yang didapat dari order di +outlet itu, dan apakah outlet menerima pembayaran EnakPoint. Transfer hanya boleh antar +customer dalam organisasi yang sama. + +**K5 — Setiap EnakPoint dan EnakCoin punya jejak: dapat dari mana, hilang ke mana.** +Satu mutasi = satu baris ledger, dan saldo tidak pernah diubah tanpa ledger. Setiap +baris **wajib** menunjuk sumbernya (untuk penambahan) atau tujuannya (untuk +pengurangan). Contohnya order mana, pembayaran mana, customer mana, game play mana, +lot mana yang kedaluwarsa, atau admin siapa. Mutasi tanpa asal/tujuan ditolak oleh +database, bukan cuma oleh aplikasi. Perubahan saldo dan penulisan ledger terjadi dalam +satu transaksi database. Rinciannya di §8.1. + +**K6 — Semua nilai EnakPoint dan EnakCoin berupa bilangan bulat.** +Pecahan hasil perhitungan earning dibulatkan ke bawah. Pembayaran memakai EnakPoint +utuh (tidak ada "setengah Point"). + +**K7 — EnakPoint dan EnakCoin tidak bisa ditunaikan.** +Nilai rupiah EnakPoint hanya berlaku sebagai potongan tagihan order. EnakPoint dan +EnakCoin tidak pernah keluar dari sistem dalam bentuk uang: tidak ada pencairan, tidak +ada kembalian, dan tidak ada refund tunai atas bagian yang dibayar EnakPoint. Semua +jalur yang bisa menjadi jalan untuk menunaikan ditutup: + +| Celah | Aturan | +|---|---| +| Pencairan langsung | Tidak ada endpoint, menu, atau tipe ledger untuk menarik saldo menjadi uang | +| Kembalian | Pembayaran EnakPoint tidak boleh melebihi sisa tagihan. Tidak ada kembalian tunai dari EnakPoint (F9) | +| Refund / void order | Bagian yang dibayar EnakPoint **selalu** kembali sebagai EnakPoint, tidak pernah tunai, transfer bank, atau method lain (F9) | +| Refund sebagian | Sisa rupiah di bawah 1 EnakPoint hangus, tidak dibayar tunai (F9) | +| Order fiktif untuk dibatalkan | Order dibayar EnakPoint lalu di-void hanya mengembalikan EnakPoint | +| Kedaluwarsa | Saldo yang kedaluwarsa hangus tanpa kompensasi dalam bentuk apa pun (F12) | +| Adjustment admin | Mengurangi saldo lewat adjustment tidak disertai pembayaran uang ke customer. Alasan adjustment tidak boleh "pencairan" | +| Transfer | Transfer hanya memindahkan saldo antar customer. Jual-beli saldo di luar sistem tidak difasilitasi dan dilarang di Syarat & Ketentuan | +| Nilai di aplikasi | Nilai rupiah ditampilkan sebagai "setara potongan Rp …", bukan "saldo Rp …", supaya tidak terbaca seperti uang elektronik | + +Aturan ini juga menjaga agar EnakPoint tetap berupa program loyalitas dan tidak +diperlakukan sebagai uang elektronik (lihat catatan N3). + +**K8 — Saldo yang dipindahkan atas permintaan customer wajib disetujui dengan PIN.** +Customer punya PIN 6 digit yang terpisah dari password login (F11). PIN wajib untuk +transfer, pembayaran EnakPoint, dan exchange. Password login tidak dipakai untuk +menyetujui transaksi, karena sesi yang sudah login (HP dipinjam, HP tidak dikunci) +tidak boleh cukup untuk memindahkan saldo. + +| Aksi | Butuh PIN | Alasan | +|---|---|---| +| Transfer EnakPoint / EnakCoin (F5) | **Ya** | Saldo keluar ke orang lain dan tidak bisa dibatalkan | +| Bayar EnakPoint di app / self-order (F9) | **Ya** | Saldo dipakai | +| Buat kode bayar untuk kasir (F9) | **Ya** | Kode bayar sama dengan izin memakai EnakPoint | +| Exchange EnakCoin → EnakPoint (F4) | **Ya** | Tidak bisa dibatalkan | +| Main game (F8) | Tidak | Nilainya kecil per aksi, dan PIN di setiap permainan merusak pengalaman bermain | +| Lihat saldo & riwayat (F6) | Tidak | Tidak memindahkan saldo | +| Reversal, refund, kedaluwarsa, adjustment admin | Tidak berlaku | Dijalankan sistem atau admin, bukan customer | + +**K9 — Saldo disimpan per lot, dan saldo yang paling cepat kedaluwarsa dipakai lebih +dulu.** +Setiap penambahan saldo membuat lot baru dengan tanggal kedaluwarsanya sendiri. Setiap +pengurangan mengambil dari lot yang **paling cepat kedaluwarsa**, dan setiap +pengambilan dicatat (lot mana, berapa banyak). Dengan cara ini: +- Customer tidak dirugikan: saldo yang hampir hangus terpakai lebih dulu. +- Kedaluwarsa tidak bisa diakali. Transfer dan exchange **membawa tanggal kedaluwarsa + asal**, sehingga saldo tidak bisa "diperpanjang" dengan mengirimnya bolak-balik atau + menukarnya. +- Asal setiap butir bisa ditelusuri, tidak hanya asal setiap mutasi (Q9, diputuskan). + +--- + +## 5. User Story + +| # | Sebagai | Saya ingin | Supaya | +|---|---|---|---| +| U1 | Customer | mendapat EnakPoint dan EnakCoin setelah membayar order | belanja saya dihargai | +| U2 | Customer | membayar order dengan EnakPoint, penuh atau sebagian | saldo saya bisa dipakai belanja | +| U3 | Customer | melihat saldo dan riwayat, termasuk asal dan tujuan tiap mutasi | tahu dari mana saldo saya berasal dan dipakai untuk apa | +| U4 | Customer | menukar EnakCoin menjadi EnakPoint | EnakCoin saya bisa ikut dipakai belanja | +| U5 | Customer | mengirim EnakPoint atau EnakCoin ke teman | bisa berbagi atau menggabungkan saldo | +| U6 | Customer | melihat berapa saldo yang akan kedaluwarsa dan kapan, serta diingatkan sebelumnya | bisa memakainya sebelum hangus | +| U7 | Kasir | menerima pembayaran EnakPoint dengan persetujuan customer | EnakPoint customer tidak bisa dipakai tanpa izinnya | +| U8 | Kasir | melihat EnakPoint & EnakCoin yang didapat dan dipakai di struk | bisa memberi tahu customer | +| U9 | Owner/Manager | mengatur earning dan penerimaan EnakPoint per outlet | bisa membedakan promo antar outlet | +| U10 | Owner/Manager | mengatur nilai rupiah EnakPoint, kurs exchange, dan masa berlaku saldo | bisa mengendalikan biaya program loyalitas | +| U11 | Owner/Manager | melihat mutasi wallet seorang customer | bisa menangani komplain | +| U12 | Owner/Manager | menyesuaikan saldo secara manual dengan alasan | bisa mengoreksi kesalahan | +| U13 | Customer | menyetujui transfer, pembayaran, dan exchange dengan PIN | saldo saya aman walaupun HP saya dipinjam orang | +| U14 | Customer | mereset PIN lewat OTP kalau lupa | tidak kehilangan akses ke saldo saya | + +--- + +## 6. Kebutuhan Fungsional + +### F1 — Pengaturan per Outlet + +Disimpan di `outlet_settings` (key–value, sudah ada). + +**Earning.** Pengaturan EnakPoint dan EnakCoin berdiri sendiri. + +| Key | Tipe | Default | Arti | +|---|---|---|---| +| `loyalty.point.enabled` | bool | `false` | Outlet memberi EnakPoint | +| `loyalty.point.earn_per_amount` | int (Rp) | `100` | Setiap kelipatan nominal ini… | +| `loyalty.point.earn_value` | int | `1` | …mendapat sekian EnakPoint | +| `loyalty.point.min_order_amount` | int (Rp) | `0` | Basis minimal agar dapat EnakPoint | +| `loyalty.point.max_per_order` | int, nullable | kosong | Batas atas EnakPoint per order | +| `loyalty.coin.enabled` | bool | `false` | Outlet memberi EnakCoin | +| `loyalty.coin.earn_per_amount` | int (Rp) | `25000` | | +| `loyalty.coin.earn_value` | int | `1` | | +| `loyalty.coin.min_order_amount` | int (Rp) | `0` | | +| `loyalty.coin.max_per_order` | int, nullable | kosong | | + +Dengan nilai EnakPoint default Rp 1, default earning 1 EnakPoint per Rp 100 setara +**cashback 1%**. Dashboard selalu menampilkan persentase cashback efektif di samping +setting ini: `earn_value × nilai EnakPoint / earn_per_amount`. Tujuannya supaya owner +tidak salah mengira skala. + +**Pembayaran EnakPoint.** Hanya ada untuk EnakPoint, tidak ada padanannya untuk +EnakCoin. + +| Key | Tipe | Default | Arti | +|---|---|---|---| +| `loyalty.point.accept_payment` | bool | `false` | Outlet menerima pembayaran EnakPoint | +| `loyalty.point.min_payment_points` | int | `1` | EnakPoint minimal per pembayaran | +| `loyalty.point.max_payment_percent` | int (0–100) | `100` | Porsi maksimal total order yang boleh dibayar EnakPoint | + +**Rumus earning:** + +``` +basis = subtotal − discount_amount − dibayar_dengan_enakpoint +jumlah = 0 jika basis < min_order_amount +jumlah = floor(basis / earn_per_amount) × earn_value +jumlah = min(jumlah, max_per_order) jika max_per_order diisi +``` + +- Basis dihitung **sebelum pajak** (Q1, diputuskan). `tax_amount` tidak ikut dihitung, + begitu juga service charge atau biaya lain yang ditambahkan di atas subtotal. +- Bagian order yang dibayar EnakPoint **tidak** menghasilkan earning (Q10, diputuskan), + supaya tidak ada "Point dari Point". + +**Contoh.** Subtotal setelah diskon Rp 87.500, dibayar tunai penuh. Outlet memberi +1 EnakPoint per Rp 100 dan 1 EnakCoin per Rp 25.000. Customer mendapat **875 +EnakPoint** dan **3 EnakCoin**. Jika Rp 20.000 dari order itu dibayar dengan EnakPoint, +basisnya menjadi Rp 67.500, sehingga customer mendapat 675 EnakPoint dan 2 EnakCoin. + +Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `min_order_amount ≥ 0`, +`max_per_order ≥ 0`, `0 ≤ max_payment_percent ≤ 100`. Hanya role Admin/Manager yang +bisa mengubah. + +### F2 — Pengaturan per Organisasi + +Disimpan di pengaturan organisasi. Berlaku untuk semua outlet (K4). + +| Key | Tipe | Default | Arti | +|---|---|---|---| +| `loyalty.point.value` | int (Rp), ≥ 1 | `1` | Nilai rupiah 1 EnakPoint saat membayar (Q11, diputuskan) | +| `loyalty.exchange.coin_amount` | int, ≥ 1 | `1` | Kurs: sekian EnakCoin… | +| `loyalty.exchange.point_amount` | int, ≥ 1 | `1` | …ditukar menjadi sekian EnakPoint (Q11, diputuskan) | +| `loyalty.transfer.enabled` | bool | `true` | Transfer diizinkan | +| `loyalty.transfer.min_amount` | int | `1` | | +| `loyalty.transfer.max_per_transaction` | int, nullable | kosong | | +| `loyalty.transfer.daily_limit` | int, nullable | kosong | | +| `loyalty.{point,coin}.expiry_*` | – | nonaktif | Kedaluwarsa, lihat F12 | + +**Mengubah nilai EnakPoint atau kurs exchange** langsung mengubah daya beli saldo yang +beredar. Karena itu: +- Dashboard menampilkan peringatan beserta total saldo beredar dan nilai rupiahnya + sebelum dan sesudah perubahan. +- Perubahan berlaku ke depan saja. Pembayaran, refund, dan exchange yang sudah terjadi + memakai nilai yang dibekukan saat transaksi tersebut. +- Setiap perubahan setting loyalitas dicatat: key, nilai lama, nilai baru, siapa, dan + kapan. + +### F3 — Earning dari Order + +- **Pemicu:** order berpindah ke `payment_status = completed`, yaitu lunas penuh + (termasuk lunas lewat split bill). +- **Syarat:** order punya `customer_id`, customer tersebut **bukan** customer default + (walk-in, `is_default = true`), dan customer aktif. +- **Semua kanal diperlakukan sama** (Q2, diputuskan): order dari kasir, self-order (QR + meja), dan customer app memakai aturan dan setting outlet yang sama. +- **Sekali per order.** Ledger memakai idempotency key `earn:{order_id}:{currency}`, + sehingga pemicu ganda (retry, webhook ganda) tidak menggandakan saldo. +- **Snapshot setting.** Nilai setting yang dipakai disimpan di metadata ledger, supaya + perubahan setting berikutnya tidak mengubah arti earning yang sudah terjadi dan + reversal bisa dihitung dengan setting yang sama. +- Earning membuat lot baru dengan tanggal kedaluwarsa sesuai F12. +- Kegagalan earning **tidak boleh** menggagalkan pembayaran order. Kegagalan dicatat + di log dan bisa di-retry, dan idempotency key menjamin retry aman. +- Response order dan data struk menyertakan `points_earned` dan `coins_earned`. + +### F4 — Exchange EnakCoin → EnakPoint + +- Kurs sesuai F2: `coin_amount` EnakCoin = `point_amount` EnakPoint (default 1 : 1). +- Customer memasukkan jumlah EnakCoin. Jumlahnya harus **kelipatan `coin_amount`**, + supaya tidak ada EnakCoin yang hilang karena pembulatan. Aplikasi menampilkan + EnakPoint yang akan didapat sebelum konfirmasi. + ``` + point_didapat = (coin_ditukar / coin_amount) × point_amount + ``` +- EnakCoin berkurang dan EnakPoint bertambah dalam satu transaksi. +- Menghasilkan dua baris ledger: `EXCHANGE_OUT` (COIN, −) dan `EXCHANGE_IN` (POINT, +), + keduanya dengan `group_id` yang sama. Kurs yang dipakai dibekukan di metadata keduanya. +- **Kedaluwarsa ikut terbawa** (K9). Lot EnakPoint hasil exchange kedaluwarsa pada + `min(kedaluwarsa lot EnakCoin asal, sekarang + masa berlaku EnakPoint)`. Exchange + tidak bisa dipakai untuk memperpanjang umur saldo. +- Tidak bisa dibatalkan, jadi aplikasi menampilkan konfirmasi dan meminta PIN (K8). +- Request wajib membawa `Idempotency-Key`. + +### F5 — Transfer ke Customer Lain + +- Mata uang: EnakPoint **atau** EnakCoin, satu jenis per transfer. +- **Penerima** diidentifikasi dengan nomor telepon (identitas login customer app). + Sebelum konfirmasi, aplikasi menampilkan nama penerima yang sudah disamarkan (mis. + "Bu*** Sa***") supaya pengirim bisa memastikan. +- **Syarat penerima:** customer aktif, organisasi sama, bukan customer default, dan + bukan diri sendiri. +- **Konfirmasi:** pengirim memasukkan **PIN** (K8, F11; Q5 diputuskan). +- **Batas:** diatur per organisasi (F2). Defaultnya tanpa batas, dan owner bisa + memasang batas per transaksi atau harian (Q4, diputuskan). +- Menghasilkan dua baris ledger: `TRANSFER_OUT` (pengirim, −N) dan `TRANSFER_IN` + (penerima, +N), dengan `group_id` sama dan referensi silang ke customer lawan. +- **Kedaluwarsa ikut terbawa** (K9). Saldo diambil dari lot pengirim yang paling cepat + kedaluwarsa, dan penerima mendapat lot dengan tanggal kedaluwarsa yang sama persis. + Aplikasi pengirim menampilkan bahwa saldo yang dikirim akan kedaluwarsa pada tanggal + tersebut. +- Final dan tidak bisa dibatalkan oleh customer. Koreksi hanya lewat adjustment admin + (F7). +- Request wajib membawa `Idempotency-Key`. +- Penerima mendapat notifikasi push (memakai `NotificationService` yang sudah ada). + +### F6 — Saldo & Riwayat (Customer App) + +- `GET /customer/wallet` mengembalikan saldo EnakPoint (beserta nilai rupiahnya saat + ini), saldo EnakCoin, **saldo yang akan kedaluwarsa terdekat** (jumlah dan tanggal), + dan beberapa mutasi terakhir. +- `GET /customer/wallet/expiring` mengembalikan rincian saldo yang akan kedaluwarsa, + dikelompokkan per tanggal. +- `GET /customer/wallet/transactions` mengembalikan daftar mutasi dengan pagination, + bisa difilter per currency, tipe, dan rentang tanggal. +- Setiap mutasi menampilkan: tipe, jumlah bertanda (+/−), saldo setelahnya, + **asal (untuk penambahan) atau tujuan (untuk pengurangan)** sesuai §8.1, dan waktu. + Mutasi masuk juga menampilkan tanggal kedaluwarsanya. +- Mutasi bisa dibuka ke detail: order (nomor, outlet, total), pembayaran (nominal + rupiah yang ditutup), lawan transfer (nama tersamar), game play (hadiah yang + didapat), atau pasangan exchange-nya. +- Riwayat tidak pernah hilang. Mutasi yang dikoreksi tetap tampil, bersama baris + koreksinya. + +### F7 — Admin (Dashboard) + +- Melihat wallet dan mutasi seorang customer, dengan asal/tujuan tampil penuh (nama + asli lawan transfer, admin pelaku adjustment, kasir penerima pembayaran). +- **Telusuri mutasi:** dari satu mutasi, lompat ke referensinya, yaitu order, + pembayaran, baris pasangan transfer/exchange, baris asal dari sebuah reversal, game + play, atau lot yang kedaluwarsa. +- **Telusuri per butir:** dari satu pengurangan (misalnya pembayaran), lihat lot mana + yang terpakai, lalu dari lot itu telusuri asalnya sampai ke earning awal, termasuk + jika saldo itu sudah melewati beberapa transfer atau exchange. +- Melihat semua mutasi yang berasal dari satu order (earning, pembayaran, reversal, + refund) dari halaman detail order. +- **Adjustment manual:** tambah atau kurangi EnakPoint/EnakCoin dengan alasan wajib. + Tercatat sebagai `ADJUSTMENT` beserta `user_id` admin. Saldo tidak boleh menjadi + negatif. Adjustment tambah membuat lot dengan kedaluwarsa sesuai F12. +- Mengatur F1 per outlet serta F2 dan F12 per organisasi. + +### F8 — Game Memakai EnakCoin + +- **Semua jenis game** (`SPIN`, ferris wheel, `RAFFLE`, `MINIGAME`) memotong EnakCoin + yang sama. `POST /customer/spin` memotong EnakCoin, bukan Token `SPIN`. +- Biaya per main diatur per game di `games.metadata.coin_cost` (default 1), sehingga + game yang hadiahnya lebih besar bisa lebih mahal. +- Pemotongan EnakCoin, pencatatan `game_plays`, pengurangan stok hadiah, dan ledger + `GAME_SPEND` terjadi dalam satu transaksi. Jika stok hadiah gagal dikurangi, seluruh + permainan dibatalkan (saat ini hanya di-`Printf`). +- `game_plays.token_used` berganti arti menjadi jumlah EnakCoin yang dipakai (diganti + nama menjadi `coins_used`). + +### F9 — Bayar Order dengan EnakPoint + +**Payment method.** Setiap organisasi otomatis punya satu payment method sistem +bernama **EnakPoint** dengan tipe baru `point` di `payment_methods`. Method ini tidak +bisa dihapus atau diubah tipenya. Muncul di kasir hanya jika outlet mengaktifkan +`loyalty.point.accept_payment`. Tidak ada payment method untuk EnakCoin. + +**Siapa yang dipotong.** Yang dipotong selalu saldo **customer yang tercatat di order** +(`orders.customer_id`). Order walk-in (customer default) tidak bisa dibayar EnakPoint. +Kalau customer ingin memakai EnakPoint milik orang lain, pemiliknya harus mentransfer +dulu (F5). + +**Perhitungan.** + +``` +nilai = loyalty.point.value (dibaca saat pembayaran, lalu dibekukan) +batas_rupiah = min(remaining_amount, + total_amount × max_payment_percent / 100 + − yang_sudah_dibayar_enakpoint_di_order_ini) +maks_point = min(saldo_point, floor(batas_rupiah / nilai)) +point_dipakai = pilihan customer, min_payment_points ≤ point_dipakai ≤ maks_point +nominal_rupiah = point_dipakai × nilai +``` + +- EnakPoint tidak pernah menghasilkan kembalian (K7). `nominal_rupiah` tidak boleh + melebihi `remaining_amount`. Jika nilai EnakPoint diatur lebih dari Rp 1, sisa tagihan + yang bukan kelipatan `nilai` dibayar dengan method lain lewat split payment yang sudah + ada. +- Aplikasi dan kasir menyediakan tombol "Pakai maksimal" yang mengisi `maks_point`. +- EnakPoint diambil dari lot yang paling cepat kedaluwarsa (K9). + +**Contoh.** Nilai EnakPoint Rp 1 (default), sisa tagihan Rp 87.550, saldo 50.000 +EnakPoint, batas 100%. `maks_point = min(50000, floor(87550 / 1)) = 50000`. Customer +memakai 50.000 EnakPoint (Rp 50.000), lalu sisa Rp 37.550 dibayar tunai. + +**Persetujuan customer.** Kasir tidak boleh bisa memakai EnakPoint customer tanpa +izinnya. +- **Di kasir (POS):** customer membuka aplikasi, memasukkan **PIN**, lalu aplikasi + menampilkan **kode bayar**, yaitu kode 6 digit/QR sekali pakai yang berlaku 2 menit. + Kasir memindai atau mengetik kode tersebut. Kode terikat ke customer, sehingga kode + milik customer lain ditolak. PIN **tidak pernah** diketik di perangkat kasir, supaya + kasir tidak bisa melihat atau merekamnya. Customer tanpa aplikasi belum didukung + (catatan N1). +- **Di customer app / self-order:** customer memasukkan PIN sebelum pembayaran + diproses. Sesi login saja tidak cukup (K8). + +**Pencatatan.** Dalam satu transaksi database: +1. Kunci wallet customer. +2. Ambil saldo dari lot yang paling cepat kedaluwarsa dan catat alokasinya (§8). +3. Potong saldo EnakPoint (update bersyarat, §7). +4. Buat baris `payments` dengan method EnakPoint, `status = completed`, + `amount = nominal_rupiah`, `points_used`, dan `point_value` (nilai yang dibekukan). +5. Tulis ledger `PAYMENT` (POINT, −N) yang menunjuk `payments.id` dan `outlet_id`. +6. Perbarui `remaining_amount` / `payment_status` order seperti pembayaran lain. + +Idempotency key: `payment:{payment_id}`. Kasir yang menekan tombol dua kali tidak +memotong dua kali. + +**Void / refund pembayaran EnakPoint.** +- Pengembalian **hanya dalam bentuk EnakPoint** (K7). Endpoint refund menolak permintaan + yang mengembalikan bagian EnakPoint lewat method lain (tunai, kartu, transfer). Kasir + tidak diberi pilihan method refund untuk bagian ini. +- EnakPoint dikembalikan ke customer yang sama sebagai `PAYMENT_REFUND` (POINT, +N), + dengan `reverses_transaction_id` menunjuk baris `PAYMENT` asal. +- Jumlah yang dikembalikan dihitung dengan **`point_value` yang dibekukan di + pembayaran**, bukan nilai saat ini. Customer mendapat kembali EnakPoint sebanyak yang + dipakai, tidak lebih dan tidak kurang, walaupun nilai EnakPoint sudah diubah. +- **Kedaluwarsa dipulihkan.** EnakPoint yang dikembalikan kembali ke lot dengan tanggal + kedaluwarsa asalnya. Jika tanggal itu sudah lewat atau tinggal kurang dari 7 hari, + masa berlakunya diperpanjang menjadi 7 hari sejak refund, supaya customer sempat + memakainya (catatan N4). +- **Void order:** semua pembayaran EnakPoint di order itu dikembalikan penuh. +- **Refund sebagian:** mengikuti alur refund per-`payments` yang sudah ada. Refund atas + pembayaran EnakPoint dilakukan dalam EnakPoint utuh: + `point_kembali = floor(refund_amount / point_value)`. Sisa rupiah di bawah 1 + EnakPoint hangus, tidak dikembalikan sebagai EnakPoint maupun tunai (Q13, + diputuskan). +- Akumulasi EnakPoint yang dikembalikan tidak boleh melebihi `points_used`. + +**Tampilan.** Struk dan detail order menampilkan baris "EnakPoint: 50.000 (Rp 50.000)". + +**Laporan.** Laporan per payment method menampilkan EnakPoint terpisah. EnakPoint yang +dipakai membayar **bukan kas masuk**. Perlakuan akuntansinya ditunda (catatan N2). + +### F10 — Reversal Earning saat Void / Refund + +- **Void** order yang sudah memberi earning: EnakPoint dan EnakCoin dari order itu + ditarik kembali sepenuhnya. +- **Refund sebagian:** penarikan proporsional, + `floor(earned × refund_amount / basis)`, dengan akumulasi penarikan tidak melebihi + yang pernah diberikan. +- **Lot yang ditarik:** pertama dari lot yang dibuat oleh `EARN` order tersebut + (kalau masih ada sisanya), lalu dari lot lain dengan urutan K9. +- **Saldo tidak cukup** (misalnya sudah dipakai atau ditransfer): tarik sebanyak saldo + yang ada sampai 0, lalu catat kekurangannya di metadata ledger (`shortfall`). Saldo + tidak boleh negatif, dan refund **tidak pernah diblokir** karena saldo tidak cukup + (Q3, diputuskan). +- Tipe ledger: `EARN_REVERSAL`, dengan `reverses_transaction_id` menunjuk `EARN` asal. +- Jika order dibayar sebagian dengan EnakPoint, maka pada void yang sama earning ditarik + (F10) **dan** EnakPoint pembayaran dikembalikan (F9). Keduanya tercatat sebagai + baris terpisah. + +### F11 — PIN Customer + +**Format.** 6 digit angka. Terpisah dari password login. + +**Membuat PIN.** +- Diminta saat customer pertama kali melakukan aksi yang butuh PIN (K8), bukan saat + registrasi. Customer yang hanya mengumpulkan saldo tidak dipaksa membuat PIN. +- Customer yang belum punya PIN tetap bisa **menerima** transfer dan earning, tapi tidak + bisa mengirim, membayar, atau exchange sampai PIN dibuat. +- Membuat PIN pertama kali memerlukan OTP ke nomor telepon customer (memakai + `OtpProcessor` yang sudah ada, dengan purpose baru `pin_setup`). Ini memastikan PIN + dibuat oleh pemilik nomor, bukan oleh orang yang kebetulan memegang HP yang sedang + login. +- PIN ditolak jika terlalu mudah ditebak: semua digit sama (`111111`), berurutan + (`123456`, `654321`), atau sama dengan tanggal lahir (`DDMMYY` / `YYMMDD`, dari + `customers.birth_date`). +- PIN dimasukkan dua kali untuk konfirmasi. + +**Penyimpanan.** Hanya hash (bcrypt, sama seperti `password_hash`). PIN tidak pernah +disimpan, dicatat di log, atau dikembalikan di response dalam bentuk asli. Admin tidak +bisa melihat PIN. + +**Salah PIN** (Q17, diputuskan). +- Setiap salah PIN menambah penghitung. Setelah **5 kali salah berturut-turut**, PIN + dikunci selama **30 menit**. Selama terkunci, semua aksi yang butuh PIN ditolak, + termasuk PIN yang benar. +- PIN yang benar mereset penghitung ke 0. +- Penghitung disimpan di database, bukan hanya di cache, supaya tidak bisa dilewati + dengan menunggu cache hilang atau menembak server yang berbeda. +- Response saat salah PIN menyebutkan sisa percobaan. Saat terkunci, response + menyebutkan kapan kunci dibuka. +- Setiap kali PIN terkunci, customer mendapat notifikasi push. + +**Mengganti PIN.** Customer memasukkan PIN lama, lalu PIN baru dua kali. + +**Lupa PIN.** Customer meminta reset, memverifikasi OTP ke nomor telepon (purpose +`pin_reset`), lalu membuat PIN baru. Reset lewat OTP juga membuka kunci PIN. Setelah +reset, **transfer keluar ditahan 24 jam**, sedangkan pembayaran dan exchange tetap bisa +(Q16, diputuskan). Ini membatasi kerugian jika nomor telepon customer diambil alih. + +**Admin.** Admin tidak bisa membuat atau mengganti PIN customer. Admin hanya bisa +**menghapus PIN** (misalnya atas permintaan customer yang kehilangan akses), sehingga +customer harus membuat PIN baru lewat OTP. Aksi ini tercatat beserta admin pelaku dan +alasannya. + +**Jejak.** Semua peristiwa PIN dicatat di log keamanan: dibuat, diganti, di-reset, +salah, terkunci, dan dihapus admin. Setiap peristiwa menyimpan waktu, customer, dan +perangkat/IP. Peristiwa ini bukan mutasi saldo, jadi tidak masuk `wallet_transactions`. + +### F12 — Kedaluwarsa Saldo + +> **Ditunda: model kedaluwarsa belum diputuskan (catatan N4).** Isi bagian ini +> menggambarkan model **per saldo masuk** sebagai draft. Alternatifnya adalah model +> **tanggal tetap** (gaya Telkomsel POIN / XL Poin, semua hangus di tanggal yang sama). +> Yang sudah pasti dan tidak bergantung pada N4: saldo bisa kedaluwarsa, owner bisa +> mengatur sendiri, saldo disimpan per lot (K9), transfer dan exchange membawa tanggal +> kedaluwarsa asal, dan saldo yang hangus tercatat sebagai `EXPIRE`. + +**Pengaturan** (per organisasi, terpisah untuk EnakPoint dan EnakCoin; Q9, diputuskan): + +| Key | Tipe | Default | Arti | +|---|---|---|---| +| `loyalty.point.expiry_enabled` | bool | `false` | EnakPoint bisa kedaluwarsa | +| `loyalty.point.expiry_period` | int, ≥ 1 | `12` | Lama masa berlaku… | +| `loyalty.point.expiry_unit` | `DAY` / `MONTH` | `MONTH` | …dalam satuan ini | +| `loyalty.point.expiry_end_of_month` | bool | `false` | Dibulatkan ke akhir bulan (mis. semua saldo Maret 2026 hangus 31 Maret 2027) | +| `loyalty.point.expiry_reminder_days` | int, ≥ 0 | `7` | Pengingat dikirim sekian hari sebelum kedaluwarsa (0 = tanpa pengingat) | +| `loyalty.coin.expiry_*` | | sama | Pengaturan yang sama untuk EnakCoin | + +Dashboard menampilkan contoh hasil setting, misalnya "EnakPoint yang didapat hari ini +kedaluwarsa pada 30 Sep 2027". + +**Tanggal kedaluwarsa per lot:** + +| Saldo masuk lewat | Kedaluwarsa | +|---|---| +| `EARN`, `ADJUSTMENT` (+) | Sejak saat masuk + masa berlaku currency tersebut. Kosong (tidak kedaluwarsa) jika expiry nonaktif | +| `TRANSFER_IN` | **Sama persis** dengan lot pengirim yang terpakai | +| `EXCHANGE_IN` | `min(kedaluwarsa lot EnakCoin asal, sekarang + masa berlaku EnakPoint)` | +| `PAYMENT_REFUND` | Kedaluwarsa lot asal. Jika sudah lewat atau kurang dari 7 hari lagi, menjadi 7 hari sejak refund (catatan N4) | +| `MIGRATION` | Kosong, sampai expiry diaktifkan (lihat aturan aktivasi di bawah) | + +**Proses kedaluwarsa.** +- Job terjadwal berjalan setiap jam. Job mencari lot dengan `expires_at ≤ sekarang` dan + sisa > 0. +- Untuk setiap lot, job menulis satu baris ledger `EXPIRE` (−sisa) yang menunjuk lot + tersebut, lalu menjadikan sisa lot 0. Semua ini dalam satu transaksi dengan lock + wallet. Idempotency key: `expire:{lot_id}`. +- Saldo yang kedaluwarsa hangus tanpa kompensasi (K7). +- Customer mendapat notifikasi saat saldo kedaluwarsa, dengan jumlahnya. + +**Pengingat.** Sekian hari sebelum kedaluwarsa (`expiry_reminder_days`), customer +mendapat notifikasi push: "150 EnakPoint akan kedaluwarsa pada 31 Okt 2026". Pengingat +dikelompokkan per tanggal, sehingga satu notifikasi per tanggal kedaluwarsa, bukan satu +per lot. + +**Mengubah pengaturan.** +- Mengubah masa berlaku hanya berlaku untuk lot yang masuk **setelah** perubahan. Lot + yang sudah ada tetap memakai tanggalnya. +- **Mengaktifkan** expiry untuk pertama kali: lot yang sudah ada tanpa tanggal + kedaluwarsa diberi tanggal `waktu aktivasi + masa berlaku`, sehingga customer mendapat + masa berlaku penuh sejak aturan diumumkan (catatan N4). +- **Menonaktifkan** expiry: lot baru tidak kedaluwarsa. Lot yang sudah punya tanggal + tetap kedaluwarsa sesuai jadwalnya (catatan N4). +- Setiap perubahan tercatat (F2), dan dashboard menampilkan berapa saldo customer yang + terdampak sebelum owner menyimpan. + +--- + +## 7. Aturan Konsistensi + +1. **Saldo tidak pernah negatif.** Dijaga oleh `CHECK` di database dan update bersyarat + (`WHERE balance >= ?`) yang **mengecek jumlah baris ter-update**. Update yang + mengenai 0 baris dianggap saldo tidak cukup. +2. **Satu transaksi database per operasi.** Semua repository wallet memakai + `DBFromContext` agar ikut transaksi dari `TxManager`. Pembayaran EnakPoint berada di + transaksi yang sama dengan pembuatan baris `payments`. +3. **Urutan lock.** Setiap operasi, termasuk job kedaluwarsa, mengunci wallet + (`SELECT … FOR UPDATE`) sebelum mengubah wallet atau lot-nya. Transfer mengunci dua + wallet berurutan berdasarkan `customer_id` untuk mencegah deadlock. Operasi yang + bersamaan untuk customer yang sama akan antre di lock yang sama, sehingga saldo tidak + terpakai dua kali dan tidak terpakai setelah kedaluwarsa. +4. **Idempotensi.** `wallet_transactions.idempotency_key` unik. Request ulang dengan key + yang sama mengembalikan hasil pertama, bukan error dan bukan mutasi baru. +5. **Rekonsiliasi.** Job pemeriksaan memastikan, per customer per currency: + - `SUM(amount)` ledger = saldo wallet = `SUM(remaining_amount)` semua lot. + - Untuk setiap lot: `original_amount − SUM(alokasi) = remaining_amount`. + - Untuk setiap mutasi keluar: `SUM(alokasi)` = nilai absolut `amount`-nya. + - Untuk setiap `payments` bermethod EnakPoint: `points_used` = nilai absolut baris + `PAYMENT`-nya. + +--- + +## 8. Model Data (Usulan) + +### `customer_wallets`: menggantikan `customer_points` dan `customer_tokens` + +Satu baris per customer. Baris ini juga menjadi titik lock untuk semua operasi wallet +customer tersebut. + +```sql +CREATE TABLE customer_wallets ( + customer_id UUID PRIMARY KEY REFERENCES customers(id) ON DELETE RESTRICT, + organization_id UUID NOT NULL REFERENCES organizations(id), + point_balance BIGINT NOT NULL DEFAULT 0 CHECK (point_balance >= 0), + coin_balance BIGINT NOT NULL DEFAULT 0 CHECK (coin_balance >= 0), + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); +``` + +### `wallet_transactions`: ledger + +```sql +CREATE TABLE wallet_transactions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id UUID NOT NULL, + customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT, + currency VARCHAR(10) NOT NULL CHECK (currency IN ('POINT','COIN')), + type VARCHAR(30) NOT NULL, + amount BIGINT NOT NULL CHECK (amount <> 0), -- bertanda + balance_after BIGINT NOT NULL, + group_id UUID, -- menyatukan pasangan exchange / transfer + + -- Asal (amount > 0) atau tujuan (amount < 0). Wajib untuk semua tipe. + reference_type VARCHAR(30) NOT NULL, -- ORDER, PAYMENT, WALLET_TX, GAME_PLAY, LOT, USER, ... + reference_id UUID NOT NULL, + + counterparty_customer_id UUID REFERENCES customers(id), -- TRANSFER_IN / _OUT + reverses_transaction_id UUID REFERENCES wallet_transactions(id), -- EARN_REVERSAL / PAYMENT_REFUND + outlet_id UUID, -- EARN, EARN_REVERSAL, PAYMENT, PAYMENT_REFUND + created_by_user UUID, -- ADJUSTMENT: admin; PAYMENT / PAYMENT_REFUND: kasir + reason VARCHAR(255), -- ADJUSTMENT: alasan + + description VARCHAR(255) NOT NULL, -- teks siap tampil, dibekukan saat dibuat + metadata JSONB DEFAULT '{}', -- snapshot setting, point_value, kurs, shortfall + idempotency_key VARCHAR(100) UNIQUE, + created_at TIMESTAMPTZ DEFAULT NOW(), + + -- Hanya EnakPoint yang bisa membayar (K2) + CONSTRAINT chk_point_only_types CHECK ( + type NOT IN ('PAYMENT','PAYMENT_REFUND','EXCHANGE_IN','REWARD_REDEEM') + OR currency = 'POINT'), + CONSTRAINT chk_coin_only_types CHECK ( + type NOT IN ('EXCHANGE_OUT','GAME_SPEND') OR currency = 'COIN'), + + CONSTRAINT chk_transfer_counterparty CHECK ( + type NOT IN ('TRANSFER_IN','TRANSFER_OUT') OR counterparty_customer_id IS NOT NULL), + CONSTRAINT chk_reversal_source CHECK ( + type NOT IN ('EARN_REVERSAL','PAYMENT_REFUND') OR reverses_transaction_id IS NOT NULL), + CONSTRAINT chk_adjustment_actor CHECK ( + type <> 'ADJUSTMENT' OR (created_by_user IS NOT NULL AND reason IS NOT NULL)), + CONSTRAINT chk_expire_lot CHECK ( + type <> 'EXPIRE' OR reference_type = 'LOT') +); +-- index: (customer_id, created_at DESC), (reference_type, reference_id), (group_id), +-- (counterparty_customer_id), (reverses_transaction_id) +``` + +Ledger bersifat **append-only**. Baris tidak pernah di-`UPDATE` atau di-`DELETE`. +Koreksi dilakukan dengan baris baru (`EARN_REVERSAL`, `PAYMENT_REFUND`, atau +`ADJUSTMENT`) yang menunjuk baris yang dikoreksi. Customer yang punya riwayat tidak bisa +dihapus permanen, cukup dinonaktifkan. + +### `wallet_lots` dan `wallet_lot_allocations`: saldo per butir (K9) + +```sql +CREATE TABLE wallet_lots ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id UUID NOT NULL, + customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT, + currency VARCHAR(10) NOT NULL CHECK (currency IN ('POINT','COIN')), + source_transaction_id UUID NOT NULL REFERENCES wallet_transactions(id), -- mutasi masuk pembuatnya + origin_lot_id UUID REFERENCES wallet_lots(id), -- lot asal: transfer / exchange / refund + original_amount BIGINT NOT NULL CHECK (original_amount > 0), + remaining_amount BIGINT NOT NULL CHECK (remaining_amount >= 0 + AND remaining_amount <= original_amount), + expires_at TIMESTAMPTZ, -- NULL = tidak kedaluwarsa + created_at TIMESTAMPTZ DEFAULT NOW() +); +-- urutan pemakaian (K9): paling cepat kedaluwarsa dulu, yang tanpa tanggal paling akhir +CREATE INDEX idx_wallet_lots_consume ON wallet_lots + (customer_id, currency, expires_at NULLS LAST, created_at) WHERE remaining_amount > 0; +CREATE INDEX idx_wallet_lots_expiry ON wallet_lots (expires_at) WHERE remaining_amount > 0; + +-- Setiap mutasi keluar mencatat lot mana yang dipakai dan berapa banyak +CREATE TABLE wallet_lot_allocations ( + transaction_id UUID NOT NULL REFERENCES wallet_transactions(id), -- mutasi keluar + lot_id UUID NOT NULL REFERENCES wallet_lots(id), + amount BIGINT NOT NULL CHECK (amount > 0), + PRIMARY KEY (transaction_id, lot_id) +); +``` + +`wallet_lots.remaining_amount` adalah satu-satunya kolom yang di-`UPDATE`, sebagai +ringkasan untuk mempercepat pemakaian. Nilainya selalu bisa dihitung ulang dari +`original_amount − SUM(wallet_lot_allocations.amount)` (§7.5). Ledger dan alokasi tetap +append-only. + +**Contoh.** Customer A punya lot 100 EnakPoint (dari order #ORD-1, kedaluwarsa 31 Des) +dan lot 50 EnakPoint (dari order #ORD-2, kedaluwarsa 31 Jan). A mentransfer 120 ke B. +- `TRANSFER_OUT` A dialokasikan 100 dari lot #ORD-1 dan 20 dari lot #ORD-2. +- B mendapat dua lot: 100 (kedaluwarsa 31 Des, `origin_lot_id` = lot #ORD-1) dan 20 + (kedaluwarsa 31 Jan, `origin_lot_id` = lot #ORD-2). +- Kalau B lalu membayar dengan 30 EnakPoint, alokasinya menunjukkan bahwa 30 EnakPoint + itu berasal dari order #ORD-1 milik A. + +### Perubahan tabel yang sudah ada + +```sql +-- payment_methods.type: tambah nilai 'point' +-- (validator saat ini: oneof=cash card digital_wallet) + +-- PIN customer (F11) +ALTER TABLE customers + ADD COLUMN pin_hash VARCHAR(255), + ADD COLUMN pin_set_at TIMESTAMPTZ, + ADD COLUMN pin_failed_attempts INT NOT NULL DEFAULT 0, + ADD COLUMN pin_locked_until TIMESTAMPTZ, + ADD COLUMN transfer_blocked_until TIMESTAMPTZ; -- 24 jam setelah reset PIN + +CREATE TABLE customer_security_events ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT, + event VARCHAR(30) NOT NULL, -- PIN_SET, PIN_CHANGED, PIN_RESET, PIN_FAILED, + -- PIN_LOCKED, PIN_REMOVED_BY_ADMIN + actor_user UUID, -- diisi untuk PIN_REMOVED_BY_ADMIN + reason VARCHAR(255), + ip_address VARCHAR(45), + user_agent VARCHAR(255), + created_at TIMESTAMPTZ DEFAULT NOW() +); + +ALTER TABLE payments + ADD COLUMN points_used BIGINT, -- diisi hanya untuk method EnakPoint + ADD COLUMN point_value DECIMAL(10,2), -- nilai 1 EnakPoint saat dibayar (beku) + ADD CONSTRAINT chk_payments_point_pair CHECK ( + (points_used IS NULL AND point_value IS NULL) + OR (points_used > 0 AND point_value > 0)); + +-- Riwayat perubahan setting loyalitas (F2, F12) +CREATE TABLE loyalty_setting_changes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id UUID NOT NULL, + outlet_id UUID, -- NULL untuk setting organisasi + key VARCHAR(100) NOT NULL, + old_value TEXT, + new_value TEXT, + changed_by UUID NOT NULL, + created_at TIMESTAMPTZ DEFAULT NOW() +); +``` + +### 8.1 Jejak Asal & Tujuan per Tipe + +| Tipe | Currency | Arah | Dari mana / ke mana | `reference_type` → `reference_id` | Kolom wajib tambahan | Contoh `description` | +|---|---|---|---|---|---|---| +| `EARN` | POINT / COIN | masuk | Order yang lunas | `ORDER` → `orders.id` | `outlet_id` | "Belanja #ORD-0123 di Outlet Kemang" | +| `EARN_REVERSAL` | POINT / COIN | keluar | Ditarik karena order di-void/refund | `ORDER` → `orders.id` | `reverses_transaction_id` (baris `EARN` asal), `outlet_id` | "Batal #ORD-0123 di Outlet Kemang" | +| `PAYMENT` | POINT | keluar | Dipakai membayar order | `PAYMENT` → `payments.id` | `outlet_id`, `created_by_user` (kasir, jika via POS) | "Bayar #ORD-0123 di Outlet Kemang (Rp 50.000)" | +| `PAYMENT_REFUND` | POINT | masuk | Dikembalikan karena pembayaran di-void/refund | `PAYMENT` → `payments.id` | `reverses_transaction_id` (baris `PAYMENT` asal), `outlet_id` | "Pengembalian #ORD-0123 di Outlet Kemang" | +| `EXCHANGE_OUT` | COIN | keluar | Ditukar menjadi EnakPoint | `WALLET_TX` → baris `EXCHANGE_IN` pasangannya | `group_id` | "Tukar 50 EnakCoin ke EnakPoint" | +| `EXCHANGE_IN` | POINT | masuk | Hasil tukar EnakCoin | `WALLET_TX` → baris `EXCHANGE_OUT` pasangannya | `group_id` | "Dari tukar 50 EnakCoin" | +| `TRANSFER_OUT` | POINT / COIN | keluar | Dikirim ke customer lain | `WALLET_TX` → baris `TRANSFER_IN` penerima | `counterparty_customer_id`, `group_id` | "Transfer ke Bu*** Sa*** (08**-****-1234)" | +| `TRANSFER_IN` | POINT / COIN | masuk | Diterima dari customer lain | `WALLET_TX` → baris `TRANSFER_OUT` pengirim | `counterparty_customer_id`, `group_id` | "Transfer dari An*** (08**-****-5678)" | +| `GAME_SPEND` | COIN | keluar | Dipakai bermain game | `GAME_PLAY` → `game_plays.id` | – | "Main Spin Wheel: dapat Voucher 10rb" | +| `EXPIRE` | POINT / COIN | keluar | Hangus karena masa berlaku habis | `LOT` → `wallet_lots.id` | – | "Kedaluwarsa: 150 EnakPoint dari Belanja #ORD-0098" | +| `ADJUSTMENT` | POINT / COIN | masuk/keluar | Koreksi manual oleh admin | `USER` → `users.id` admin | `created_by_user`, `reason` | "Koreksi oleh admin: komplain #45" | +| `MIGRATION` | POINT / COIN | masuk | Saldo lama sebelum sistem ini | `LEGACY_POINTS` / `LEGACY_TOKENS` → id baris lama | – | "Saldo awal dari sistem lama" | +| `REWARD_REDEEM` | POINT | keluar | Ditukar reward (fase berikut) | `REWARD_REDEMPTION` → id penukaran | – | "Tukar reward: Tumbler" | + +Setiap mutasi **masuk** membuat satu atau lebih lot. Setiap mutasi **keluar** mencatat +alokasi ke lot yang dipakai. Dengan begitu jejak bisa ditelusuri di dua tingkat: + +**Per mutasi** (lewat `reference_*`): +- **EnakPoint yang dipakai bayar:** `PAYMENT` → `payments` → order, outlet, kasir, dan + nominal rupiah yang ditutup. +- **EnakPoint yang kembali:** `PAYMENT_REFUND` → `PAYMENT` asal → order. +- **Saldo yang masuk lewat transfer:** `TRANSFER_IN` → baris `TRANSFER_OUT` pengirim. +- **EnakPoint hasil tukar:** `EXCHANGE_IN` → `EXCHANGE_OUT` (EnakCoin). +- **Earning yang ditarik:** `EARN_REVERSAL` → `EARN` asal → order. +- **Saldo yang hangus:** `EXPIRE` → lot → mutasi masuk yang membuat lot tersebut. + +**Per butir** (lewat `wallet_lot_allocations` dan `origin_lot_id`): dari pengurangan +mana pun, lihat lot yang terpakai, lalu ikuti `origin_lot_id` ke belakang melewati +transfer, exchange, atau refund, sampai ke lot pertama yang dibuat oleh `EARN`, +`ADJUSTMENT`, atau `MIGRATION`. + +**`description` dibekukan saat dibuat.** Nama outlet, nomor order, atau nama penerima +yang berubah belakangan tidak mengubah riwayat. Prinsipnya sama seperti snapshot harga +di `order_items`. Nama penerima/pengirim disamarkan di `description`. Nama lengkap hanya +terlihat oleh admin lewat `counterparty_customer_id`. + +--- + +## 9. API (Usulan) + +### Customer app (`/customer`, `CustomerAuthMiddleware`) + +| Method | Path | Keterangan | +|---|---|---| +| GET | `/wallet` | Saldo, nilai rupiah EnakPoint, saldo yang akan kedaluwarsa terdekat, mutasi terakhir (menggantikan `/points`, `/tokens`) | +| GET | `/wallet/transactions` | Riwayat, pagination & filter | +| GET | `/wallet/expiring` | Rincian saldo yang akan kedaluwarsa per tanggal | +| POST | `/wallet/payment-code` | `{ "pin" }` → kode bayar EnakPoint sekali pakai `{ "code", "qr", "expires_at" }` | +| GET | `/wallet/exchange/preview?coins=` | Kurs saat ini dan EnakPoint yang akan didapat | +| POST | `/wallet/exchange` | `{ "coins": 50, "pin": "..." }` | +| GET | `/wallet/transfer/recipient?phone=` | Cek penerima, mengembalikan nama tersamar | +| POST | `/wallet/transfer` | `{ "currency": "POINT", "amount": 100, "recipient_phone": "...", "pin": "..." }` | +| POST | `/orders/:id/pay-with-points` | Bayar order milik customer sendiri (self-order / app) → `{ "points": 50000, "pin": "..." }` | +| POST | `/spin` | Tetap, kini memotong EnakCoin. Tanpa PIN | +| GET | `/pin/status` | `{ "has_pin", "locked_until", "transfer_blocked_until" }` | +| POST | `/pin/otp` | Kirim OTP untuk `pin_setup` / `pin_reset` | +| POST | `/pin` | Buat PIN pertama: `{ "otp_code", "pin", "confirm_pin" }` | +| PUT | `/pin` | Ganti PIN: `{ "old_pin", "pin", "confirm_pin" }` | +| POST | `/pin/reset` | Lupa PIN: `{ "otp_code", "pin", "confirm_pin" }` | + +Semua endpoint yang menerima `pin` mengembalikan error yang bisa dibedakan oleh +aplikasi: `PIN_NOT_SET`, `PIN_INVALID` (beserta sisa percobaan), `PIN_LOCKED` (beserta +`locked_until`), dan `TRANSFER_BLOCKED` (beserta `transfer_blocked_until`). + +Endpoint `/points` dan `/tokens` dipertahankan sementara sebagai alias yang membaca +dari `customer_wallets`, lalu dihapus setelah aplikasi diperbarui. + +### POS / Dashboard (`/api/v1`) + +| Method | Path | Role | Keterangan | +|---|---|---|---| +| GET | `/orders/:id/point-payment/preview` | Kasir | `maks_point`, nilai EnakPoint, nominal rupiah untuk customer order | +| POST | `/orders/:id/payments` | Kasir | Endpoint pembayaran yang sudah ada. Untuk method EnakPoint, body membawa `{ "points": 50000, "payment_code": "482913" }` | +| GET/PUT | `/outlets/:id/loyalty-settings` | Admin/Manager | F1 | +| GET/PUT | `/marketing/loyalty-settings` | Admin/Manager | F2 dan F12 (nilai EnakPoint, kurs, transfer, kedaluwarsa) | +| GET | `/marketing/loyalty-settings/history` | Admin/Manager | Riwayat perubahan setting | +| GET | `/marketing/customers/:id/wallet` | Admin/Manager | Saldo, lot aktif, mutasi | +| GET | `/marketing/wallet-transactions/:id/trace` | Admin/Manager | Telusuri per butir: alokasi lot dan rantai `origin_lot_id` | +| POST | `/marketing/customers/:id/wallet/adjust` | Admin/Manager | `{ "currency", "amount", "reason" }` | +| DELETE | `/marketing/customers/:id/pin` | Admin/Manager | Hapus PIN customer: `{ "reason" }` | +| GET | `/marketing/customers/:id/security-events` | Admin/Manager | Log keamanan PIN | + +Payment method bertipe `point` ditolak di endpoint pembayaran jika: outlet tidak +menerima EnakPoint, order tanpa customer atau walk-in, kode bayar salah/kedaluwarsa/ +milik customer lain, atau `points` di luar batas F9. + +--- + +## 10. Migrasi dari Token + +1. Buat `customer_wallets`, `wallet_transactions`, `wallet_lots`, + `wallet_lot_allocations`, dan `loyalty_setting_changes`. +2. Salin saldo: + - `point_balance` diisi dari `customer_points.balance`. + - `coin_balance` diisi dari **jumlah seluruh jenis** `customer_tokens.balance` milik + customer tersebut (Q6, diputuskan). Contoh: SPIN 5 + RAFFLE 2 + MINIGAME 1 = + 8 EnakCoin. Rincian saldo per jenis disimpan di `metadata` baris ledger + `MIGRATION`, supaya asal saldo awal tetap bisa ditelusuri. +3. Tulis satu baris ledger `MIGRATION` dan satu lot (tanpa tanggal kedaluwarsa) per + customer per currency yang saldonya > 0, supaya rekonsiliasi (§7.5) langsung + berlaku. +4. `campaigns.type` / `campaign_rules.reward_type`: nilai `TOKENS` diganti `COINS`. +5. Tambah tipe `point` ke `payment_methods`, lalu buat payment method sistem + "EnakPoint" untuk setiap organisasi. Tambah kolom `points_used` / `point_value` ke + `payments`. +6. Tambah kolom PIN ke `customers` dan tabel `customer_security_events`. Semua customer + yang sudah ada mulai tanpa PIN, dan akan diminta membuatnya lewat OTP saat pertama + kali transfer, membayar, atau exchange. +7. `customer_points` dan `customer_tokens` dibiarkan read-only selama satu rilis, lalu + di-drop di migrasi berikutnya. + +--- + +## 11. Di Luar Scope + +- **Penukaran reward dengan EnakPoint.** Katalog reward sudah ada. Alurnya akan dibahas + di PRD terpisah dan memakai tipe ledger `REWARD_REDEEM`. +- **Tier otomatis** berdasarkan EnakPoint. Dibahas di PRD terpisah (lihat Q8 untuk + arahannya). +- **Eksekusi campaign rules** (bonus/multiplier) di atas earning dasar outlet. +- **Earning untuk order tanpa customer terdaftar** (klaim belakangan lewat struk/QR). + +--- + +## 12. Pertanyaan & Catatan + +### 12.1 Sudah Diputuskan + +| # | Pertanyaan | Keputusan | Tercermin di | +|---|---|---|---| +| Q1 | Basis earning: sebelum atau sesudah pajak/service charge? | **Sebelum pajak** (`subtotal − discount`) | F1 | +| Q2 | Apakah earning dari self-order (QR meja) diperlakukan sama? | **Ya**, semua kanal sama selama order punya customer | F3 | +| Q3 | Saat reversal earning dan saldo tidak cukup: tarik sampai 0, izinkan saldo negatif, atau blokir refund? | **Tarik sampai 0 dan catat shortfall.** Refund tidak diblokir | F10 | +| Q4 | Batas transfer diatur per organisasi atau global? Perlu limit harian? | **Per organisasi**, default tanpa batas | F2, F5 | +| Q5 | Konfirmasi transfer pakai password, PIN khusus, atau OTP? | **PIN customer 6 digit**, juga untuk pembayaran dan exchange | K8, F11 | +| Q6 | Saldo Token `RAFFLE`/`MINIGAME` yang ada ikut dikonversi ke EnakCoin? | **Ya**, semua jenis dijumlahkan menjadi EnakCoin. EnakCoin adalah mata uang untuk semua game | K1, F8, §10 | +| Q7 | Customer app melayani satu organisasi atau banyak? | **Satu nomor telepon = satu customer di satu organisasi**, sesuai `customers.phone_number` yang unik secara global | K4 | +| Q8 | Bagaimana tier (level keanggotaan, mis. Silver/Gold; tabel `tiers` sudah ada tapi belum terhubung ke customer) berhubungan dengan EnakPoint? | **Dibahas di PRD terpisah.** Arahan untuk PRD itu: tier dihitung dari **total `EARN` dalam 12 bulan terakhir**, bukan dari saldo, supaya customer tidak turun tier karena memakai, mentransfer, atau kehilangan saldo karena kedaluwarsa, dan tier tidak bisa "dibeli" lewat transfer. Ledger di PRD ini sudah mencatat `EARN`, jadi tidak ada yang perlu diubah di sini | §11 | +| Q9 | Jejak cukup per mutasi, atau harus per butir? | **Per butir**, lewat lot. EnakPoint dan EnakCoin **bisa kedaluwarsa**, dengan masa berlaku yang diatur sendiri | K9, F12, §8 | +| Q10 | Apakah bagian order yang dibayar EnakPoint tetap menghasilkan earning? | **Tidak.** Basis earning dikurangi nominal EnakPoint | F1 | +| Q11 | Berapa nilai rupiah 1 EnakPoint, dan kurs EnakCoin → EnakPoint? | **1 EnakPoint = Rp 1** dan **1 EnakCoin = 1 EnakPoint** sebagai default. Keduanya bisa diubah di setting | K3, F2, F4 | +| Q13 | Refund sebagian yang tidak habis dibagi nilai EnakPoint: sisa rupiahnya ke mana? | **Dibulatkan ke bawah**, sisanya hangus | F9 | +| Q16 | Setelah reset PIN, berapa lama transfer keluar ditahan? | **24 jam, hanya transfer.** Pembayaran dan exchange tetap bisa | F11 | +| Q17 | Parameter kunci PIN? | **5 kali salah, terkunci 30 menit** | F11 | + +### 12.2 Masih Terbuka + +Tidak ada. Semua hal yang belum diputuskan sudah dipindahkan ke catatan N1–N4 di +bawah, masing-masing dengan batas waktu. + +### 12.3 Ditunda (Catatan agar Tidak Lupa) + +Hal-hal berikut sengaja belum diputuskan. Masing-masing punya batas waktu, yaitu fase +yang tidak boleh dirilis sebelum catatan ini ditutup. + +**N1 — Pembayaran EnakPoint di kasir untuk customer tanpa aplikasi** (sebelumnya Q12) +- **Situasi:** persetujuan pembayaran di kasir saat ini hanya lewat kode bayar dari + aplikasi (F9). Customer yang tidak punya aplikasi, HP-nya mati, atau tidak ada + internet belum bisa membayar dengan EnakPoint di kasir. +- **Batasan yang harus tetap dijaga:** PIN tidak boleh diketik di layar kasir (K8). +- **Opsi yang sudah terpikir:** PIN pad atau layar yang menghadap customer; OTP ke + nomor telepon (butuh HP tapi tidak butuh aplikasi); atau memang tidak didukung. +- **Batas waktu:** tidak memblokir fase 3. Fase 3 bisa rilis tanpa jalur ini, tetapi + kasir perlu tahu apa yang harus dikatakan ke customer tanpa aplikasi. +- **Pemilik keputusan:** product owner. + +**N2 — Perlakuan akuntansi EnakPoint dan EnakCoin** (sebelumnya Q14) +- **Situasi:** EnakPoint yang dipakai membayar bukan kas masuk. Saldo yang beredar + berpotensi menjadi kewajiban. Saldo yang kedaluwarsa (F12) menjadi "breakage" yang + juga perlu dicatat. +- **Yang perlu diputuskan:** apakah EnakPoint yang dipakai dicatat sebagai beban + promosi atau pengurang liabilitas loyalitas; apakah saldo beredar dicatat sebagai + liabilitas; bagaimana breakage dari kedaluwarsa dicatat; apakah EnakCoin (yang bisa + ditukar ke EnakPoint, K3) ikut dihitung; dan apakah perlu jurnal otomatis ke modul + chart of account yang sudah ada. +- **Dampak ke sistem:** laporan payment method, laporan penjualan (penjualan kotor vs + kas masuk), dan kemungkinan jurnal otomatis. +- **Batas waktu:** sebelum fase 3 (pembayaran EnakPoint) dirilis ke outlet pertama. +- **Pemilik keputusan:** tim keuangan. + +**N3 — Tinjauan regulasi uang elektronik** (sebelumnya Q15) +- **Situasi:** EnakPoint bernilai rupiah, bisa dipakai membayar, dan bisa ditransfer + antar customer. Kombinasi ini mirip dengan uang elektronik yang diatur Bank + Indonesia. +- **Mitigasi yang sudah ada di desain:** tidak bisa ditunaikan (K7), hanya berlaku di + outlet dalam organisasi yang sama (K4), tampilan "setara potongan", bukan "saldo + rupiah", dan bisa kedaluwarsa (F12). +- **Yang perlu dicek ke legal:** apakah fitur transfer (F5) masih aman; apakah perlu + batas transfer wajib (F2); dan apa yang harus ada di Syarat & Ketentuan. +- **Batas waktu:** sebelum fase 3 (pembayaran) dan fase 4 (transfer) dirilis. +- **Pemilik keputusan:** legal. + +**N4 — Model kedaluwarsa saldo** +- **Situasi:** sudah diputuskan bahwa EnakPoint dan EnakCoin bisa kedaluwarsa dan + owner bisa mengatur sendiri (Q9). Yang belum diputuskan adalah **modelnya**. +- **Pilihan:** + + | | A. Tanggal tetap (gaya Telkomsel POIN / XL Poin) | B. Per saldo masuk (draft F12 saat ini) | + |---|---|---| + | Cara kerja | Semua saldo hangus di tanggal yang sama, mis. tiap 31 Des (1× setahun) atau tiap 30 Jun & 31 Des (2× setahun) | Tiap saldo punya tanggal sendiri, mis. 12 bulan sejak didapat | + | Mudah dipahami customer | Sangat mudah: "semua hangus 31 Desember" | Lebih rumit: "150 hangus 3 Okt, 200 hangus 18 Nov" | + | Pengingat | Satu kampanye besar menjelang tanggal hangus | Banyak pengingat kecil | + | Adil | Kurang. Saldo yang didapat sehari sebelum tanggal hangus langsung hilang. Bisa ditutup dengan **periode tanggung**, mis. saldo yang didapat < 3 bulan sebelum tanggal hangus ikut ke tanggal hangus berikutnya | Adil. Semua saldo punya umur yang sama | + | Efek bisnis | Lonjakan belanja menjelang tanggal hangus | Lebih rata | + +- **Pilihan ketiga:** keduanya didukung sebagai mode di setting, dan owner memilih. + Ini tidak mengubah struktur data. Lot, alokasi, dan `EXPIRE` tetap sama. Yang berbeda + hanya rumus `expires_at` saat lot dibuat: + - A: tanggal hangus berikutnya setelah (tanggal didapat + periode tanggung) + - B: tanggal didapat + masa berlaku +- **Usulan sementara (belum disetujui):** dukung keduanya, dengan default model A + setahun sekali tiap 31 Desember dan periode tanggung 3 bulan, karena model ini sudah + familiar bagi customer di Indonesia. +- **Pertanyaan turunan yang ikut diputuskan bersama N4:** + - Saat kedaluwarsa pertama kali diaktifkan, bagaimana dengan saldo lama yang belum + punya tanggal kedaluwarsa? Usulan: diberi masa berlaku penuh sejak tanggal aktivasi + (model B), atau ikut tanggal hangus kedua berikutnya (model A). + - EnakPoint yang dikembalikan karena refund, padahal lot asalnya sudah atau hampir + kedaluwarsa? Usulan: diberi masa berlaku minimal 7 hari sejak refund. + - Saat kedaluwarsa dinonaktifkan, apakah saldo yang sudah terjadwal kedaluwarsa ikut + dibatalkan? Usulan: tidak, hanya saldo baru yang tidak kedaluwarsa. + - Pengingat dikirim berapa hari sebelum tanggal hangus, dan berapa kali? +- **Dampak ke sistem:** tabel pengaturan di F12, rumus kedaluwarsa per lot, isi + pengingat, dan tampilan "saldo yang akan kedaluwarsa" di aplikasi. +- **Batas waktu:** sebelum fase 5 (kedaluwarsa) dikerjakan. Fase 1–4 tidak terblokir, + karena lot sudah dibuat sejak fase 1 dan dipakai oleh kedua model. +- **Pemilik keputusan:** product owner. + +--- + +## 13. Tahapan Rilis + +| Fase | Isi | Syarat rilis | +|---|---|---| +| **1. Fondasi** | Tabel wallet, ledger, dan lot; migrasi Token → EnakCoin; repository transaksional; endpoint saldo & riwayat; adjustment admin; riwayat perubahan setting | – | +| **2. Earning** | Setting outlet (F1), earning saat order lunas (F3), reversal (F10), `points_earned`/`coins_earned` di response order | – | +| **3. Pembayaran EnakPoint** | PIN customer (F11), setting organisasi (F2), payment method EnakPoint, kode bayar, bayar di kasir & app (F9), refund EnakPoint, laporan payment method | N2 dan N3 ditutup | +| **4. Pergerakan saldo** | Exchange dengan kurs (F4), transfer (F5), semua game memakai EnakCoin (F8), telusuri per butir di dashboard | N3 ditutup | +| **5. Kedaluwarsa** | Setting kedaluwarsa (F12), job kedaluwarsa, pengingat, tampilan saldo yang akan kedaluwarsa | N4 ditutup | +| **6. Lanjutan** | Penukaran reward, tier (Q8), campaign rules | – | + +Lot sudah dibuat sejak fase 1, meskipun kedaluwarsa baru aktif di fase 5. Kalau lot +baru ditambahkan belakangan, seluruh riwayat alokasi harus direkonstruksi ulang dari +ledger. + +--- + +## 14. Metrik Keberhasilan + +- 0 selisih pada job rekonsiliasi: ledger vs saldo vs lot, alokasi vs mutasi, dan + pembayaran EnakPoint vs ledger. +- 0 mutasi tanpa asal/tujuan (dijamin oleh constraint, tetapi diverifikasi di job + rekonsiliasi). +- 0 earning ganda per order, 0 pemotongan ganda per pembayaran, dan 0 kedaluwarsa ganda + per lot (dicek dari idempotency key). +- 0 refund non-EnakPoint atas pembayaran EnakPoint (dicek dari job rekonsiliasi). +- 0 lot yang lewat tanggal kedaluwarsa lebih dari 1 jam tanpa diproses. +- Persentase order lunas dengan customer terdaftar yang mendapat earning (target: 100% + untuk outlet dengan setting aktif). +- Persentase transaksi yang dibayar (sebagian) dengan EnakPoint, dan total nilai + rupiahnya per bulan. +- Jumlah EnakPoint/EnakCoin yang kedaluwarsa per bulan, dan persentase customer yang + memakai saldonya setelah menerima pengingat. +- Volume exchange dan transfer per minggu sebagai indikator adopsi. diff --git a/docs/tasks-point-coin.md b/docs/tasks-point-coin.md new file mode 100644 index 0000000..1129ad6 --- /dev/null +++ b/docs/tasks-point-coin.md @@ -0,0 +1,438 @@ +# Task Breakdown: EnakPoint & EnakCoin + +**Sumber:** [PRD EnakPoint & EnakCoin](prd-point-coin.md) +**Tanggal:** 2026-09-29 + +Setiap task menyebut bagian PRD yang dikerjakan, lapisan kode yang disentuh, task yang +harus selesai lebih dulu, dan kriteria selesai. Ukuran: **S** ≤ 1 hari, **M** 2–3 hari, +**L** 4–5 hari. + +Konvensi kode mengikuti yang sudah ada: `migrations/` (lanjut dari `000089`), +`entities` → `repository` → `processor` → `service` → `handler` / `validator` → +`router`, dan wiring di `internal/app/app.go`. + +--- + +## Ringkasan + +| Fase | Task | Terblokir oleh catatan PRD | +|---|---|---| +| 1. Fondasi | PC-101 – PC-109 | – | +| 2. Earning | PC-201 – PC-205 | – | +| 3. Pembayaran EnakPoint | PC-301 – PC-308 | N2 (keuangan), N3 (legal) sebelum **rilis** | +| 4. Pergerakan saldo | PC-401 – PC-404 | N3 (legal) sebelum **rilis** | +| 5. Kedaluwarsa | PC-501 – PC-504 | N4 (model kedaluwarsa) sebelum **dikerjakan** | +| 6. Bersih-bersih | PC-601 – PC-602 | – | + +Catatan N2 dan N3 hanya memblokir **rilis** fase 3–4, bukan pengerjaannya. N4 +memblokir pengerjaan fase 5, karena rumus kedaluwarsanya belum ditentukan. + +``` +PC-101 ─┬─ PC-103 ── PC-104 ─┬─ PC-105 ── PC-106 + │ ├─ PC-107 + │ ├─ PC-108 + │ ├─ PC-203 ── PC-204 ── PC-205 + │ ├─ PC-305 ── PC-306 / PC-307 + │ ├─ PC-401 / PC-402 / PC-403 / PC-404 + │ └─ PC-502 ── PC-503 +PC-102 ── PC-109 ─┬─ PC-201 ── PC-202 ── PC-203 + └─ PC-302 +PC-301 ── PC-304 ── PC-305 +PC-303 ── PC-305 +``` + +--- + +## Fase 1 — Fondasi + +Semua fase lain bergantung pada fase ini. **PC-104 (wallet engine) adalah inti.** Tidak +ada kode lain yang boleh mengubah saldo tanpa lewat engine ini. + +### PC-101 · Migrasi tabel wallet, ledger, dan lot · M +- **PRD:** §8 (`customer_wallets`, `wallet_transactions`, `wallet_lots`, + `wallet_lot_allocations`), K5, K9 +- **Kerjakan:** migrasi `000090_create_wallet_tables` (up & down) dengan semua + `CHECK` constraint dan index persis seperti di §8. +- **Selesai jika:** + - Up dan down berjalan bersih di database kosong dan di salinan staging. + - Uji constraint langsung di SQL, masing-masing harus ditolak: + `PAYMENT` bercurrency `COIN`; `TRANSFER_IN` tanpa `counterparty_customer_id`; + `EARN_REVERSAL` tanpa `reverses_transaction_id`; `ADJUSTMENT` tanpa `reason`; + `EXPIRE` dengan `reference_type` selain `LOT`; saldo negatif; lot dengan + `remaining_amount > original_amount`. +- **Bergantung pada:** – + +### PC-102 · Migrasi pengaturan organisasi dan riwayat perubahan setting · S +- **PRD:** F2, `loyalty_setting_changes` di §8 +- **Kerjakan:** tabel `organization_settings` (key–value, pola sama dengan + `outlet_settings`, `UNIQUE(organization_id, key)`) dan `loyalty_setting_changes`. + Saat ini belum ada tempat menyimpan setting per organisasi. +- **Selesai jika:** up/down bersih. +- **Bergantung pada:** – + +### PC-103 · Entities dan repository wallet · M +- **PRD:** §7.1–§7.4 +- **Kerjakan:** + - Entities untuk empat tabel PC-101. + - Repository yang **selalu** memakai `DBFromContext` (berbeda dari repository + gamification yang sekarang memakai `r.db` langsung). + - `LockWallet(ctx, customerID)` dengan `SELECT … FOR UPDATE`. Membuat baris wallet + jika belum ada (`INSERT … ON CONFLICT DO NOTHING`, lalu lock). + - `LockWallets(ctx, a, b)` yang selalu mengunci berurutan berdasarkan `customer_id`. + - Update saldo bersyarat yang **mengembalikan error jika 0 baris ter-update**. + - Query lot aktif sesuai urutan K9: `expires_at NULLS LAST, created_at`. +- **Selesai jika:** test repository menunjukkan update bersyarat gagal saat saldo + kurang, dan dua goroutine yang mengunci wallet yang sama berjalan bergantian. +- **Bergantung pada:** PC-101 + +### PC-104 · Wallet engine (credit / debit / lot / idempotensi) · L +- **PRD:** K5, K6, K9, §7, §8.1 +- **Kerjakan:** processor `WalletProcessor` sebagai **satu-satunya pintu** perubahan + saldo: + - `Credit(ctx, CreditInput)`: menulis ledger, membuat lot (dengan `expires_at` dan + `origin_lot_id` dari input), dan menambah saldo. + - `Debit(ctx, DebitInput)`: mengambil dari lot sesuai urutan K9 (atau dari lot + tertentu lebih dulu, untuk reversal di F10), menulis alokasi dan ledger, lalu + mengurangi saldo. Mengembalikan daftar alokasi, supaya transfer/exchange bisa + membuat lot penerima dengan `expires_at` yang sama. + - `DebitUpTo`: mengambil sebanyak yang tersedia, untuk reversal dengan shortfall + (F10, Q3). + - Idempotensi: jika `idempotency_key` sudah ada, kembalikan hasil pertama tanpa + mutasi baru. + - Validasi di level kode untuk aturan §8.1 (tipe ↔ currency ↔ referensi wajib), + sebagai lapisan kedua di atas constraint database. + - Semua method mewajibkan caller sudah berada di dalam transaksi dan wallet sudah + dikunci. +- **Selesai jika:** unit test mencakup debit yang melewati beberapa lot, urutan lot + dengan dan tanpa `expires_at`, debit melebihi saldo (ditolak), `DebitUpTo` dengan + shortfall, idempotency key ganda, dan saldo = `SUM(ledger)` = `SUM(lot.remaining)` + setelah setiap skenario. +- **Bergantung pada:** PC-103 + +### PC-105 · Migrasi data Point & Token lama · M +- **PRD:** §10, Q6 +- **Kerjakan:** migrasi data (atau command satu kali) yang: + - Membuat wallet dari `customer_points` dan penjumlahan semua jenis + `customer_tokens`. + - Menulis ledger `MIGRATION` dan lot tanpa `expires_at` per customer per currency, + dengan rincian per jenis token di `metadata`. + - Mengganti `TOKENS` menjadi `COINS` di `campaigns.type` dan + `campaign_rules.reward_type`. +- **Selesai jika:** jumlah total Point dan Token sebelum = jumlah total saldo wallet + sesudah (diuji pada salinan data staging), dan migrasi aman dijalankan dua kali + (tidak menggandakan). +- **Bergantung pada:** PC-104 + +### PC-106 · Endpoint saldo & riwayat customer · M +- **PRD:** F6, §9 (customer app) +- **Kerjakan:** `GET /customer/wallet` dan `GET /customer/wallet/transactions` + (pagination, filter currency/tipe/tanggal). Ganti isi `/customer/points` dan + `/customer/tokens` menjadi alias yang membaca `customer_wallets`. Hapus pemakaian + `customer_points_repository` untuk saldo. +- **Selesai jika:** response menampilkan asal/tujuan setiap mutasi sesuai §8.1, dan + aplikasi lama yang memanggil `/points` / `/tokens` tetap mendapat angka yang benar. +- **Bergantung pada:** PC-105 + +### PC-107 · Wallet customer dan adjustment di dashboard · M +- **PRD:** F7 +- **Kerjakan:** `GET /marketing/customers/:id/wallet` (saldo, lot aktif, mutasi) dan + `POST /marketing/customers/:id/wallet/adjust` (alasan wajib, tidak boleh membuat saldo + negatif, tercatat `created_by_user`). +- **Selesai jika:** adjustment muncul di riwayat customer dengan nama admin dan alasan. + Adjustment yang melebihi saldo ditolak. +- **Bergantung pada:** PC-104 + +### PC-108 · Job rekonsiliasi · S +- **PRD:** §7.5 +- **Kerjakan:** query dan job terjadwal yang memeriksa semua invarian §7.5 dan + melaporkan selisih ke log dan notifikasi admin. +- **Selesai jika:** job menemukan selisih yang sengaja dibuat di data test, dan diam + saat data konsisten. +- **Bergantung pada:** PC-104 + +### PC-109 · Pembaca setting loyalitas dan riwayat perubahan · M +- **PRD:** F1, F2 (bagian mekanisme, bukan UI), §8 `loyalty_setting_changes` +- **Kerjakan:** service yang membaca setting outlet dan organisasi dengan nilai default + PRD bila key belum diisi, mengembalikan struct bertipe (bukan string mentah), dan + menulis `loyalty_setting_changes` setiap kali setting loyalitas diubah. +- **Selesai jika:** outlet tanpa setting mendapat semua default PRD, dan setiap + perubahan tercatat nilai lama, nilai baru, dan pelakunya. +- **Bergantung pada:** PC-102 + +--- + +## Fase 2 — Earning + +### PC-201 · API pengaturan loyalitas outlet · M +- **PRD:** F1 +- **Kerjakan:** `GET/PUT /outlets/:id/loyalty-settings` dengan validasi F1. Response + menyertakan **persentase cashback efektif** (`earn_value × nilai EnakPoint / + earn_per_amount`). +- **Selesai jika:** validasi menolak nilai di luar batas, dan hanya Admin/Manager yang + bisa mengubah. +- **Bergantung pada:** PC-109 + +### PC-202 · Kalkulator earning · S +- **PRD:** F1 (rumus), Q1, Q10 +- **Kerjakan:** fungsi murni `CalculateEarning(order, pointPaidAmount, settings)` yang + mengembalikan Point, Coin, basis, dan snapshot setting. +- **Selesai jika:** unit test mencakup contoh di PRD (Rp 87.500 → 875 Point, 3 Coin; + dengan Rp 20.000 dibayar EnakPoint → 675 Point, 2 Coin), basis di bawah minimum, + `max_per_order`, setting nonaktif, dan pajak tidak ikut dihitung. +- **Bergantung pada:** PC-201 + +### PC-203 · Earning saat order lunas · L +- **PRD:** F3 +- **Kerjakan:** + - **Satukan titik "order menjadi lunas".** Saat ini `payment_status = completed` + di-set di empat tempat: `OrderProcessorImpl.UpdateOrder`, + `OrderProcessorImpl.updateOrderStatus`, dan dua tempat di `split_bill_processor.go`. + Buat satu hook `onOrderPaid(orderID)` yang dipanggil dari keempatnya. + - Hook menjalankan earning **setelah** transaksi pembayaran commit, sehingga + kegagalan earning tidak menggagalkan pembayaran. + - Idempotency key `earn:{order_id}:{currency}`. + - Lewati order tanpa customer, customer default, atau customer nonaktif. + - **Jaring pengaman:** job yang mencari order lunas beberapa hari terakhir yang belum + punya `EARN` (dan seharusnya punya), lalu menjalankan ulang earning. +- **Selesai jika:** test untuk pembayaran penuh, split bill (lunas di pembayaran + terakhir), self-order, dan pemanggilan ganda (hasilnya tetap satu earning). Earning + yang sengaja digagalkan tidak menggagalkan pembayaran dan terambil oleh job. +- **Bergantung pada:** PC-104, PC-202 + +### PC-204 · Reversal earning saat void / refund · M +- **PRD:** F10, Q3 +- **Kerjakan:** panggil reversal dari `VoidOrder`, `RefundOrder`, dan `RefundPayment`. + Ambil pertama dari lot `EARN` order tersebut, lalu lot lain. Gunakan `DebitUpTo` dan + catat `shortfall`. Refund tidak pernah diblokir. +- **Selesai jika:** test untuk void penuh, refund sebagian (proporsional, akumulasi tidak + melebihi earning), dan saldo yang sudah terpakai (shortfall tercatat, saldo 0). +- **Bergantung pada:** PC-203 + +### PC-205 · Tampilkan earning di order dan struk · S +- **PRD:** F3 +- **Kerjakan:** tambah `points_earned` dan `coins_earned` ke response order dan data + struk. +- **Selesai jika:** nilai sama dengan baris `EARN` di ledger, dan bernilai 0 untuk order + tanpa earning. +- **Bergantung pada:** PC-203 + +--- + +## Fase 3 — Pembayaran EnakPoint + +> Boleh dikerjakan sekarang. **Tidak boleh dirilis** sebelum catatan N2 (keuangan) dan +> N3 (legal) ditutup. + +### PC-301 · PIN customer · L +- **PRD:** K8, F11, Q16, Q17 +- **Kerjakan:** + - Migrasi kolom PIN di `customers` dan tabel `customer_security_events`. + - Purpose OTP baru `pin_setup` dan `pin_reset` di `OtpProcessor`. + - Endpoint `/customer/pin/*` (status, OTP, buat, ganti, reset). + - Hash bcrypt, tolak PIN lemah (digit sama, berurutan, tanggal lahir). + - Kunci 30 menit setelah 5 kali salah, dengan penghitung di database. + - Tahan transfer keluar 24 jam setelah reset. + - `VerifyPin(ctx, customerID, pin)` untuk dipakai task lain, dengan error + `PIN_NOT_SET`, `PIN_INVALID`, `PIN_LOCKED`, `TRANSFER_BLOCKED`. + - Hapus PIN oleh admin: `DELETE /marketing/customers/:id/pin`, dan + `GET /marketing/customers/:id/security-events`. + - PIN tidak pernah muncul di log (termasuk log request body). +- **Selesai jika:** test untuk semua aturan di atas, termasuk 5 kali salah lalu PIN + benar tetap ditolak selama terkunci, dan reset OTP membuka kunci. +- **Bergantung pada:** – + +### PC-302 · API pengaturan loyalitas organisasi · S +- **PRD:** F2 +- **Kerjakan:** `GET/PUT /marketing/loyalty-settings` untuk nilai EnakPoint, kurs + exchange, dan batas transfer, serta `GET /marketing/loyalty-settings/history`. + Sebelum menyimpan perubahan nilai EnakPoint atau kurs, response preview menampilkan + total saldo beredar dan nilai rupiahnya sebelum/sesudah. +- **Selesai jika:** perubahan tercatat di riwayat, dan transaksi lama tetap memakai nilai + yang dibekukan. +- **Bergantung pada:** PC-109 + +### PC-303 · Payment method EnakPoint · M +- **PRD:** F9 (payment method), §8 (perubahan `payments`), §10.5 +- **Kerjakan:** + - Tambah tipe `point` ke `PaymentMethodType` dan validator (`oneof=cash card + digital_wallet point`). + - Migrasi kolom `points_used` dan `point_value` di `payments`. + - Buat payment method sistem "EnakPoint" untuk setiap organisasi yang sudah ada, dan + otomatis untuk organisasi baru. + - Tolak hapus / ubah tipe method sistem. + - Sembunyikan method ini di kasir jika outlet tidak mengaktifkan `accept_payment`. +- **Selesai jika:** setiap organisasi punya tepat satu method EnakPoint yang tidak bisa + dihapus. +- **Bergantung pada:** – + +### PC-304 · Kode bayar sekali pakai · M +- **PRD:** F9 (persetujuan customer), K8 +- **Kerjakan:** `POST /customer/wallet/payment-code` (butuh PIN) menghasilkan kode 6 + digit dan QR yang berlaku 2 menit, disimpan di Redis dengan TTL dan diambil + sekali-pakai (`GETDEL`). Kode terikat ke `customer_id`. +- **Selesai jika:** kode kedaluwarsa, kode yang sudah dipakai, dan kode milik customer + lain semuanya ditolak. +- **Bergantung pada:** PC-301 + +### PC-305 · Bayar EnakPoint di kasir · L +- **PRD:** F9 (perhitungan, pencatatan), K7 +- **Kerjakan:** + - `GET /orders/:id/point-payment/preview`. + - Cabang method `point` di `CreatePayment`: validasi kode bayar, cocokkan customer + order, hitung `maks_point`, lalu lakukan langkah 1–6 F9 dalam **satu transaksi** + bersama pembuatan baris `payments`. + - Idempotency `payment:{payment_id}`. + - Tolak jika `nominal_rupiah > remaining_amount` (tidak ada kembalian). +- **Selesai jika:** test untuk pembayaran penuh, sebagian + tunai (split), batas + `max_payment_percent`, order walk-in (ditolak), kode salah (ditolak), dan dua + pembayaran bersamaan untuk customer yang sama (saldo tidak terpakai dua kali). + Earning (PC-203) menghitung basis tanpa bagian EnakPoint. +- **Bergantung pada:** PC-104, PC-303, PC-304 + +### PC-306 · Bayar EnakPoint dari app / self-order · M +- **PRD:** F9 +- **Kerjakan:** `POST /customer/orders/:id/pay-with-points` (butuh PIN, hanya untuk + order milik customer itu sendiri), memakai logika yang sama dengan PC-305. +- **Selesai jika:** customer tidak bisa membayar order milik customer lain. +- **Bergantung pada:** PC-305 + +### PC-307 · Refund pembayaran EnakPoint · M +- **PRD:** F9 (void/refund), K7, Q13 +- **Kerjakan:** `PAYMENT_REFUND` di jalur void dan refund memakai `point_value` yang + dibekukan, dengan pembulatan ke bawah. Kembalikan ke lot dengan `expires_at` asal + (aturan perpanjangan 7 hari mengikuti N4, jadi untuk sekarang cukup pakai tanggal + asal). **Tolak** permintaan refund bagian EnakPoint lewat method lain. +- **Selesai jika:** test untuk void penuh, refund sebagian, perubahan nilai EnakPoint di + antara bayar dan refund (jumlah EnakPoint yang kembali tetap sama), dan percobaan + refund tunai atas pembayaran EnakPoint (ditolak). +- **Bergantung pada:** PC-305 + +### PC-308 · EnakPoint di laporan · S +- **PRD:** F9 (laporan) +- **Kerjakan:** laporan per payment method menampilkan EnakPoint terpisah dan tidak + menghitungnya sebagai kas masuk. Cek laporan analytics yang menjumlahkan pembayaran. +- **Selesai jika:** total kas masuk di laporan tidak berubah saat sebagian order dibayar + EnakPoint. Perlakuan akuntansi lanjutan menunggu N2. +- **Bergantung pada:** PC-305 + +--- + +## Fase 4 — Pergerakan Saldo + +> Boleh dikerjakan sekarang. Transfer (PC-402) **tidak boleh dirilis** sebelum N3 +> (legal) ditutup. + +### PC-401 · Exchange EnakCoin → EnakPoint · M +- **PRD:** F4, K3 +- **Kerjakan:** `GET /customer/wallet/exchange/preview` dan + `POST /customer/wallet/exchange` (butuh PIN, `Idempotency-Key`). Jumlah harus + kelipatan `coin_amount`. Kurs dibekukan di metadata. Lot EnakPoint kedaluwarsa pada + `min(lot EnakCoin asal, sekarang + masa berlaku EnakPoint)`. +- **Selesai jika:** test untuk kurs default 1:1, kurs 10:3, jumlah bukan kelipatan + (ditolak), dan `expires_at` lot hasil exchange tidak pernah lebih lama dari lot asal. +- **Bergantung pada:** PC-104, PC-301, PC-302 + +### PC-402 · Transfer antar customer · L +- **PRD:** F5, Q4, Q16 +- **Kerjakan:** `GET /customer/wallet/transfer/recipient` (nama disamarkan) dan + `POST /customer/wallet/transfer` (butuh PIN, `Idempotency-Key`). Kunci dua wallet + berurutan, cek batas organisasi (per transaksi dan harian), cek + `transfer_blocked_until`. Lot penerima mewarisi `expires_at` dan `origin_lot_id` dari + lot pengirim. Kirim notifikasi push ke penerima. +- **Selesai jika:** test untuk transfer ke diri sendiri / customer lain organisasi / + customer default (semua ditolak), batas harian, transfer dua arah bersamaan (tidak + deadlock), dan `expires_at` di penerima sama persis dengan pengirim. +- **Bergantung pada:** PC-104, PC-301, PC-302 + +### PC-403 · Semua game memakai EnakCoin · M +- **PRD:** F8, K1 +- **Kerjakan:** + - `GamePlayProcessor.PlayGame` memotong EnakCoin lewat wallet engine sesuai + `games.metadata.coin_cost`. + - Seluruh permainan dalam satu transaksi: ubah repository game, game play, dan game + prize ke `DBFromContext`. Gagal mengurangi stok hadiah membatalkan permainan (saat + ini hanya di-`Printf`), dan rollback manual `AddTokens` dihapus. + - Rename `game_plays.token_used` menjadi `coins_used`. +- **Selesai jika:** test untuk saldo kurang (ditolak, tidak ada `game_plays` yang + tercatat), stok hadiah gagal (semua dibatalkan), dan `GAME_SPEND` menunjuk + `game_plays.id`. +- **Bergantung pada:** PC-104 + +### PC-404 · Telusuri per butir di dashboard · S +- **PRD:** F7, §8.1 (per butir) +- **Kerjakan:** `GET /marketing/wallet-transactions/:id/trace` yang mengembalikan + alokasi lot dan rantai `origin_lot_id` sampai ke lot pertama. +- **Selesai jika:** contoh di §8 (A transfer 120 ke B, B bayar 30) menelusuri ke order + #ORD-1 milik A. +- **Bergantung pada:** PC-402 + +--- + +## Fase 5 — Kedaluwarsa + +> **Jangan dikerjakan sebelum catatan N4 (model kedaluwarsa) diputuskan.** Struktur lot +> sudah ada sejak PC-101, jadi yang tersisa hanya rumus, job, dan tampilan. + +### PC-501 · Setting kedaluwarsa · M +- **PRD:** F12 (pengaturan), N4 +- **Kerjakan:** key setting sesuai model yang dipilih di N4, dengan validasi dan preview + "saldo yang didapat hari ini kedaluwarsa pada …". +- **Bergantung pada:** PC-302, **N4** + +### PC-502 · Hitung `expires_at` saat lot dibuat · M +- **PRD:** F12 (tabel kedaluwarsa per lot), N4 +- **Kerjakan:** satu fungsi `ComputeExpiry(currency, receivedAt, settings)` yang dipakai + oleh `EARN` dan `ADJUSTMENT`, serta aturan aktivasi pertama untuk lot lama (termasuk + lot `MIGRATION`). +- **Bergantung pada:** PC-104, PC-501 + +### PC-503 · Job kedaluwarsa · M +- **PRD:** F12 (proses kedaluwarsa) +- **Kerjakan:** job per jam yang memproses lot lewat tanggal dengan `EXPIRE` + (idempotency `expire:{lot_id}`) di bawah lock wallet. + - **Jangan menyalin pola `OmsetMilestoneScheduler`.** Scheduler itu menyimpan state di + memori, dan menurut komentarnya sendiri bisa mengirim ulang notifikasi setelah + restart. Job ini harus aman dijalankan di banyak instance sekaligus: pilih lot + dengan `FOR UPDATE SKIP LOCKED`, dan andalkan idempotency key. +- **Selesai jika:** dua instance yang berjalan bersamaan tidak menghanguskan lot yang + sama dua kali, dan tidak ada lot yang lewat tanggal lebih dari 1 jam tanpa diproses. +- **Bergantung pada:** PC-502 + +### PC-504 · Pengingat dan tampilan saldo yang akan kedaluwarsa · M +- **PRD:** F6 (`/wallet/expiring`), F12 (pengingat) +- **Kerjakan:** endpoint `GET /customer/wallet/expiring`, field saldo kedaluwarsa + terdekat di `/wallet`, dan notifikasi pengingat yang dikelompokkan per tanggal. + Jadwal pengingat mengikuti N4. +- **Bergantung pada:** PC-503 + +--- + +## Fase 6 — Bersih-bersih + +### PC-601 · Hapus tabel dan kode lama · S +- **PRD:** §10.7 +- **Kerjakan:** satu rilis setelah PC-105 berjalan di production, drop + `customer_points` dan `customer_tokens`. Hapus `CustomerPointsProcessor` dan + `CustomerTokensProcessor` beserta stub `not implemented`, rute yang di-comment di + `router.go`, dan alias `/customer/points` / `/customer/tokens` setelah aplikasi + diperbarui. +- **Bergantung pada:** PC-106, PC-403, dan konfirmasi bahwa aplikasi sudah tidak + memanggil endpoint lama. + +### PC-602 · Dokumentasi integrasi · S +- **Kerjakan:** panduan integrasi untuk tim aplikasi dan POS (seperti + `integration-weight-based-products.md`): endpoint, kode error PIN, alur kode bayar, dan + contoh request/response. +- **Bergantung pada:** PC-305, PC-402 + +--- + +## Yang Bisa Dimulai Sekarang + +Bisa dikerjakan paralel tanpa menunggu apa pun: +- **PC-101** (migrasi wallet) → langsung lanjut **PC-103**, lalu **PC-104** +- **PC-102** (setting organisasi) → **PC-109** +- **PC-301** (PIN customer) +- **PC-303** (payment method EnakPoint) + +PC-104 adalah jalur kritis: hampir semua task lain menunggunya. diff --git a/internal/contract/order_contract.go b/internal/contract/order_contract.go index 4ce5f20..b95b492 100644 --- a/internal/contract/order_contract.go +++ b/internal/contract/order_contract.go @@ -121,7 +121,7 @@ type OrderItemResponse struct { Status string `json:"status"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` - PrinterType string `json:"printer_type"` + PrinterTypes []string `json:"printer_types"` PrintToChecker bool `json:"print_to_checker"` PaidQuantity int `json:"paid_quantity"` } diff --git a/internal/contract/product_contract.go b/internal/contract/product_contract.go index 90a90ea..f606dfd 100644 --- a/internal/contract/product_contract.go +++ b/internal/contract/product_contract.go @@ -16,7 +16,7 @@ type CreateProductRequest struct { Cost *float64 `json:"cost,omitempty" validate:"omitempty,min=0"` BusinessType *string `json:"business_type,omitempty"` ImageURL *string `json:"image_url,omitempty" validate:"omitempty,max=500"` - PrinterType *string `json:"printer_type,omitempty" validate:"omitempty,max=50"` + PrinterTypes []string `json:"printer_types,omitempty" validate:"omitempty,dive,max=50"` PrintToChecker *bool `json:"print_to_checker,omitempty"` UnitID *uuid.UUID `json:"unit_id,omitempty"` SellBy *string `json:"sell_by,omitempty" validate:"omitempty,oneof=unit weight"` @@ -38,7 +38,7 @@ type UpdateProductRequest struct { Cost *float64 `json:"cost,omitempty" validate:"omitempty,min=0"` BusinessType *string `json:"business_type,omitempty"` ImageURL *string `json:"image_url,omitempty" validate:"omitempty,max=500"` - PrinterType *string `json:"printer_type,omitempty" validate:"omitempty,max=50"` + PrinterTypes []string `json:"printer_types,omitempty" validate:"omitempty,dive,max=50"` // Replaces the whole list when sent PrintToChecker *bool `json:"print_to_checker,omitempty"` UnitID *uuid.UUID `json:"unit_id,omitempty"` SellBy *string `json:"sell_by,omitempty" validate:"omitempty,oneof=unit weight"` @@ -76,7 +76,7 @@ type ProductResponse struct { Cost float64 `json:"cost"` BusinessType string `json:"business_type"` ImageURL *string `json:"image_url"` - PrinterType string `json:"printer_type"` + PrinterTypes []string `json:"printer_types"` UnitID *uuid.UUID `json:"unit_id,omitempty"` SellBy string `json:"sell_by"` PrintToChecker bool `json:"print_to_checker"` diff --git a/internal/entities/product.go b/internal/entities/product.go index 22d3f6d..ef7901a 100644 --- a/internal/entities/product.go +++ b/internal/entities/product.go @@ -1,6 +1,7 @@ package entities import ( + "strings" "time" "github.com/google/uuid" @@ -8,24 +9,26 @@ import ( ) type Product struct { - ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"` - OrganizationID uuid.UUID `gorm:"type:uuid;not null;index" json:"organization_id" validate:"required"` - CategoryID uuid.UUID `gorm:"type:uuid;not null;index" json:"category_id" validate:"required"` - SKU *string `gorm:"size:100;index" json:"sku"` - Name string `gorm:"not null;size:255" json:"name" validate:"required,min=1,max=255"` - Description *string `gorm:"type:text" json:"description"` - Price float64 `gorm:"type:decimal(10,2);not null" json:"price" validate:"required,min=0"` - Cost float64 `gorm:"type:decimal(10,2);default:0.00" json:"cost" validate:"min=0"` - BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"` - ImageURL *string `gorm:"size:500" json:"image_url"` - PrinterType string `gorm:"size:50;default:'kitchen'" json:"printer_type"` - UnitID *uuid.UUID `gorm:"type:uuid;index" json:"unit_id"` - SellBy string `gorm:"size:20;default:'unit'" json:"sell_by"` - HasIngredients bool `gorm:"default:false" json:"has_ingredients"` - Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"` - IsActive bool `gorm:"default:true" json:"is_active"` - CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` - UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` + ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"` + OrganizationID uuid.UUID `gorm:"type:uuid;not null;index" json:"organization_id" validate:"required"` + CategoryID uuid.UUID `gorm:"type:uuid;not null;index" json:"category_id" validate:"required"` + SKU *string `gorm:"size:100;index" json:"sku"` + Name string `gorm:"not null;size:255" json:"name" validate:"required,min=1,max=255"` + Description *string `gorm:"type:text" json:"description"` + Price float64 `gorm:"type:decimal(10,2);not null" json:"price" validate:"required,min=0"` + Cost float64 `gorm:"type:decimal(10,2);default:0.00" json:"cost" validate:"min=0"` + BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"` + ImageURL *string `gorm:"size:500" json:"image_url"` + // PrinterTypes are the stations the product is printed at. Set them through + // SetPrinterTypes. + PrinterTypes StringSlice `gorm:"type:jsonb;not null;default:'[\"kitchen\"]'" json:"printer_types"` + UnitID *uuid.UUID `gorm:"type:uuid;index" json:"unit_id"` + SellBy string `gorm:"size:20;default:'unit'" json:"sell_by"` + HasIngredients bool `gorm:"default:false" json:"has_ingredients"` + Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"` + IsActive bool `gorm:"default:true" json:"is_active"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` Organization Organization `gorm:"foreignKey:OrganizationID" json:"organization,omitempty"` Category Category `gorm:"foreignKey:CategoryID" json:"category,omitempty"` @@ -48,6 +51,32 @@ func (Product) TableName() string { return "products" } +// SetPrinterTypes records the stations the product is printed at, in order, dropping +// blanks and repeats. +func (p *Product) SetPrinterTypes(printerTypes []string) { + cleaned := StringSlice{} + seen := make(map[string]bool, len(printerTypes)) + for _, printerType := range printerTypes { + printerType = strings.TrimSpace(printerType) + if printerType == "" || seen[printerType] { + continue + } + seen[printerType] = true + cleaned = append(cleaned, printerType) + } + + p.PrinterTypes = cleaned +} + +// GetPrinterTypes returns the stations the product is printed at, never nil, so a +// response always carries a list. A product that was not loaded has none. +func (p *Product) GetPrinterTypes() []string { + if p.PrinterTypes == nil { + return []string{} + } + return []string(p.PrinterTypes) +} + type ProductVariant struct { ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"` ProductID uuid.UUID `gorm:"type:uuid;not null;index" json:"product_id" validate:"required"` diff --git a/internal/mappers/order_mapper.go b/internal/mappers/order_mapper.go index 8a12404..e4b5803 100644 --- a/internal/mappers/order_mapper.go +++ b/internal/mappers/order_mapper.go @@ -149,7 +149,7 @@ func OrderItemEntityToResponse(item *entities.OrderItem, outletID uuid.UUID) *mo Status: constants.OrderItemStatus(item.Status), CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, - PrinterType: item.Product.PrinterType, + PrinterTypes: item.Product.GetPrinterTypes(), PrintToChecker: printToChecker, } diff --git a/internal/mappers/product_mapper.go b/internal/mappers/product_mapper.go index c9d1aa4..572ed96 100644 --- a/internal/mappers/product_mapper.go +++ b/internal/mappers/product_mapper.go @@ -24,7 +24,7 @@ func ProductEntityToModel(entity *entities.Product) *models.Product { Cost: entity.Cost, BusinessType: constants.BusinessType(entity.BusinessType), ImageURL: entity.ImageURL, - PrinterType: entity.PrinterType, + PrinterTypes: entity.GetPrinterTypes(), UnitID: entity.UnitID, SellBy: entity.SellBy, HasIngredients: entity.HasIngredients, @@ -51,7 +51,7 @@ func ProductModelToEntity(model *models.Product) *entities.Product { Cost: model.Cost, BusinessType: string(model.BusinessType), ImageURL: model.ImageURL, - PrinterType: model.PrinterType, + PrinterTypes: entities.StringSlice(model.PrinterTypes), UnitID: model.UnitID, SellBy: model.SellBy, HasIngredients: model.HasIngredients, @@ -77,11 +77,6 @@ func CreateProductRequestToEntity(req *models.CreateProductRequest) *entities.Pr businessType = string(req.BusinessType) } - printerType := "kitchen" - if req.PrinterType != nil && *req.PrinterType != "" { - printerType = *req.PrinterType - } - sellBy := constants.SellByUnit if constants.IsValidSellBy(req.SellBy) { sellBy = req.SellBy @@ -92,7 +87,7 @@ func CreateProductRequestToEntity(req *models.CreateProductRequest) *entities.Pr metadata = entities.Metadata(req.Metadata) } - return &entities.Product{ + product := &entities.Product{ OrganizationID: req.OrganizationID, CategoryID: req.CategoryID, SKU: req.SKU, @@ -102,12 +97,18 @@ func CreateProductRequestToEntity(req *models.CreateProductRequest) *entities.Pr Cost: cost, BusinessType: businessType, ImageURL: req.ImageURL, - PrinterType: printerType, UnitID: req.UnitID, SellBy: sellBy, Metadata: metadata, IsActive: true, // Default to active } + + product.SetPrinterTypes(req.PrinterTypes) + if len(product.PrinterTypes) == 0 { + product.SetPrinterTypes([]string{"kitchen"}) + } + + return product } func ProductEntityToResponse(entity *entities.Product) *models.ProductResponse { @@ -152,7 +153,7 @@ func ProductEntityToResponse(entity *entities.Product) *models.ProductResponse { Cost: entity.Cost, BusinessType: constants.BusinessType(entity.BusinessType), ImageURL: entity.ImageURL, - PrinterType: entity.PrinterType, + PrinterTypes: entity.GetPrinterTypes(), UnitID: entity.UnitID, SellBy: entity.SellBy, Metadata: map[string]interface{}(entity.Metadata), @@ -196,8 +197,8 @@ func UpdateProductEntityFromRequest(entity *entities.Product, req *models.Update entity.ImageURL = req.ImageURL } - if req.PrinterType != nil { - entity.PrinterType = *req.PrinterType + if req.PrinterTypes != nil { + entity.SetPrinterTypes(req.PrinterTypes) } if req.UnitID != nil { diff --git a/internal/mappers/product_mapper_printer_types_test.go b/internal/mappers/product_mapper_printer_types_test.go new file mode 100644 index 0000000..cd18156 --- /dev/null +++ b/internal/mappers/product_mapper_printer_types_test.go @@ -0,0 +1,102 @@ +package mappers + +import ( + "testing" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" +) + +func TestCreateProductRequestToEntityPrinterTypes(t *testing.T) { + tests := []struct { + name string + printerTypes []string + want []string + }{ + { + name: "nothing sent prints in the kitchen", + want: []string{"kitchen"}, + }, + { + name: "a meal-and-drink package prints in the kitchen and the bar", + printerTypes: []string{"kitchen", "bar"}, + want: []string{"kitchen", "bar"}, + }, + { + name: "blanks and repeats are dropped", + printerTypes: []string{" kitchen ", "", "kitchen", "bar"}, + want: []string{"kitchen", "bar"}, + }, + { + name: "a list of only blanks falls back to the kitchen", + printerTypes: []string{" ", ""}, + want: []string{"kitchen"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + product := CreateProductRequestToEntity(&models.CreateProductRequest{ + OrganizationID: uuid.New(), + CategoryID: uuid.New(), + Name: "Paket Makan Minum", + PrinterTypes: tt.printerTypes, + }) + + assert.Equal(t, entities.StringSlice(tt.want), product.PrinterTypes) + }) + } +} + +func TestUpdateProductEntityFromRequestPrinterTypes(t *testing.T) { + tests := []struct { + name string + printerTypes []string + want []string + }{ + { + name: "a save that does not send printers keeps them", + want: []string{"kitchen", "bar"}, + }, + { + name: "printer_types replaces the whole list", + printerTypes: []string{"bar"}, + want: []string{"bar"}, + }, + { + name: "an empty printer_types prints nowhere", + printerTypes: []string{}, + want: []string{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + product := &entities.Product{} + product.SetPrinterTypes([]string{"kitchen", "bar"}) + + UpdateProductEntityFromRequest(product, &models.UpdateProductRequest{PrinterTypes: tt.printerTypes}) + + assert.Equal(t, entities.StringSlice(tt.want), product.PrinterTypes) + }) + } +} + +func TestOrderItemEntityToResponsePrinterTypes(t *testing.T) { + product := entities.Product{ID: uuid.New(), Name: "Paket Makan Minum"} + product.SetPrinterTypes([]string{"kitchen", "bar"}) + + response := OrderItemEntityToResponse(&entities.OrderItem{ProductID: product.ID, Product: product}, uuid.New()) + + assert.Equal(t, []string{"kitchen", "bar"}, response.PrinterTypes) +} + +func TestProductEntityToResponseAlwaysHasAList(t *testing.T) { + // The POS reads printer_types as a list, so a product without one sends [] not null. + response := ProductEntityToResponse(&entities.Product{}) + + assert.Equal(t, []string{}, response.PrinterTypes) +} diff --git a/internal/models/order.go b/internal/models/order.go index d15278f..dcb584e 100644 --- a/internal/models/order.go +++ b/internal/models/order.go @@ -218,7 +218,7 @@ type OrderItemResponse struct { Status constants.OrderItemStatus CreatedAt time.Time UpdatedAt time.Time - PrinterType string + PrinterTypes []string PrintToChecker bool PaidQuantity int } diff --git a/internal/models/product.go b/internal/models/product.go index 1d2142b..1580715 100644 --- a/internal/models/product.go +++ b/internal/models/product.go @@ -18,7 +18,7 @@ type Product struct { Cost float64 BusinessType constants.BusinessType ImageURL *string - PrinterType string + PrinterTypes []string SellBy string UnitID *uuid.UUID HasIngredients bool @@ -50,7 +50,7 @@ type CreateProductRequest struct { Cost float64 `validate:"min=0"` BusinessType constants.BusinessType `validate:"required"` ImageURL *string `validate:"omitempty,max=500"` - PrinterType *string `validate:"omitempty,max=50"` + PrinterTypes []string `validate:"omitempty,dive,max=50"` PrintToChecker *bool `validate:"omitempty"` UnitID *uuid.UUID `validate:"omitempty"` SellBy string `validate:"omitempty,oneof=unit weight"` @@ -72,7 +72,7 @@ type UpdateProductRequest struct { Price *float64 `validate:"omitempty,min=0"` Cost *float64 `validate:"omitempty,min=0"` ImageURL *string `validate:"omitempty,max=500"` - PrinterType *string `validate:"omitempty,max=50"` + PrinterTypes []string `validate:"omitempty,dive,max=50"` // Replaces the whole list when not nil PrintToChecker *bool `validate:"omitempty"` UnitID *uuid.UUID `validate:"omitempty"` SellBy *string `validate:"omitempty,oneof=unit weight"` @@ -112,7 +112,7 @@ type ProductResponse struct { Cost float64 BusinessType constants.BusinessType ImageURL *string - PrinterType string + PrinterTypes []string SellBy string PrintToChecker bool UnitID *uuid.UUID diff --git a/internal/processor/order_add_items_test.go b/internal/processor/order_add_items_test.go new file mode 100644 index 0000000..550f1a5 --- /dev/null +++ b/internal/processor/order_add_items_test.go @@ -0,0 +1,46 @@ +package processor + +import ( + "testing" + + "apskel-pos-be/internal/entities" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The items AddToOrder creates have no product loaded, so their responses used to go out +// without a name or a printer, and the POS could not print them. +func TestAddedItemsFromOrderUsesTheReloadedProduct(t *testing.T) { + outletID := uuid.New() + + paket := entities.Product{ID: uuid.New(), Name: "Paket Makan Minum"} + paket.SetPrinterTypes([]string{"kitchen", "bar"}) + paket.ProductOutletPrices = []entities.ProductOutletPrice{{OutletID: outletID, PrintToChecker: false}} + esTeh := entities.Product{ID: uuid.New(), Name: "Es Teh"} + esTeh.SetPrinterTypes([]string{"bar"}) + + existing := entities.OrderItem{ID: uuid.New(), ProductID: esTeh.ID, Product: esTeh} + addedPaket := &entities.OrderItem{ID: uuid.New(), ProductID: paket.ID} + addedEsTeh := &entities.OrderItem{ID: uuid.New(), ProductID: esTeh.ID} + + order := &entities.Order{ + OutletID: outletID, + OrderItems: []entities.OrderItem{ + existing, + {ID: addedEsTeh.ID, ProductID: esTeh.ID, Product: esTeh}, + {ID: addedPaket.ID, ProductID: paket.ID, Product: paket}, + }, + } + + responses := addedItemsFromOrder([]*entities.OrderItem{addedPaket, addedEsTeh}, order) + + require.Len(t, responses, 2, "only the added items, not the ones already on the order") + assert.Equal(t, addedPaket.ID, responses[0].ID, "in the order they were requested") + assert.Equal(t, "Paket Makan Minum", responses[0].ProductName) + assert.Equal(t, []string{"kitchen", "bar"}, responses[0].PrinterTypes) + assert.False(t, responses[0].PrintToChecker, "the outlet's print_to_checker is loaded too") + assert.Equal(t, addedEsTeh.ID, responses[1].ID) + assert.Equal(t, []string{"bar"}, responses[1].PrinterTypes) +} diff --git a/internal/processor/order_processor.go b/internal/processor/order_processor.go index 60ad0f4..0afc945 100644 --- a/internal/processor/order_processor.go +++ b/internal/processor/order_processor.go @@ -568,16 +568,10 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID, return nil, fmt.Errorf("failed to update order: %w", err) } - var addedItemResponses []models.OrderItemResponse for _, orderItem := range addedOrderItems { if err := p.orderItemRepo.Create(ctx, orderItem); err != nil { return nil, fmt.Errorf("failed to create order item: %w", err) } - - itemResponse := mappers.OrderItemEntityToResponse(orderItem, order.OutletID) - if itemResponse != nil { - addedItemResponses = append(addedItemResponses, *itemResponse) - } } orderWithRelations, err := p.orderRepo.GetWithRelations(ctx, orderID) @@ -585,6 +579,10 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID, return nil, fmt.Errorf("failed to retrieve updated order: %w", err) } + // The items just created carry no product, so take them from the reloaded order: the + // POS prints added items from this response and needs their name and printers. + addedItemResponses := addedItemsFromOrder(addedOrderItems, orderWithRelations) + updatedOrderResponse := mappers.OrderEntityToResponse(orderWithRelations) p.attachEarnings(ctx, updatedOrderResponse) @@ -596,6 +594,26 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID, }, nil } +// addedItemsFromOrder maps the added items in the order they were requested, using their +// copies in the reloaded order, which have the product and its outlet prices loaded. +func addedItemsFromOrder(added []*entities.OrderItem, order *entities.Order) []models.OrderItemResponse { + reloaded := make(map[uuid.UUID]*entities.OrderItem, len(order.OrderItems)) + for i := range order.OrderItems { + reloaded[order.OrderItems[i].ID] = &order.OrderItems[i] + } + + var responses []models.OrderItemResponse + for _, item := range added { + if loaded, ok := reloaded[item.ID]; ok { + item = loaded + } + if response := mappers.OrderItemEntityToResponse(item, order.OutletID); response != nil { + responses = append(responses, *response) + } + } + return responses +} + func (p *OrderProcessorImpl) UpdateOrder(ctx context.Context, id uuid.UUID, req *models.UpdateOrderRequest) (*models.OrderResponse, error) { // Get existing order order, err := p.orderRepo.GetByID(ctx, id) diff --git a/internal/processor/product_recipe_processor.go b/internal/processor/product_recipe_processor.go index 5f63fa1..924b4e2 100644 --- a/internal/processor/product_recipe_processor.go +++ b/internal/processor/product_recipe_processor.go @@ -199,7 +199,7 @@ func (p *ProductRecipeProcessorImpl) entityToResponse(entity *entities.ProductRe Cost: entity.Product.Cost, BusinessType: string(entity.Product.BusinessType), ImageURL: entity.Product.ImageURL, - PrinterType: entity.Product.PrinterType, + PrinterTypes: entity.Product.GetPrinterTypes(), Metadata: entity.Product.Metadata, IsActive: entity.Product.IsActive, CreatedAt: entity.Product.CreatedAt, diff --git a/internal/repository/product_ingredient_repository.go b/internal/repository/product_ingredient_repository.go index b81579d..e55481a 100644 --- a/internal/repository/product_ingredient_repository.go +++ b/internal/repository/product_ingredient_repository.go @@ -39,7 +39,7 @@ func (r *ProductIngredientRepository) Create(ctx context.Context, productIngredi func (r *ProductIngredientRepository) GetByID(ctx context.Context, id, organizationID uuid.UUID) (*entities.ProductIngredient, error) { query := ` SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at, - p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_type, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at, + p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_types, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at, i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at FROM product_ingredients pi LEFT JOIN products p ON pi.product_id = p.id @@ -70,7 +70,7 @@ func (r *ProductIngredientRepository) GetByID(ctx context.Context, id, organizat &product.Cost, &product.BusinessType, &product.ImageURL, - &product.PrinterType, + &product.PrinterTypes, &product.UnitID, &product.HasIngredients, &product.Metadata, @@ -103,7 +103,7 @@ func (r *ProductIngredientRepository) GetByID(ctx context.Context, id, organizat func (r *ProductIngredientRepository) GetByProductID(ctx context.Context, productID, organizationID uuid.UUID) ([]*entities.ProductIngredient, error) { query := ` SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at, - p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_type, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at, + p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_types, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at, i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at FROM product_ingredients pi LEFT JOIN products p ON pi.product_id = p.id @@ -143,7 +143,7 @@ func (r *ProductIngredientRepository) GetByProductID(ctx context.Context, produc &product.Cost, &product.BusinessType, &product.ImageURL, - &product.PrinterType, + &product.PrinterTypes, &product.UnitID, &product.HasIngredients, &product.Metadata, @@ -178,7 +178,7 @@ func (r *ProductIngredientRepository) GetByProductID(ctx context.Context, produc func (r *ProductIngredientRepository) GetByIngredientID(ctx context.Context, ingredientID, organizationID uuid.UUID) ([]*entities.ProductIngredient, error) { query := ` SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at, - p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_type, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at, + p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_types, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at, i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at FROM product_ingredients pi LEFT JOIN products p ON pi.product_id = p.id @@ -218,7 +218,7 @@ func (r *ProductIngredientRepository) GetByIngredientID(ctx context.Context, ing &product.Cost, &product.BusinessType, &product.ImageURL, - &product.PrinterType, + &product.PrinterTypes, &product.UnitID, &product.HasIngredients, &product.Metadata, diff --git a/internal/repository/product_repository_printer_types_test.go b/internal/repository/product_repository_printer_types_test.go new file mode 100644 index 0000000..63b5c3b --- /dev/null +++ b/internal/repository/product_repository_printer_types_test.go @@ -0,0 +1,48 @@ +package repository + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/entities" +) + +// Needs TEST_DATABASE_URL pointing at a migrated database; see walletTestDB. +func TestProductPrinterTypes_AgainstPostgres(t *testing.T) { + db := walletTestDB(t) + ctx := context.Background() + + org, category := uuid.New(), uuid.New() + require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'printer test', 'basic')`, org).Error) + require.NoError(t, db.Exec(`INSERT INTO categories (id, organization_id, name) VALUES (?, ?, 'Paket')`, category, org).Error) + t.Cleanup(func() { + db.Exec(`DELETE FROM products WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM categories WHERE id = ?`, category) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + repo := NewProductRepositoryImpl(db) + product := &entities.Product{OrganizationID: org, CategoryID: category, Name: "Paket Makan Minum", Price: 25000} + product.SetPrinterTypes([]string{"kitchen", "bar"}) + require.NoError(t, repo.Create(ctx, product)) + + stored, err := repo.GetByID(ctx, product.ID) + require.NoError(t, err) + assert.Equal(t, entities.StringSlice{"kitchen", "bar"}, stored.PrinterTypes) + + stored.SetPrinterTypes([]string{"bar"}) + require.NoError(t, repo.Update(ctx, stored)) + + var printerTypes string + require.NoError(t, db.Raw(`SELECT printer_types::text FROM products WHERE id = ?`, product.ID).Scan(&printerTypes).Error) + assert.Equal(t, `["bar"]`, printerTypes) + + // The old single column is gone. + var columns int64 + require.NoError(t, db.Raw(`SELECT COUNT(*) FROM information_schema.columns WHERE table_name = 'products' AND column_name = 'printer_type'`).Scan(&columns).Error) + assert.Zero(t, columns) +} diff --git a/internal/transformer/inventory_transformer.go b/internal/transformer/inventory_transformer.go index 4825b2c..6d39c63 100644 --- a/internal/transformer/inventory_transformer.go +++ b/internal/transformer/inventory_transformer.go @@ -44,8 +44,9 @@ func InventoryModelResponseToResponse(inv *models.InventoryResponse) *contract.I IsLowStock: inv.IsLowStock, UpdatedAt: inv.UpdatedAt, Product: &contract.ProductResponse{ - ID: inv.ProductID, - Name: inv.ProductName, + ID: inv.ProductID, + Name: inv.ProductName, + PrinterTypes: []string{}, }, } } diff --git a/internal/transformer/order_transformer.go b/internal/transformer/order_transformer.go index 2ed1194..5c7c8c0 100644 --- a/internal/transformer/order_transformer.go +++ b/internal/transformer/order_transformer.go @@ -118,7 +118,7 @@ func OrderModelToContract(resp *models.OrderResponse) *contract.OrderResponse { Status: string(item.Status), CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, - PrinterType: item.PrinterType, + PrinterTypes: item.PrinterTypes, PrintToChecker: item.PrintToChecker, PaidQuantity: item.PaidQuantity, } @@ -195,6 +195,7 @@ func AddToOrderModelToContract(resp *models.AddToOrderResponse) *contract.AddToO Status: string(item.Status), CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, + PrinterTypes: item.PrinterTypes, PrintToChecker: item.PrintToChecker, } } diff --git a/internal/transformer/order_transformer_printer_types_test.go b/internal/transformer/order_transformer_printer_types_test.go new file mode 100644 index 0000000..a07b88e --- /dev/null +++ b/internal/transformer/order_transformer_printer_types_test.go @@ -0,0 +1,50 @@ +package transformer + +import ( + "encoding/json" + "testing" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/mappers" + "apskel-pos-be/internal/models" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The POS prints items added to an open order from this response, so each one has to +// say where it is printed. +func TestAddToOrderModelToContractCarriesPrinters(t *testing.T) { + result := AddToOrderModelToContract(&models.AddToOrderResponse{ + AddedItems: []models.OrderItemResponse{{PrinterTypes: []string{"kitchen", "bar"}}}, + }) + + require.Len(t, result.AddedItems, 1) + assert.Equal(t, []string{"kitchen", "bar"}, result.AddedItems[0].PrinterTypes) +} + +// Follows an order from the database row to the JSON the POS reads. +func TestOrderJSONCarriesPrinters(t *testing.T) { + paket := entities.Product{ID: uuid.New(), Name: "Paket Makan Minum"} + paket.SetPrinterTypes([]string{"kitchen", "bar"}) + order := &entities.Order{ + ID: uuid.New(), + OrderItems: []entities.OrderItem{{ID: uuid.New(), ProductID: paket.ID, Product: paket, Quantity: 1}}, + } + + body, err := json.Marshal(OrderModelToContract(mappers.OrderEntityToResponse(order))) + require.NoError(t, err) + + assert.Contains(t, string(body), `"printer_types":["kitchen","bar"]`) + assert.NotContains(t, string(body), `"printer_type":`, "printer_types replaced it") +} + +func TestOrderModelToContractCarriesPrinters(t *testing.T) { + result := OrderModelToContract(&models.OrderResponse{ + OrderItems: []models.OrderItemResponse{{PrinterTypes: []string{"kitchen", "bar"}}}, + }) + + require.Len(t, result.OrderItems, 1) + assert.Equal(t, []string{"kitchen", "bar"}, result.OrderItems[0].PrinterTypes) +} diff --git a/internal/transformer/product_transformer.go b/internal/transformer/product_transformer.go index 0a628f6..97a4ff4 100644 --- a/internal/transformer/product_transformer.go +++ b/internal/transformer/product_transformer.go @@ -61,7 +61,7 @@ func CreateProductRequestToModel(apctx *appcontext.ContextInfo, req *contract.Cr Cost: cost, BusinessType: businessType, ImageURL: req.ImageURL, - PrinterType: req.PrinterType, + PrinterTypes: req.PrinterTypes, PrintToChecker: req.PrintToChecker, UnitID: req.UnitID, SellBy: sellBy, @@ -91,7 +91,7 @@ func UpdateProductRequestToModel(apctx *appcontext.ContextInfo, req *contract.Up Price: req.Price, Cost: req.Cost, ImageURL: req.ImageURL, - PrinterType: req.PrinterType, + PrinterTypes: req.PrinterTypes, PrintToChecker: req.PrintToChecker, UnitID: req.UnitID, SellBy: req.SellBy, @@ -152,7 +152,7 @@ func ProductModelResponseToResponse(prod *models.ProductResponse) *contract.Prod Cost: prod.Cost, BusinessType: string(prod.BusinessType), ImageURL: prod.ImageURL, - PrinterType: prod.PrinterType, + PrinterTypes: prod.PrinterTypes, PrintToChecker: prod.PrintToChecker, UnitID: prod.UnitID, SellBy: prod.SellBy, diff --git a/internal/validator/product_validator.go b/internal/validator/product_validator.go index a5943bb..23b5e4c 100644 --- a/internal/validator/product_validator.go +++ b/internal/validator/product_validator.go @@ -59,8 +59,8 @@ func (v *ProductValidatorImpl) ValidateCreateProductRequest(req *contract.Create return errors.New("image_url cannot exceed 500 characters"), constants.MalformedFieldErrorCode } - if req.PrinterType != nil && len(*req.PrinterType) > 50 { - return errors.New("printer_type cannot exceed 50 characters"), constants.MalformedFieldErrorCode + if err, code := validatePrinterTypes(req.PrinterTypes); err != nil { + return err, code } if err, code := validateSellBy(req.SellBy, req.UnitID); err != nil { @@ -70,6 +70,18 @@ func (v *ProductValidatorImpl) ValidateCreateProductRequest(req *contract.Create return nil, "" } +// validatePrinterTypes holds each printer to the 50 characters the single printer_type +// column allowed. +func validatePrinterTypes(printerTypes []string) (error, string) { + for _, printerType := range printerTypes { + if len(strings.TrimSpace(printerType)) > 50 { + return errors.New("each printer_types entry cannot exceed 50 characters"), constants.MalformedFieldErrorCode + } + } + + return nil, "" +} + // validateSellBy checks how a product is sold and that it carries what that choice // needs. A weight-based product without a unit would produce order lines with no unit // to print, so the receipt could show "4,2" with no idea of what. @@ -100,7 +112,7 @@ func (v *ProductValidatorImpl) ValidateUpdateProductRequest(req *contract.Update // At least one field should be provided for update if req.CategoryID == nil && req.SKU == nil && req.Name == nil && req.Description == nil && req.Price == nil && req.Cost == nil && req.BusinessType == nil && req.ImageURL == nil && - req.PrinterType == nil && req.PrintToChecker == nil && req.UnitID == nil && + req.PrinterTypes == nil && req.PrintToChecker == nil && req.UnitID == nil && req.SellBy == nil && req.Metadata == nil && req.IsActive == nil { return errors.New("at least one field must be provided for update"), constants.MissingFieldErrorCode } @@ -134,8 +146,8 @@ func (v *ProductValidatorImpl) ValidateUpdateProductRequest(req *contract.Update return errors.New("image_url cannot exceed 500 characters"), constants.MalformedFieldErrorCode } - if req.PrinterType != nil && len(*req.PrinterType) > 50 { - return errors.New("printer_type cannot exceed 50 characters"), constants.MalformedFieldErrorCode + if err, code := validatePrinterTypes(req.PrinterTypes); err != nil { + return err, code } // Only the value is checked here. Whether the product ends up with a unit depends on diff --git a/internal/validator/product_validator_printer_types_test.go b/internal/validator/product_validator_printer_types_test.go new file mode 100644 index 0000000..558b2f1 --- /dev/null +++ b/internal/validator/product_validator_printer_types_test.go @@ -0,0 +1,35 @@ +package validator + +import ( + "strings" + "testing" + + "apskel-pos-be/internal/contract" +) + +func TestValidateProductRequestPrinterTypes(t *testing.T) { + v := NewProductValidator() + tooLong := strings.Repeat("a", 51) + + create := baseCreateRequest() + create.PrinterTypes = []string{"kitchen", "bar"} + if err, _ := v.ValidateCreateProductRequest(create); err != nil { + t.Fatalf("kitchen and bar should be accepted, got: %v", err) + } + + create.PrinterTypes = []string{"kitchen", tooLong} + if err, _ := v.ValidateCreateProductRequest(create); err == nil { + t.Fatal("expected an error for a printer longer than 50 characters") + } + + err, _ := v.ValidateUpdateProductRequest(&contract.UpdateProductRequest{PrinterTypes: []string{tooLong}}) + if err == nil { + t.Fatal("expected an error for a printer longer than 50 characters on update") + } + + // An update that only changes the printers is a real update. + err, _ = v.ValidateUpdateProductRequest(&contract.UpdateProductRequest{PrinterTypes: []string{"kitchen", "bar"}}) + if err != nil { + t.Fatalf("an update of only printer_types should be accepted, got: %v", err) + } +} diff --git a/migrations/000099_add_printer_types_to_products.down.sql b/migrations/000099_add_printer_types_to_products.down.sql new file mode 100644 index 0000000..36d9968 --- /dev/null +++ b/migrations/000099_add_printer_types_to_products.down.sql @@ -0,0 +1,8 @@ +-- Only the first printer fits back into printer_type; the extra stations are lost. +ALTER TABLE products ADD COLUMN printer_type VARCHAR(50) DEFAULT 'kitchen'; + +UPDATE products SET printer_type = COALESCE(printer_types->>0, ''); + +CREATE INDEX idx_products_printer_type ON products(printer_type); + +ALTER TABLE products DROP COLUMN printer_types; diff --git a/migrations/000099_add_printer_types_to_products.up.sql b/migrations/000099_add_printer_types_to_products.up.sql new file mode 100644 index 0000000..8dfc29b --- /dev/null +++ b/migrations/000099_add_printer_types_to_products.up.sql @@ -0,0 +1,12 @@ +-- A product can be prepared at more than one station: a meal-and-drink package goes to +-- the kitchen and to the bar. printer_types replaces the single printer_type. +ALTER TABLE products ADD COLUMN printer_types JSONB NOT NULL DEFAULT '["kitchen"]'; + +UPDATE products +SET printer_types = CASE + WHEN COALESCE(printer_type, '') = '' THEN '[]'::jsonb + ELSE jsonb_build_array(printer_type) +END; + +-- Dropping the column drops idx_products_printer_type with it. +ALTER TABLE products DROP COLUMN printer_type; diff --git a/postman.json b/postman.json index dfc9647..68173bd 100644 --- a/postman.json +++ b/postman.json @@ -500,7 +500,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"name\": \"Cappuccino\",\n \"description\": \"Classic Italian coffee drink\",\n \"category_id\": \"{{category_id}}\",\n \"sku\": \"CAP001\",\n \"barcode\": \"1234567890123\",\n \"price\": 4.50,\n \"cost\": 1.20,\n \"is_active\": true,\n \"has_variants\": false,\n \"image_url\": \"https://example.com/cappuccino.jpg\",\n \"printer_type\": \"kitchen\"\n}" + "raw": "{\n \"name\": \"Cappuccino\",\n \"description\": \"Classic Italian coffee drink\",\n \"category_id\": \"{{category_id}}\",\n \"sku\": \"CAP001\",\n \"barcode\": \"1234567890123\",\n \"price\": 4.50,\n \"cost\": 1.20,\n \"is_active\": true,\n \"has_variants\": false,\n \"image_url\": \"https://example.com/cappuccino.jpg\",\n \"printer_types\": [\"kitchen\"]\n}" }, "url": { "raw": "{{base_url}}/api/v1/products", @@ -563,7 +563,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"name\": \"Premium Cappuccino\",\n \"description\": \"Premium Italian coffee drink with extra foam\",\n \"price\": 5.50,\n \"cost\": 1.50,\n \"is_active\": true,\n \"image_url\": \"https://example.com/premium-cappuccino.jpg\",\n \"printer_type\": \"kitchen\"\n}" + "raw": "{\n \"name\": \"Premium Cappuccino\",\n \"description\": \"Premium Italian coffee drink with extra foam\",\n \"price\": 5.50,\n \"cost\": 1.50,\n \"is_active\": true,\n \"image_url\": \"https://example.com/premium-cappuccino.jpg\",\n \"printer_types\": [\"kitchen\"]\n}" }, "url": { "raw": "{{base_url}}/api/v1/products/{{product_id}}", -- 2.54.0 From b372821b23b5fdd6797ea773e6ade2ecc61eaa2c Mon Sep 17 00:00:00 2001 From: efrilm Date: Fri, 2 Oct 2026 14:19:12 +0700 Subject: [PATCH 09/12] feat: add percentage loyalti setting mode --- docs/api-enakpoint.md | 6 +-- docs/backoffice-enakpoint.md | 14 ++++--- docs/integration-enakpoint.md | 7 ++-- docs/prd-point-coin.md | 24 +++++++++--- internal/constants/loyalty.go | 14 +++++++ internal/handler/loyalty_settings_db_test.go | 6 ++- internal/models/loyalty.go | 39 ++++++++++++++----- internal/models/loyalty_test.go | 8 ++++ internal/processor/earning_calculator.go | 26 ++++++++++--- internal/processor/earning_calculator_test.go | 39 +++++++++++++++++++ .../processor/loyalty_settings_processor.go | 36 +++++++++++++++++ .../loyalty_settings_processor_test.go | 8 +++- internal/service/loyalty_settings_service.go | 2 +- 13 files changed, 193 insertions(+), 36 deletions(-) diff --git a/docs/api-enakpoint.md b/docs/api-enakpoint.md index 0f168b1..6ccf437 100644 --- a/docs/api-enakpoint.md +++ b/docs/api-enakpoint.md @@ -323,13 +323,13 @@ Pada kedua `PUT` setting, field yang tidak dikirim tetap memakai nilai sekarang; ```json { - "point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, - "coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "point": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }, + "coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }, "point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 } } ``` -Response menambahkan `outlet_id`, `point_value`, `point_cashback_percent` (default di atas = 1%), dan `changes` pada PUT. Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `max_payment_percent` 0–100. +Response menambahkan `outlet_id`, `point_value`, `point_cashback_percent` (default di atas = 1%), dan `changes` pada PUT. `earn_mode` adalah `PER_AMOUNT` (setiap `earn_per_amount` rupiah mendapat `earn_value`) atau `PERCENTAGE` (`earn_percent` persen dari basis). Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `earn_percent` 0–100 dengan maks. 2 angka desimal, `max_payment_percent` 0–100. ### /marketing/loyalty-settings diff --git a/docs/backoffice-enakpoint.md b/docs/backoffice-enakpoint.md index 599eb34..82a992a 100644 --- a/docs/backoffice-enakpoint.md +++ b/docs/backoffice-enakpoint.md @@ -32,8 +32,8 @@ Tiap outlet mengatur sendiri berapa EnakPoint dan EnakCoin yang didapat dari ord ```json { - "point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, - "coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "point": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }, + "coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }, "point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 } } ``` @@ -41,15 +41,19 @@ Tiap outlet mengatur sendiri berapa EnakPoint dan EnakCoin yang didapat dari ord | Field | Label usulan | Tipe | Default | Validasi | | --- | --- | --- | --- | --- | | `point.enabled` / `coin.enabled` | Beri EnakPoint / EnakCoin | toggle | mati | – | -| `earn_per_amount` | Setiap belanja Rp … | Rp | 100 (point), 25.000 (coin) | > 0 | -| `earn_value` | … mendapat | angka | 1 | ≥ 0 | +| `earn_mode` | Cara hitung: per nominal / persentase | pilihan `PER_AMOUNT` / `PERCENTAGE` | `PER_AMOUNT` | salah satu dari keduanya | +| `earn_per_amount` | Setiap belanja Rp … (mode `PER_AMOUNT`) | Rp | 100 (point), 25.000 (coin) | > 0 | +| `earn_value` | … mendapat (mode `PER_AMOUNT`) | angka | 1 | ≥ 0 | +| `earn_percent` | … % dari belanja (mode `PERCENTAGE`) | %, boleh desimal | 1 | 0–100, maks. 2 angka desimal | | `min_order_amount` | Minimal belanja | Rp | 0 | ≥ 0 | | `max_per_order` | Maksimal per order | angka, boleh kosong | kosong = tanpa batas | ≥ 0 | | `point_payment.accept_payment` | Terima pembayaran EnakPoint | toggle | mati | – | | `min_payment_points` | Minimal EnakPoint per pembayaran | angka | 1 | ≥ 1 | | `max_payment_percent` | Maksimal porsi order dibayar EnakPoint | % | 100 | 0–100 | -**Cashback efektif.** Response membawa `point_cashback_percent` dan `point_value`. Tampilkan persentase di samping field earning EnakPoint, mis. "setara cashback 1%", dan hitung ulang di sisi klien saat owner mengetik: `earn_value × point_value ÷ earn_per_amount × 100`. Tujuannya agar owner tidak salah membaca skala (1 per Rp 100 bukan 1 per Rp 1). +**Cashback efektif.** Response membawa `point_cashback_percent` dan `point_value`. Tampilkan persentase di samping field earning EnakPoint, mis. "setara cashback 1%", dan hitung ulang di sisi klien saat owner mengetik: `earn_value × point_value ÷ earn_per_amount × 100`, atau pada mode `PERCENTAGE`: `earn_percent × point_value`. Tujuannya agar owner tidak salah membaca skala (1 per Rp 100 bukan 1 per Rp 1). + +**Mode earning.** Tampilkan hanya field mode yang dipilih (`earn_per_amount` + `earn_value`, atau `earn_percent`). Field mode lain tetap tersimpan di server, jadi tidak perlu dikosongkan saat owner berpindah mode. Pada mode `PERCENTAGE` jumlah yang didapat adalah `floor(basis × earn_percent ÷ 100)`, mis. 2,5% dari Rp 87.500 = 2.187 EnakPoint. **Contoh di bawah form.** "Belanja Rp 87.500 mendapat 875 EnakPoint dan 3 EnakCoin." Earning dihitung dari subtotal setelah diskon, sebelum pajak, dan bagian yang dibayar EnakPoint tidak ikut dihitung. diff --git a/docs/integration-enakpoint.md b/docs/integration-enakpoint.md index 58b459a..f7afdf0 100644 --- a/docs/integration-enakpoint.md +++ b/docs/integration-enakpoint.md @@ -516,15 +516,16 @@ Semua endpoint di bagian ini butuh login user dengan role Admin atau Manager. ```json { - "point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, - "coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "point": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }, + "coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }, "point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 } } ``` Field yang tidak dikirim di `PUT` tetap memakai nilai sekarang. Response menambahkan `point_value` organisasi dan `point_cashback_percent` -(`earn_value × point_value / earn_per_amount × 100`). **Tampilkan persentase ini di +(`earn_value × point_value / earn_per_amount × 100`, atau `earn_percent × point_value` +pada `earn_mode` `PERCENTAGE`). **Tampilkan persentase ini di samping setting** supaya owner tidak salah membaca skala: default di atas setara cashback 1%. diff --git a/docs/prd-point-coin.md b/docs/prd-point-coin.md index 5af5fbd..5e07b65 100644 --- a/docs/prd-point-coin.md +++ b/docs/prd-point-coin.md @@ -197,20 +197,28 @@ Disimpan di `outlet_settings` (key–value, sudah ada). | Key | Tipe | Default | Arti | |---|---|---|---| | `loyalty.point.enabled` | bool | `false` | Outlet memberi EnakPoint | -| `loyalty.point.earn_per_amount` | int (Rp) | `100` | Setiap kelipatan nominal ini… | +| `loyalty.point.earn_mode` | `PER_AMOUNT` / `PERCENTAGE` | `PER_AMOUNT` | Cara menghitung earning | +| `loyalty.point.earn_per_amount` | int (Rp) | `100` | `PER_AMOUNT`: setiap kelipatan nominal ini… | | `loyalty.point.earn_value` | int | `1` | …mendapat sekian EnakPoint | +| `loyalty.point.earn_percent` | desimal (0–100, maks. 2 angka desimal) | `1` | `PERCENTAGE`: sekian persen dari basis menjadi EnakPoint | | `loyalty.point.min_order_amount` | int (Rp) | `0` | Basis minimal agar dapat EnakPoint | | `loyalty.point.max_per_order` | int, nullable | kosong | Batas atas EnakPoint per order | | `loyalty.coin.enabled` | bool | `false` | Outlet memberi EnakCoin | +| `loyalty.coin.earn_mode` | `PER_AMOUNT` / `PERCENTAGE` | `PER_AMOUNT` | | | `loyalty.coin.earn_per_amount` | int (Rp) | `25000` | | | `loyalty.coin.earn_value` | int | `1` | | +| `loyalty.coin.earn_percent` | desimal (0–100, maks. 2 angka desimal) | `1` | | | `loyalty.coin.min_order_amount` | int (Rp) | `0` | | | `loyalty.coin.max_per_order` | int, nullable | kosong | | Dengan nilai EnakPoint default Rp 1, default earning 1 EnakPoint per Rp 100 setara **cashback 1%**. Dashboard selalu menampilkan persentase cashback efektif di samping -setting ini: `earn_value × nilai EnakPoint / earn_per_amount`. Tujuannya supaya owner -tidak salah mengira skala. +setting ini: `earn_value × nilai EnakPoint / earn_per_amount`, atau pada mode +`PERCENTAGE`: `earn_percent × nilai EnakPoint`. Tujuannya supaya owner tidak salah +mengira skala. + +Setting mode yang sedang tidak dipakai tetap tersimpan, sehingga berpindah mode tidak +menghapus nilai mode sebelumnya. **Pembayaran EnakPoint.** Hanya ada untuk EnakPoint, tidak ada padanannya untuk EnakCoin. @@ -226,7 +234,8 @@ EnakCoin. ``` basis = subtotal − discount_amount − dibayar_dengan_enakpoint jumlah = 0 jika basis < min_order_amount -jumlah = floor(basis / earn_per_amount) × earn_value +jumlah = floor(basis / earn_per_amount) × earn_value mode PER_AMOUNT +jumlah = floor(basis × earn_percent / 100) mode PERCENTAGE jumlah = min(jumlah, max_per_order) jika max_per_order diisi ``` @@ -240,7 +249,12 @@ jumlah = min(jumlah, max_per_order) jika max_per_order diisi EnakPoint** dan **3 EnakCoin**. Jika Rp 20.000 dari order itu dibayar dengan EnakPoint, basisnya menjadi Rp 67.500, sehingga customer mendapat 675 EnakPoint dan 2 EnakCoin. -Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `min_order_amount ≥ 0`, +Pada mode `PERCENTAGE`, `earn_percent` adalah persen dari basis yang menjadi +**jumlah** EnakPoint/EnakCoin (bukan nilai rupiahnya): 2,5% dari basis Rp 87.500 +menghasilkan 2.187 EnakPoint. + +Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `0 ≤ earn_percent ≤ 100` dengan +paling banyak dua angka desimal, `min_order_amount ≥ 0`, `max_per_order ≥ 0`, `0 ≤ max_payment_percent ≤ 100`. Hanya role Admin/Manager yang bisa mengubah. diff --git a/internal/constants/loyalty.go b/internal/constants/loyalty.go index 6721edf..3c1283f 100644 --- a/internal/constants/loyalty.go +++ b/internal/constants/loyalty.go @@ -7,12 +7,16 @@ package constants // Per outlet (F1): what an order earns, and whether EnakPoint can pay. const ( LoyaltyPointEnabledKey = "loyalty.point.enabled" + LoyaltyPointEarnModeKey = "loyalty.point.earn_mode" + LoyaltyPointEarnPercentKey = "loyalty.point.earn_percent" LoyaltyPointEarnPerAmountKey = "loyalty.point.earn_per_amount" LoyaltyPointEarnValueKey = "loyalty.point.earn_value" LoyaltyPointMinOrderAmountKey = "loyalty.point.min_order_amount" LoyaltyPointMaxPerOrderKey = "loyalty.point.max_per_order" LoyaltyCoinEnabledKey = "loyalty.coin.enabled" + LoyaltyCoinEarnModeKey = "loyalty.coin.earn_mode" + LoyaltyCoinEarnPercentKey = "loyalty.coin.earn_percent" LoyaltyCoinEarnPerAmountKey = "loyalty.coin.earn_per_amount" LoyaltyCoinEarnValueKey = "loyalty.coin.earn_value" LoyaltyCoinMinOrderAmountKey = "loyalty.coin.min_order_amount" @@ -47,6 +51,14 @@ const ( LoyaltyExpiryGraceMonthsSuffix = "expiry_grace_months" ) +// Modes of loyalty.{point,coin}.earn_mode. +const ( + // earn_value for every earn_per_amount rupiah of the basis. + LoyaltyEarnModePerAmount = "PER_AMOUNT" + // earn_percent percent of the basis. + LoyaltyEarnModePercentage = "PERCENTAGE" +) + // Units of loyalty.{point,coin}.expiry_unit. const ( LoyaltyExpiryUnitDay = "DAY" @@ -66,6 +78,8 @@ const ( LoyaltyPointEarnPerAmountDefault = int64(100) LoyaltyCoinEarnPerAmountDefault = int64(25000) LoyaltyEarnValueDefault = int64(1) + LoyaltyEarnModeDefault = LoyaltyEarnModePerAmount + LoyaltyEarnPercentDefault = float64(1) LoyaltyMinPaymentPointsDefault = int64(1) LoyaltyMaxPaymentPercentDefault = int64(100) diff --git a/internal/handler/loyalty_settings_db_test.go b/internal/handler/loyalty_settings_db_test.go index c427002..57d6804 100644 --- a/internal/handler/loyalty_settings_db_test.go +++ b/internal/handler/loyalty_settings_db_test.go @@ -91,8 +91,8 @@ func TestOutletLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) { status, body := call(http.MethodGet, "/manager"+path, "") require.Equal(t, http.StatusOK, status, body) got := data(body) - assert.Equal(t, map[string]any{"enabled": false, "earn_per_amount": float64(100), "earn_value": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["point"]) - assert.Equal(t, map[string]any{"enabled": false, "earn_per_amount": float64(25000), "earn_value": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["coin"]) + assert.Equal(t, map[string]any{"enabled": false, "earn_mode": "PER_AMOUNT", "earn_per_amount": float64(100), "earn_value": float64(1), "earn_percent": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["point"]) + assert.Equal(t, map[string]any{"enabled": false, "earn_mode": "PER_AMOUNT", "earn_per_amount": float64(25000), "earn_value": float64(1), "earn_percent": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["coin"]) assert.Equal(t, map[string]any{"accept_payment": false, "min_payment_points": float64(1), "max_payment_percent": float64(100)}, got["point_payment"]) assert.EqualValues(t, 1, got["point_value"]) assert.EqualValues(t, 1, got["point_cashback_percent"]) @@ -135,6 +135,8 @@ func TestOutletLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) { for name, bad := range map[string]string{ "earn_per_amount 0": `{"point": {"earn_per_amount": 0}}`, "negative earn_value": `{"coin": {"earn_value": -1}}`, + "earn mode unknown": `{"point": {"earn_mode": "PERCENT"}}`, + "earn_percent over 100": `{"coin": {"earn_percent": 101}}`, "negative min_order": `{"point": {"min_order_amount": -5}}`, "negative max_per_order": `{"point": {"max_per_order": -1}}`, "payment percent over 100": `{"point_payment": {"max_payment_percent": 101}}`, diff --git a/internal/models/loyalty.go b/internal/models/loyalty.go index 3a0f8b1..5733bdb 100644 --- a/internal/models/loyalty.go +++ b/internal/models/loyalty.go @@ -5,6 +5,8 @@ import ( "time" "github.com/google/uuid" + + "apskel-pos-be/internal/constants" ) // OutletLoyaltySettings are an outlet's loyalty settings (docs/prd-point-coin.md F1). @@ -15,15 +17,23 @@ type OutletLoyaltySettings struct { PointPayment LoyaltyPointPaymentSettings `json:"point_payment"` } -// LoyaltyEarnSettings is how much of one currency an order earns: -// floor(basis / EarnPerAmount) × EarnValue, nothing below MinOrderAmount, and at most -// MaxPerOrder when set. +// LoyaltyEarnSettings is how much of one currency an order earns, nothing below +// MinOrderAmount, and at most MaxPerOrder when set: +// +// - PER_AMOUNT: floor(basis / EarnPerAmount) × EarnValue; +// - PERCENTAGE: floor(basis × EarnPercent / 100). +// +// The settings of the mode not in use are kept, so switching back restores them. type LoyaltyEarnSettings struct { - Enabled bool `json:"enabled"` - EarnPerAmount int64 `json:"earn_per_amount"` - EarnValue int64 `json:"earn_value"` - MinOrderAmount int64 `json:"min_order_amount"` - MaxPerOrder *int64 `json:"max_per_order"` + Enabled bool `json:"enabled"` + // PER_AMOUNT or PERCENTAGE. + EarnMode string `json:"earn_mode"` + EarnPerAmount int64 `json:"earn_per_amount"` + EarnValue int64 `json:"earn_value"` + // PERCENTAGE: percent of the basis earned, 0–100 with at most two decimals. + EarnPercent float64 `json:"earn_percent"` + MinOrderAmount int64 `json:"min_order_amount"` + MaxPerOrder *int64 `json:"max_per_order"` } type LoyaltyPointPaymentSettings struct { @@ -102,8 +112,8 @@ type OutletLoyaltySettingsView struct { // The organization's rupiah value of one EnakPoint, which the cashback depends on. PointValue int64 `json:"point_value"` // Effective EnakPoint cashback in percent: earn_value × point_value / - // earn_per_amount × 100. Shown next to the setting so an owner cannot misread the - // scale (F1). + // earn_per_amount × 100, or earn_percent × point_value in PERCENTAGE mode. Shown + // next to the setting so an owner cannot misread the scale (F1). PointCashbackPercent float64 `json:"point_cashback_percent"` // Set on PUT: the keys that changed. Changes []LoyaltySettingChange `json:"changes,omitempty"` @@ -168,6 +178,15 @@ type LoyaltySettingsImpact struct { CoinRupiahAfter int64 `json:"coin_rupiah_after"` } +// CashbackPercent is the rupiah value of what an order earns as a percentage of its +// basis, in the mode the settings are in, rounded to two decimals. +func (s LoyaltyEarnSettings) CashbackPercent(pointValue int64) float64 { + if s.EarnMode == constants.LoyaltyEarnModePercentage { + return math.Round(s.EarnPercent*float64(pointValue)*100) / 100 + } + return LoyaltyCashbackPercent(s.EarnValue, pointValue, s.EarnPerAmount) +} + // NewLoyaltySettingsImpact computes the impact of moving from one organization setting // to another on the balances in circulation. func NewLoyaltySettingsImpact(points, coins int64, before, after OrganizationLoyaltySettings) LoyaltySettingsImpact { diff --git a/internal/models/loyalty_test.go b/internal/models/loyalty_test.go index 2fc48e5..2d4afbf 100644 --- a/internal/models/loyalty_test.go +++ b/internal/models/loyalty_test.go @@ -14,6 +14,14 @@ func TestLoyaltyCashbackPercent(t *testing.T) { assert.Equal(t, 0.0, LoyaltyCashbackPercent(1, 1, 0)) } +func TestLoyaltyEarnSettings_CashbackPercent(t *testing.T) { + s := LoyaltyEarnSettings{EarnMode: "PER_AMOUNT", EarnPerAmount: 100, EarnValue: 1, EarnPercent: 2.5} + assert.Equal(t, 1.0, s.CashbackPercent(1)) + s.EarnMode = "PERCENTAGE" + assert.Equal(t, 2.5, s.CashbackPercent(1)) + assert.Equal(t, 250.0, s.CashbackPercent(100), "each point earned is worth point_value rupiah") +} + func TestNewLoyaltySettingsImpact(t *testing.T) { before := OrganizationLoyaltySettings{PointValue: 1, Exchange: LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 1}} after := OrganizationLoyaltySettings{PointValue: 100, Exchange: LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 1}} diff --git a/internal/processor/earning_calculator.go b/internal/processor/earning_calculator.go index 28825c4..f4b7b84 100644 --- a/internal/processor/earning_calculator.go +++ b/internal/processor/earning_calculator.go @@ -3,6 +3,7 @@ package processor import ( "math" + "apskel-pos-be/internal/constants" "apskel-pos-be/internal/entities" "apskel-pos-be/internal/models" ) @@ -36,6 +37,10 @@ func (r EarningResult) Metadata(line EarningLine) entities.Metadata { "min_order_amount": line.Settings.MinOrderAmount, "capped": line.Capped, } + if line.Settings.EarnMode == constants.LoyaltyEarnModePercentage { + m["earn_mode"] = line.Settings.EarnMode + m["earn_percent"] = line.Settings.EarnPercent + } if line.Settings.MaxPerOrder != nil { m["max_per_order"] = *line.Settings.MaxPerOrder } @@ -46,7 +51,8 @@ func (r EarningResult) Metadata(line EarningLine) entities.Metadata { // // basis = subtotal − discount_amount − paid with EnakPoint // amount = 0 if basis < min_order_amount -// amount = floor(basis / earn_per_amount) × earn_value +// amount = floor(basis / earn_per_amount) × earn_value in PER_AMOUNT mode +// amount = floor(basis × earn_percent / 100) in PERCENTAGE mode // amount = min(amount, max_per_order) if max_per_order is set // // The part paid with EnakPoint earns nothing (Q10). Money is handled in whole cents so @@ -66,13 +72,23 @@ func CalculateEarning(order *entities.Order, pointPaidAmount float64, settings m func earnLine(basisCents int64, s models.LoyaltyEarnSettings) EarningLine { line := EarningLine{Settings: s} - if !s.Enabled || s.EarnPerAmount <= 0 || s.EarnValue <= 0 { + if !s.Enabled || basisCents < s.MinOrderAmount*100 { return line } - if basisCents < s.MinOrderAmount*100 { - return line + if s.EarnMode == constants.LoyaltyEarnModePercentage { + // The percent has at most two decimals, so in hundredths it is whole and the + // product stays in integers: cents × hundredths / (100 × 100 × 100). + hundredths := int64(math.Round(s.EarnPercent * 100)) + if hundredths <= 0 { + return line + } + line.Amount = basisCents * hundredths / 1_000_000 + } else { + if s.EarnPerAmount <= 0 || s.EarnValue <= 0 { + return line + } + line.Amount = basisCents / (s.EarnPerAmount * 100) * s.EarnValue } - line.Amount = basisCents / (s.EarnPerAmount * 100) * s.EarnValue if s.MaxPerOrder != nil && line.Amount > *s.MaxPerOrder { line.Amount = *s.MaxPerOrder line.Capped = true diff --git a/internal/processor/earning_calculator_test.go b/internal/processor/earning_calculator_test.go index b49efab..2fe987d 100644 --- a/internal/processor/earning_calculator_test.go +++ b/internal/processor/earning_calculator_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/assert" + "apskel-pos-be/internal/constants" "apskel-pos-be/internal/entities" "apskel-pos-be/internal/models" ) @@ -113,6 +114,44 @@ func TestCalculateEarning_EdgeCases(t *testing.T) { assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount) } +func TestCalculateEarning_Percentage(t *testing.T) { + s := prdEarningSettings() + s.Point.EarnMode = constants.LoyaltyEarnModePercentage + s.Point.EarnPercent = 1 + + // 1% of the basis; the per-amount settings are ignored, and coin keeps its own mode. + got := CalculateEarning(&entities.Order{Subtotal: 97500, DiscountAmount: 10000}, 0, s) + assert.Equal(t, int64(875), got.Point.Amount) + assert.Equal(t, int64(3), got.Coin.Amount) + // The part paid with EnakPoint earns nothing in this mode either. + assert.Equal(t, int64(675), CalculateEarning(&entities.Order{Subtotal: 97500, DiscountAmount: 10000}, 20000, s).Point.Amount) + + // Decimals, and floor, not round: 2.5% of 87.500 is 2187.5. + s.Point.EarnPercent = 2.5 + assert.Equal(t, int64(2187), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount) + s.Point.EarnPercent = 0.01 + assert.Equal(t, int64(8), CalculateEarning(&entities.Order{Subtotal: 87599.99}, 0, s).Point.Amount) + + // The minimum and the cap apply as in the other mode. + s.Point.EarnPercent = 10 + s.Point.MinOrderAmount = 50000 + max := int64(6000) + s.Point.MaxPerOrder = &max + assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 49999}, 0, s).Point.Amount) + assert.Equal(t, int64(5000), CalculateEarning(&entities.Order{Subtotal: 50000}, 0, s).Point.Amount) + got = CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s) + assert.Equal(t, int64(6000), got.Point.Amount) + assert.True(t, got.Point.Capped) + + // The mode and percent are frozen on the ledger row. + assert.Equal(t, constants.LoyaltyEarnModePercentage, got.Metadata(got.Point)["earn_mode"]) + assert.Equal(t, 10.0, got.Metadata(got.Point)["earn_percent"]) + + // A zero percent earns nothing even when enabled. + s.Point.EarnPercent = 0 + assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount) +} + func TestCalculateEarning_MetadataSnapshot(t *testing.T) { got := CalculateEarning(&entities.Order{Subtotal: 87500}, 0, prdEarningSettings()) assert.Equal(t, entities.Metadata{ diff --git a/internal/processor/loyalty_settings_processor.go b/internal/processor/loyalty_settings_processor.go index 2b78e45..437e897 100644 --- a/internal/processor/loyalty_settings_processor.go +++ b/internal/processor/loyalty_settings_processor.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "math" "strconv" "strings" "time" @@ -240,14 +241,20 @@ func loyaltySettingChangeModel(row entities.LoyaltySettingChange) models.Loyalty func outletLoyaltyFields(s *models.OutletLoyaltySettings) []loyaltyField { return []loyaltyField{ boolLoyaltyField(constants.LoyaltyPointEnabledKey, &s.Point.Enabled, false), + enumLoyaltyField(constants.LoyaltyPointEarnModeKey, &s.Point.EarnMode, constants.LoyaltyEarnModeDefault, + constants.LoyaltyEarnModePerAmount, constants.LoyaltyEarnModePercentage), intLoyaltyField(constants.LoyaltyPointEarnPerAmountKey, &s.Point.EarnPerAmount, constants.LoyaltyPointEarnPerAmountDefault, 1, noLoyaltyMax), intLoyaltyField(constants.LoyaltyPointEarnValueKey, &s.Point.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax), + percentLoyaltyField(constants.LoyaltyPointEarnPercentKey, &s.Point.EarnPercent, constants.LoyaltyEarnPercentDefault), intLoyaltyField(constants.LoyaltyPointMinOrderAmountKey, &s.Point.MinOrderAmount, 0, 0, noLoyaltyMax), optionalIntLoyaltyField(constants.LoyaltyPointMaxPerOrderKey, &s.Point.MaxPerOrder, 0), boolLoyaltyField(constants.LoyaltyCoinEnabledKey, &s.Coin.Enabled, false), + enumLoyaltyField(constants.LoyaltyCoinEarnModeKey, &s.Coin.EarnMode, constants.LoyaltyEarnModeDefault, + constants.LoyaltyEarnModePerAmount, constants.LoyaltyEarnModePercentage), intLoyaltyField(constants.LoyaltyCoinEarnPerAmountKey, &s.Coin.EarnPerAmount, constants.LoyaltyCoinEarnPerAmountDefault, 1, noLoyaltyMax), intLoyaltyField(constants.LoyaltyCoinEarnValueKey, &s.Coin.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax), + percentLoyaltyField(constants.LoyaltyCoinEarnPercentKey, &s.Coin.EarnPercent, constants.LoyaltyEarnPercentDefault), intLoyaltyField(constants.LoyaltyCoinMinOrderAmountKey, &s.Coin.MinOrderAmount, 0, 0, noLoyaltyMax), optionalIntLoyaltyField(constants.LoyaltyCoinMaxPerOrderKey, &s.Coin.MaxPerOrder, 0), @@ -329,6 +336,35 @@ func intLoyaltyField(key string, v *int64, def, min, max int64) loyaltyField { } } +// percentLoyaltyField is a percentage from 0 to 100 with at most two decimals, so it +// is whole in hundredths and calculations with it stay in integers. +func percentLoyaltyField(key string, v *float64, def float64) loyaltyField { + check := func(n float64) error { + // The negated form also rejects NaN. + if !(n >= 0 && n <= 100) { + return fmt.Errorf("%w: %s must be between 0 and 100", ErrInvalidLoyaltySettings, key) + } + if math.Abs(n*100-math.Round(n*100)) > 1e-6 { + return fmt.Errorf("%w: %s must have at most two decimals", ErrInvalidLoyaltySettings, key) + } + return nil + } + return loyaltyField{ + key: key, + parse: func(raw string) bool { + n, err := strconv.ParseFloat(strings.TrimSpace(raw), 64) + if err != nil || check(n) != nil { + return false + } + *v = n + return true + }, + reset: func() { *v = def }, + validate: func() error { return check(*v) }, + format: func() *string { s := strconv.FormatFloat(*v, 'f', -1, 64); return &s }, + } +} + // optionalIntLoyaltyField is a limit that may be unset, meaning no limit. func optionalIntLoyaltyField(key string, v **int64, min int64) loyaltyField { return loyaltyField{ diff --git a/internal/processor/loyalty_settings_processor_test.go b/internal/processor/loyalty_settings_processor_test.go index ecbdb1e..7248c37 100644 --- a/internal/processor/loyalty_settings_processor_test.go +++ b/internal/processor/loyalty_settings_processor_test.go @@ -107,8 +107,8 @@ func TestLoyaltySettings_OutletWithoutSettingsGetsEveryDefault(t *testing.T) { s, err := p.Outlet(context.Background(), uuid.New()) require.NoError(t, err) assert.Equal(t, models.OutletLoyaltySettings{ - Point: models.LoyaltyEarnSettings{Enabled: false, EarnPerAmount: 100, EarnValue: 1, MinOrderAmount: 0, MaxPerOrder: nil}, - Coin: models.LoyaltyEarnSettings{Enabled: false, EarnPerAmount: 25000, EarnValue: 1, MinOrderAmount: 0, MaxPerOrder: nil}, + Point: models.LoyaltyEarnSettings{Enabled: false, EarnMode: "PER_AMOUNT", EarnPerAmount: 100, EarnValue: 1, EarnPercent: 1, MinOrderAmount: 0, MaxPerOrder: nil}, + Coin: models.LoyaltyEarnSettings{Enabled: false, EarnMode: "PER_AMOUNT", EarnPerAmount: 25000, EarnValue: 1, EarnPercent: 1, MinOrderAmount: 0, MaxPerOrder: nil}, PointPayment: models.LoyaltyPointPaymentSettings{AcceptPayment: false, MinPaymentPoints: 1, MaxPaymentPercent: 100}, }, *s) } @@ -290,6 +290,10 @@ func TestLoyaltySettings_UpdateRejectsInvalidValues(t *testing.T) { for name, mutate := range map[string]func(*models.OutletLoyaltySettings){ "earn_per_amount 0": func(s *models.OutletLoyaltySettings) { s.Point.EarnPerAmount = 0 }, "negative earn_value": func(s *models.OutletLoyaltySettings) { s.Coin.EarnValue = -1 }, + "earn mode unknown": func(s *models.OutletLoyaltySettings) { s.Point.EarnMode = "PERCENT" }, + "negative earn_percent": func(s *models.OutletLoyaltySettings) { s.Point.EarnPercent = -1 }, + "earn_percent over 100": func(s *models.OutletLoyaltySettings) { s.Coin.EarnPercent = 100.5 }, + "earn_percent 3 decimals": func(s *models.OutletLoyaltySettings) { s.Point.EarnPercent = 1.125 }, "negative min_order": func(s *models.OutletLoyaltySettings) { s.Point.MinOrderAmount = -1 }, "negative max_per_order": func(s *models.OutletLoyaltySettings) { s.Coin.MaxPerOrder = ptr(int64(-1)) }, "payment percent over 100": func(s *models.OutletLoyaltySettings) { s.PointPayment.MaxPaymentPercent = 101 }, diff --git a/internal/service/loyalty_settings_service.go b/internal/service/loyalty_settings_service.go index 1d81921..20e592c 100644 --- a/internal/service/loyalty_settings_service.go +++ b/internal/service/loyalty_settings_service.go @@ -111,7 +111,7 @@ func (s *LoyaltySettingsServiceImpl) outletView(ctx context.Context, organizatio OutletID: outletID, OutletLoyaltySettings: settings, PointValue: pointValue, - PointCashbackPercent: models.LoyaltyCashbackPercent(settings.Point.EarnValue, pointValue, settings.Point.EarnPerAmount), + PointCashbackPercent: settings.Point.CashbackPercent(pointValue), Changes: changes, }, nil } -- 2.54.0 From fbe7e97dc7c9aee7144b3bd73d4d6da01860a4b9 Mon Sep 17 00:00:00 2001 From: efrilm Date: Fri, 2 Oct 2026 23:30:03 +0700 Subject: [PATCH 10/12] feat: add limit owner --- internal/constants/budget.go | 3 +- internal/contract/analytics_contract.go | 52 +++++---- internal/contract/category_contract.go | 103 +++++++++++++----- internal/contract/category_contract_test.go | 48 ++++++++ internal/entities/analytics.go | 35 ++++-- internal/entities/category.go | 6 +- internal/mappers/category_mapper.go | 54 +++++---- internal/models/analytics.go | 52 +++++---- internal/models/category.go | 59 +++++----- internal/processor/analytics_processor.go | 64 +++++++++-- .../processor/analytics_processor_test.go | 62 ++++++++++- internal/processor/budget_cutoff_test.go | 8 +- internal/repository/analytics_repository.go | 65 +++++++++-- internal/transformer/analytics_transformer.go | 21 +++- internal/transformer/category_transformer.go | 58 +++++----- internal/validator/category_validator.go | 10 +- ...d_owner_fee_percent_to_categories.down.sql | 1 + ...add_owner_fee_percent_to_categories.up.sql | 4 + 18 files changed, 533 insertions(+), 172 deletions(-) create mode 100644 internal/contract/category_contract_test.go create mode 100644 migrations/000100_add_owner_fee_percent_to_categories.down.sql create mode 100644 migrations/000100_add_owner_fee_percent_to_categories.up.sql diff --git a/internal/constants/budget.go b/internal/constants/budget.go index 5bfa3d3..ac62e5a 100644 --- a/internal/constants/budget.go +++ b/internal/constants/budget.go @@ -1,7 +1,8 @@ package constants // Budget allocation of revenue used by the parent category cut-off report. -// The three shares are expected to add up to 100. +// The three shares are expected to add up to 100. BudgetLimitOwnerPercent is only the +// default: a parent category can override it with categories.owner_fee_percent. const ( BudgetLimitPurchasePercent = 60.0 BudgetLimitOwnerPercent = 20.0 diff --git a/internal/contract/analytics_contract.go b/internal/contract/analytics_contract.go index 3b48206..97ec2a8 100644 --- a/internal/contract/analytics_contract.go +++ b/internal/contract/analytics_contract.go @@ -266,16 +266,27 @@ type ProductAnalyticsPerParentCategoryResponse struct { } type ProductAnalyticsPerParentCategoryData struct { - ParentCategoryID uuid.UUID `json:"parent_category_id"` - ParentCategoryName string `json:"parent_category_name"` - TotalRevenue float64 `json:"total_revenue"` - TotalQuantity int64 `json:"total_quantity"` - CategoryCount int64 `json:"category_count"` - ProductCount int64 `json:"product_count"` - OrderCount int64 `json:"order_count"` - TotalStandardHpp float64 `json:"total_standard_hpp"` - TotalFifoHpp float64 `json:"total_fifo_hpp"` - TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + ParentCategoryID uuid.UUID `json:"parent_category_id"` + ParentCategoryName string `json:"parent_category_name"` + OwnerFeePercent float64 `json:"owner_fee_percent"` + SDL float64 `json:"sdl"` + TotalRevenue float64 `json:"total_revenue"` + TotalQuantity int64 `json:"total_quantity"` + CategoryCount int64 `json:"category_count"` + ProductCount int64 `json:"product_count"` + OrderCount int64 `json:"order_count"` + TotalStandardHpp float64 `json:"total_standard_hpp"` + TotalFifoHpp float64 `json:"total_fifo_hpp"` + TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + TopProduct *ParentCategoryTopProduct `json:"top_product"` +} + +// ParentCategoryTopProduct is the best-selling product of a parent category by revenue. +type ParentCategoryTopProduct struct { + ProductID uuid.UUID `json:"product_id"` + ProductName string `json:"product_name"` + QuantitySold int64 `json:"quantity_sold"` + Revenue float64 `json:"revenue"` } // ParentCategoryAnalyticsDetailRequest represents the request for the drill-down of one parent category @@ -302,14 +313,17 @@ type ParentCategoryAnalyticsDetailResponse struct { } type ParentCategoryAnalyticsDetailSummary struct { - TotalRevenue float64 `json:"total_revenue"` - TotalQuantity int64 `json:"total_quantity"` - CategoryCount int64 `json:"category_count"` - ProductCount int64 `json:"product_count"` - OrderCount int64 `json:"order_count"` - TotalStandardHpp float64 `json:"total_standard_hpp"` - TotalFifoHpp float64 `json:"total_fifo_hpp"` - TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + OwnerFeePercent float64 `json:"owner_fee_percent"` + SDL float64 `json:"sdl"` + TotalRevenue float64 `json:"total_revenue"` + TotalQuantity int64 `json:"total_quantity"` + CategoryCount int64 `json:"category_count"` + ProductCount int64 `json:"product_count"` + OrderCount int64 `json:"order_count"` + TotalStandardHpp float64 `json:"total_standard_hpp"` + TotalFifoHpp float64 `json:"total_fifo_hpp"` + TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + TopProduct *ParentCategoryTopProduct `json:"top_product"` } type ParentCategoryAnalyticsDetailData struct { @@ -366,7 +380,7 @@ type BudgetPeriod struct { Revenue float64 `json:"revenue"` OrderCount int64 `json:"order_count"` LimitPurchase float64 `json:"limit_purchase"` - LimitOwner float64 `json:"limit_owner"` + SDL float64 `json:"sdl"` LimitTeam float64 `json:"limit_team"` } diff --git a/internal/contract/category_contract.go b/internal/contract/category_contract.go index 1950207..322f3c1 100644 --- a/internal/contract/category_contract.go +++ b/internal/contract/category_contract.go @@ -1,29 +1,79 @@ package contract import ( + "bytes" + "encoding/json" "time" "github.com/google/uuid" ) type CreateCategoryRequest struct { - Name string `json:"name" validate:"required,min=1,max=255"` - Description *string `json:"description,omitempty"` - BusinessType *string `json:"business_type,omitempty"` - OutletID *uuid.UUID `json:"outlet_id,omitempty"` - ParentID *uuid.UUID `json:"parent_id,omitempty"` - Order *int `json:"order,omitempty"` - Metadata map[string]interface{} `json:"metadata,omitempty"` + Name string `json:"name" validate:"required,min=1,max=255"` + Description *string `json:"description,omitempty"` + BusinessType *string `json:"business_type,omitempty"` + OutletID *uuid.UUID `json:"outlet_id,omitempty"` + ParentID *uuid.UUID `json:"parent_id,omitempty"` + Order *int `json:"order,omitempty"` + OwnerFeePercent *float64 `json:"owner_fee_percent,omitempty"` + Metadata map[string]interface{} `json:"metadata,omitempty"` } type UpdateCategoryRequest struct { - Name *string `json:"name,omitempty" validate:"omitempty,min=1,max=255"` - Description *string `json:"description,omitempty"` - BusinessType *string `json:"business_type,omitempty"` - OutletID *uuid.UUID `json:"outlet_id,omitempty"` - ParentID *uuid.UUID `json:"parent_id,omitempty"` - Order *int `json:"order,omitempty"` - Metadata map[string]interface{} `json:"metadata,omitempty"` + Name *string `json:"name,omitempty" validate:"omitempty,min=1,max=255"` + Description *string `json:"description,omitempty"` + BusinessType *string `json:"business_type,omitempty"` + OutletID *uuid.UUID `json:"outlet_id,omitempty"` + ParentID *uuid.UUID `json:"parent_id,omitempty"` + Order *int `json:"order,omitempty"` + OwnerFeePercent *float64 `json:"owner_fee_percent,omitempty"` + Metadata map[string]interface{} `json:"metadata,omitempty"` + + // Set when the field is sent as null (or "" for parent_id), which asks for the + // value to be removed. A field that is left out stays unchanged. + ClearParentID bool `json:"-"` + ClearOwnerFeePercent bool `json:"-"` +} + +// UnmarshalJSON tells an explicit null apart from a field that was left out, so a +// category can be detached from its parent and an owner fee override can be removed. +func (r *UpdateCategoryRequest) UnmarshalJSON(data []byte) error { + var raw map[string]json.RawMessage + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + isEmpty := func(key string, allowEmptyString bool) bool { + value, ok := raw[key] + if !ok { + return false + } + value = bytes.TrimSpace(value) + return bytes.Equal(value, []byte("null")) || (allowEmptyString && bytes.Equal(value, []byte(`""`))) + } + + clearParentID := isEmpty("parent_id", true) + clearOwnerFeePercent := isEmpty("owner_fee_percent", false) + if clearParentID { + // An empty string is not a valid UUID, so keep it away from the decoder + delete(raw, "parent_id") + cleaned, err := json.Marshal(raw) + if err != nil { + return err + } + data = cleaned + } + + type plain UpdateCategoryRequest + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + + *r = UpdateCategoryRequest(decoded) + r.ClearParentID = clearParentID + r.ClearOwnerFeePercent = clearOwnerFeePercent + return nil } type ListCategoriesRequest struct { @@ -39,18 +89,19 @@ type ListCategoriesRequest struct { // Category Response DTOs type CategoryResponse struct { - ID uuid.UUID `json:"id"` - OrganizationID uuid.UUID `json:"organization_id"` - OutletID *uuid.UUID `json:"outlet_id"` - ParentID *uuid.UUID `json:"parent_id,omitempty"` - ParentName *string `json:"parent_name,omitempty"` - Name string `json:"name"` - Description *string `json:"description"` - BusinessType string `json:"business_type"` - Order int `json:"order"` - Metadata map[string]interface{} `json:"metadata"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"organization_id"` + OutletID *uuid.UUID `json:"outlet_id"` + ParentID *uuid.UUID `json:"parent_id,omitempty"` + ParentName *string `json:"parent_name,omitempty"` + Name string `json:"name"` + Description *string `json:"description"` + BusinessType string `json:"business_type"` + Order int `json:"order"` + OwnerFeePercent *float64 `json:"owner_fee_percent"` + Metadata map[string]interface{} `json:"metadata"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } type ListCategoriesResponse struct { diff --git a/internal/contract/category_contract_test.go b/internal/contract/category_contract_test.go new file mode 100644 index 0000000..8ef29fa --- /dev/null +++ b/internal/contract/category_contract_test.go @@ -0,0 +1,48 @@ +package contract + +import ( + "encoding/json" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" +) + +func TestUpdateCategoryRequestTellsNullFromOmitted(t *testing.T) { + parentID := uuid.New() + + tests := []struct { + name string + body string + wantParentID *uuid.UUID + wantClear bool + wantClearFee bool + wantFee *float64 + wantNameIsSet bool + }{ + {name: "omitted leaves parent unchanged", body: `{"name":"Food"}`, wantNameIsSet: true}, + {name: "null detaches the parent", body: `{"parent_id":null}`, wantClear: true}, + {name: "empty string detaches the parent", body: `{"name":"Food","parent_id":""}`, wantClear: true, wantNameIsSet: true}, + {name: "uuid sets the parent", body: `{"parent_id":"` + parentID.String() + `"}`, wantParentID: &parentID}, + {name: "null removes the owner fee override", body: `{"owner_fee_percent":null}`, wantClearFee: true}, + {name: "number sets the owner fee", body: `{"owner_fee_percent":35}`, wantFee: func() *float64 { v := 35.0; return &v }()}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var req UpdateCategoryRequest + require.NoError(t, json.Unmarshal([]byte(tt.body), &req)) + + require.Equal(t, tt.wantParentID, req.ParentID) + require.Equal(t, tt.wantClear, req.ClearParentID) + require.Equal(t, tt.wantClearFee, req.ClearOwnerFeePercent) + require.Equal(t, tt.wantFee, req.OwnerFeePercent) + require.Equal(t, tt.wantNameIsSet, req.Name != nil) + }) + } +} + +func TestUpdateCategoryRequestRejectsInvalidParentID(t *testing.T) { + var req UpdateCategoryRequest + require.Error(t, json.Unmarshal([]byte(`{"parent_id":"not-a-uuid"}`), &req)) +} diff --git a/internal/entities/analytics.go b/internal/entities/analytics.go index 8446e86..2994c8a 100644 --- a/internal/entities/analytics.go +++ b/internal/entities/analytics.go @@ -143,16 +143,29 @@ type ProductAnalyticsPerCategory struct { // ProductAnalyticsPerParentCategory rolls the per-category figures up to the // top-level category. A category without a parent is its own group. type ProductAnalyticsPerParentCategory struct { - ParentCategoryID uuid.UUID `json:"parent_category_id"` - ParentCategoryName string `json:"parent_category_name"` - TotalRevenue float64 `json:"total_revenue"` - TotalQuantity int64 `json:"total_quantity"` - CategoryCount int64 `json:"category_count"` - ProductCount int64 `json:"product_count"` - OrderCount int64 `json:"order_count"` - TotalStandardHpp float64 `json:"total_standard_hpp"` - TotalFifoHpp float64 `json:"total_fifo_hpp"` - TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + ParentCategoryID uuid.UUID `json:"parent_category_id"` + ParentCategoryName string `json:"parent_category_name"` + // OwnerFeePercent is the owner share of this group's revenue, already resolved to the default + OwnerFeePercent float64 `json:"owner_fee_percent"` + TotalRevenue float64 `json:"total_revenue"` + TotalQuantity int64 `json:"total_quantity"` + CategoryCount int64 `json:"category_count"` + ProductCount int64 `json:"product_count"` + OrderCount int64 `json:"order_count"` + TotalStandardHpp float64 `json:"total_standard_hpp"` + TotalFifoHpp float64 `json:"total_fifo_hpp"` + TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + // TopProduct is filled by a separate query, so it is not a scanned column + TopProduct *ParentCategoryTopProduct `gorm:"-" json:"top_product"` +} + +// ParentCategoryTopProduct is the best-selling product of a parent category by revenue. +type ParentCategoryTopProduct struct { + ParentCategoryID uuid.UUID `json:"parent_category_id"` + ProductID uuid.UUID `json:"product_id"` + ProductName string `json:"product_name"` + QuantitySold int64 `json:"quantity_sold"` + Revenue float64 `json:"revenue"` } // ParentCategoryAnalyticsDetail is the drill-down for a single parent category: @@ -171,6 +184,8 @@ type BudgetCutOffWeek struct { WeekStart time.Time `json:"week_start"` Revenue float64 `json:"revenue"` OrderCount int64 `json:"order_count"` + // SDL is summed per parent category, each at its own owner fee percent + SDL float64 `json:"sdl"` } // DashboardOverview represents dashboard overview data diff --git a/internal/entities/category.go b/internal/entities/category.go index 3d0aafc..ca85c8f 100644 --- a/internal/entities/category.go +++ b/internal/entities/category.go @@ -41,8 +41,10 @@ type Category struct { Order int `gorm:"default:0" json:"order"` BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"` Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"` - CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` - UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` + // OwnerFeePercent overrides the owner's share in the parent category budget report; nil uses the default + OwnerFeePercent *float64 `gorm:"type:numeric(5,2)" json:"owner_fee_percent"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` Organization Organization `gorm:"foreignKey:OrganizationID" json:"organization,omitempty"` Products []Product `gorm:"foreignKey:CategoryID" json:"products,omitempty"` diff --git a/internal/mappers/category_mapper.go b/internal/mappers/category_mapper.go index bbfe984..8130bc2 100644 --- a/internal/mappers/category_mapper.go +++ b/internal/mappers/category_mapper.go @@ -59,14 +59,15 @@ func CreateCategoryRequestToEntity(req *models.CreateCategoryRequest) *entities. } return &entities.Category{ - OrganizationID: req.OrganizationID, - OutletID: req.OutletID, - ParentID: req.ParentID, - Name: req.Name, - Description: req.Description, - Order: req.Order, - BusinessType: "restaurant", - Metadata: metadata, + OrganizationID: req.OrganizationID, + OutletID: req.OutletID, + ParentID: req.ParentID, + Name: req.Name, + Description: req.Description, + Order: req.Order, + OwnerFeePercent: req.OwnerFeePercent, + BusinessType: "restaurant", + Metadata: metadata, } } @@ -94,18 +95,19 @@ func CategoryEntityToResponse(entity *entities.Category) *models.CategoryRespons } return &models.CategoryResponse{ - ID: entity.ID, - OrganizationID: entity.OrganizationID, - OutletID: entity.OutletID, - ParentID: entity.ParentID, - ParentName: parentName, - Name: entity.Name, - Description: entity.Description, - ImageURL: imageURL, - Order: entity.Order, - IsActive: true, - CreatedAt: entity.CreatedAt, - UpdatedAt: entity.UpdatedAt, + ID: entity.ID, + OrganizationID: entity.OrganizationID, + OutletID: entity.OutletID, + ParentID: entity.ParentID, + ParentName: parentName, + Name: entity.Name, + Description: entity.Description, + ImageURL: imageURL, + Order: entity.Order, + OwnerFeePercent: entity.OwnerFeePercent, + IsActive: true, + CreatedAt: entity.CreatedAt, + UpdatedAt: entity.UpdatedAt, } } @@ -134,11 +136,21 @@ func UpdateCategoryEntityFromRequest(entity *entities.Category, req *models.Upda entity.Order = *req.Order } + if req.ClearOwnerFeePercent { + entity.OwnerFeePercent = nil + } else if req.OwnerFeePercent != nil { + entity.OwnerFeePercent = req.OwnerFeePercent + } + if req.OutletID != nil { entity.OutletID = req.OutletID } - if req.ParentID != nil { + if req.ClearParentID { + // Drop the preloaded parent too, so the response stops reporting it + entity.ParentID = nil + entity.Parent = nil + } else if req.ParentID != nil { entity.ParentID = req.ParentID } } diff --git a/internal/models/analytics.go b/internal/models/analytics.go index 141dac2..1810dfd 100644 --- a/internal/models/analytics.go +++ b/internal/models/analytics.go @@ -306,16 +306,27 @@ type ProductAnalyticsPerParentCategoryResponse struct { } type ProductAnalyticsPerParentCategoryData struct { - ParentCategoryID uuid.UUID `json:"parent_category_id"` - ParentCategoryName string `json:"parent_category_name"` - TotalRevenue float64 `json:"total_revenue"` - TotalQuantity int64 `json:"total_quantity"` - CategoryCount int64 `json:"category_count"` - ProductCount int64 `json:"product_count"` - OrderCount int64 `json:"order_count"` - TotalStandardHpp float64 `json:"total_standard_hpp"` - TotalFifoHpp float64 `json:"total_fifo_hpp"` - TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + ParentCategoryID uuid.UUID `json:"parent_category_id"` + ParentCategoryName string `json:"parent_category_name"` + OwnerFeePercent float64 `json:"owner_fee_percent"` + SDL float64 `json:"sdl"` + TotalRevenue float64 `json:"total_revenue"` + TotalQuantity int64 `json:"total_quantity"` + CategoryCount int64 `json:"category_count"` + ProductCount int64 `json:"product_count"` + OrderCount int64 `json:"order_count"` + TotalStandardHpp float64 `json:"total_standard_hpp"` + TotalFifoHpp float64 `json:"total_fifo_hpp"` + TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + TopProduct *ParentCategoryTopProduct `json:"top_product"` +} + +// ParentCategoryTopProduct is the best-selling product of a parent category by revenue. +type ParentCategoryTopProduct struct { + ProductID uuid.UUID `json:"product_id"` + ProductName string `json:"product_name"` + QuantitySold int64 `json:"quantity_sold"` + Revenue float64 `json:"revenue"` } // ParentCategoryAnalyticsDetailRequest represents the request for the drill-down of one parent category @@ -342,14 +353,17 @@ type ParentCategoryAnalyticsDetailResponse struct { } type ParentCategoryAnalyticsDetailSummary struct { - TotalRevenue float64 `json:"total_revenue"` - TotalQuantity int64 `json:"total_quantity"` - CategoryCount int64 `json:"category_count"` - ProductCount int64 `json:"product_count"` - OrderCount int64 `json:"order_count"` - TotalStandardHpp float64 `json:"total_standard_hpp"` - TotalFifoHpp float64 `json:"total_fifo_hpp"` - TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + OwnerFeePercent float64 `json:"owner_fee_percent"` + SDL float64 `json:"sdl"` + TotalRevenue float64 `json:"total_revenue"` + TotalQuantity int64 `json:"total_quantity"` + CategoryCount int64 `json:"category_count"` + ProductCount int64 `json:"product_count"` + OrderCount int64 `json:"order_count"` + TotalStandardHpp float64 `json:"total_standard_hpp"` + TotalFifoHpp float64 `json:"total_fifo_hpp"` + TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"` + TopProduct *ParentCategoryTopProduct `json:"top_product"` } type ParentCategoryAnalyticsDetailData struct { @@ -406,7 +420,7 @@ type BudgetPeriod struct { Revenue float64 `json:"revenue"` OrderCount int64 `json:"order_count"` LimitPurchase float64 `json:"limit_purchase"` - LimitOwner float64 `json:"limit_owner"` + SDL float64 `json:"sdl"` LimitTeam float64 `json:"limit_team"` } diff --git a/internal/models/category.go b/internal/models/category.go index 0d20cd4..7953863 100644 --- a/internal/models/category.go +++ b/internal/models/category.go @@ -20,36 +20,43 @@ type Category struct { } type CreateCategoryRequest struct { - OrganizationID uuid.UUID `validate:"required"` - OutletID *uuid.UUID - ParentID *uuid.UUID - Name string `validate:"required,min=1,max=255"` - Description *string `validate:"omitempty,max=1000"` - ImageURL *string `validate:"omitempty,url"` - Order int `validate:"min=0"` + OrganizationID uuid.UUID `validate:"required"` + OutletID *uuid.UUID + ParentID *uuid.UUID + Name string `validate:"required,min=1,max=255"` + Description *string `validate:"omitempty,max=1000"` + ImageURL *string `validate:"omitempty,url"` + Order int `validate:"min=0"` + OwnerFeePercent *float64 `validate:"omitempty,min=0,max=100"` } type UpdateCategoryRequest struct { - Name *string `validate:"omitempty,min=1,max=255"` - Description *string `validate:"omitempty,max=1000"` - ImageURL *string `validate:"omitempty,url"` - OutletID *uuid.UUID - ParentID *uuid.UUID - Order *int `validate:"omitempty,min=0"` - IsActive *bool + Name *string `validate:"omitempty,min=1,max=255"` + Description *string `validate:"omitempty,max=1000"` + ImageURL *string `validate:"omitempty,url"` + OutletID *uuid.UUID + ParentID *uuid.UUID + Order *int `validate:"omitempty,min=0"` + OwnerFeePercent *float64 `validate:"omitempty,min=0,max=100"` + IsActive *bool + + // Clear flags remove the value; a nil pointer above only means "leave unchanged" + ClearParentID bool + ClearOwnerFeePercent bool } type CategoryResponse struct { - ID uuid.UUID - OrganizationID uuid.UUID - OutletID *uuid.UUID - ParentID *uuid.UUID - ParentName *string - Name string - Description *string - ImageURL *string - Order int - IsActive bool - CreatedAt time.Time - UpdatedAt time.Time + ID uuid.UUID + OrganizationID uuid.UUID + OutletID *uuid.UUID + ParentID *uuid.UUID + ParentName *string + Name string + Description *string + ImageURL *string + Order int + OwnerFeePercent *float64 + IsActive bool + CreatedAt time.Time + UpdatedAt time.Time } diff --git a/internal/processor/analytics_processor.go b/internal/processor/analytics_processor.go index 9764551..921015e 100644 --- a/internal/processor/analytics_processor.go +++ b/internal/processor/analytics_processor.go @@ -413,9 +413,22 @@ func (p *AnalyticsProcessorImpl) GetProductAnalyticsPerParentCategory(ctx contex // Transform data var resultData []models.ProductAnalyticsPerParentCategoryData for _, data := range analyticsData { + var topProduct *models.ParentCategoryTopProduct + if data.TopProduct != nil { + topProduct = &models.ParentCategoryTopProduct{ + ProductID: data.TopProduct.ProductID, + ProductName: data.TopProduct.ProductName, + QuantitySold: data.TopProduct.QuantitySold, + Revenue: data.TopProduct.Revenue, + } + } + resultData = append(resultData, models.ProductAnalyticsPerParentCategoryData{ + TopProduct: topProduct, ParentCategoryID: data.ParentCategoryID, ParentCategoryName: data.ParentCategoryName, + OwnerFeePercent: data.OwnerFeePercent, + SDL: data.TotalRevenue * data.OwnerFeePercent / 100, TotalRevenue: data.TotalRevenue, TotalQuantity: data.TotalQuantity, CategoryCount: data.CategoryCount, @@ -500,6 +513,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co summary := models.ParentCategoryAnalyticsDetailSummary{} if detail.Summary != nil { summary = models.ParentCategoryAnalyticsDetailSummary{ + TopProduct: topProductByRevenue(detail.Products), + OwnerFeePercent: detail.Summary.OwnerFeePercent, + SDL: detail.Summary.TotalRevenue * detail.Summary.OwnerFeePercent / 100, TotalRevenue: detail.Summary.TotalRevenue, TotalQuantity: detail.Summary.TotalQuantity, CategoryCount: detail.Summary.CategoryCount, @@ -515,6 +531,10 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co if err != nil { return nil, err } + // The block covers a single parent category, so it reports that category's own fee + if detail.Summary != nil { + budget.Percentages.Owner = detail.Summary.OwnerFeePercent + } return &models.ParentCategoryAnalyticsDetailResponse{ OrganizationID: req.OrganizationID, @@ -530,6 +550,30 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co }, nil } +// topProductByRevenue picks the best-selling product of a parent category. A product +// can span several rows (one per outlet price), so the rows are added up per product +// first. Ties keep the product that was seen first. +func topProductByRevenue(products []*entities.ProductAnalytics) *models.ParentCategoryTopProduct { + totals := make(map[uuid.UUID]*models.ParentCategoryTopProduct) + for _, product := range products { + total, ok := totals[product.ProductID] + if !ok { + total = &models.ParentCategoryTopProduct{ProductID: product.ProductID, ProductName: product.ProductName} + totals[product.ProductID] = total + } + total.QuantitySold += product.QuantitySold + total.Revenue += product.Revenue + } + + var top *models.ParentCategoryTopProduct + for _, product := range products { + if total := totals[product.ProductID]; top == nil || total.Revenue > top.Revenue { + top = total + } + } + return top +} + // startOfWeek returns the Monday 00:00 of the week containing t, in t's own location. func startOfWeek(t time.Time) time.Time { daysSinceMonday := (int(t.Weekday()) + 6) % 7 @@ -542,15 +586,16 @@ func endOfWeek(t time.Time) time.Time { return startOfWeek(t).AddDate(0, 0, 7).Add(-time.Nanosecond) } -// newBudgetPeriod splits a period's revenue into the spending limits. -func newBudgetPeriod(start, end time.Time, revenue float64, orderCount int64) models.BudgetPeriod { +// newBudgetPeriod splits a period's revenue into the spending limits. The owner limit +// is passed in because a parent category can carry its own owner fee percent. +func newBudgetPeriod(start, end time.Time, revenue, sdl float64, orderCount int64) models.BudgetPeriod { return models.BudgetPeriod{ PeriodStart: start, PeriodEnd: end, Revenue: revenue, OrderCount: orderCount, LimitPurchase: revenue * constants.BudgetLimitPurchasePercent / 100, - LimitOwner: revenue * constants.BudgetLimitOwnerPercent / 100, + SDL: sdl, LimitTeam: revenue * constants.BudgetLimitTeamPercent / 100, } } @@ -588,22 +633,24 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza var ( totalRevenue float64 + totalSDL float64 totalOrders int64 monthOrder []string monthAccumulator = map[string]*models.BudgetMonthPeriod{} ) for week := cutOffFrom; !week.After(cutOffTo); week = week.AddDate(0, 0, 7) { - var revenue float64 + var revenue, sdl float64 var orderCount int64 if row, ok := rowsByWeek[week.Format("2006-01-02")]; ok { - revenue, orderCount = row.Revenue, row.OrderCount + revenue, sdl, orderCount = row.Revenue, row.SDL, row.OrderCount } - period := newBudgetPeriod(week, endOfWeek(week), revenue, orderCount) + period := newBudgetPeriod(week, endOfWeek(week), revenue, sdl, orderCount) budget.Weekly = append(budget.Weekly, period) totalRevenue += revenue + totalSDL += sdl totalOrders += orderCount // A week belongs to the month of its Monday, so every week is counted once @@ -618,6 +665,7 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza month.WeekCount++ month.PeriodEnd = period.PeriodEnd month.Revenue += revenue + month.SDL += sdl month.OrderCount += orderCount } @@ -626,11 +674,11 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza budget.Monthly = append(budget.Monthly, models.BudgetMonthPeriod{ Month: month.Month, WeekCount: month.WeekCount, - BudgetPeriod: newBudgetPeriod(month.PeriodStart, month.PeriodEnd, month.Revenue, month.OrderCount), + BudgetPeriod: newBudgetPeriod(month.PeriodStart, month.PeriodEnd, month.Revenue, month.SDL, month.OrderCount), }) } - budget.Total = newBudgetPeriod(cutOffFrom, cutOffTo, totalRevenue, totalOrders) + budget.Total = newBudgetPeriod(cutOffFrom, cutOffTo, totalRevenue, totalSDL, totalOrders) return budget, nil } diff --git a/internal/processor/analytics_processor_test.go b/internal/processor/analytics_processor_test.go index 33f9f79..fe84ea4 100644 --- a/internal/processor/analytics_processor_test.go +++ b/internal/processor/analytics_processor_test.go @@ -18,6 +18,7 @@ type analyticsRepositoryStub struct { purchasingResult *entities.PurchasingAnalytics purchasingTeam *entities.PurchaseTeamFilter budgetCutOffWeeks []*entities.BudgetCutOffWeek + parentCategories []*entities.ProductAnalyticsPerParentCategory profitLossResult *entities.ProfitLossAnalytics exclusiveSummaryResults []*entities.ExclusiveSummaryAnalytics bankBalances []entities.ExclusiveSummaryBankBalance @@ -49,8 +50,8 @@ func (analyticsRepositoryStub) GetProductAnalyticsPerCategory(context.Context, u return nil, nil } -func (analyticsRepositoryStub) GetProductAnalyticsPerParentCategory(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.ProductAnalyticsPerParentCategory, error) { - return nil, nil +func (s analyticsRepositoryStub) GetProductAnalyticsPerParentCategory(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.ProductAnalyticsPerParentCategory, error) { + return s.parentCategories, nil } func (analyticsRepositoryStub) GetParentCategoryAnalyticsDetail(context.Context, uuid.UUID, *uuid.UUID, uuid.UUID, time.Time, time.Time) (*entities.ParentCategoryAnalyticsDetail, error) { @@ -604,3 +605,60 @@ func TestPaymentMethodAnalytics_EnakPointIsNotCashIn(t *testing.T) { assert.Zero(t, byType["point"].Percentage) assert.Equal(t, int64(30000), byType["point"].PointsUsed) } + +// A parent category with its own owner fee percent moves the owner limit away from the +// default share, while purchase and team stay on the default split of revenue. +func TestAnalyticsProcessorParentCategoryUsesOwnerFeePercent(t *testing.T) { + monday := time.Date(2026, 9, 28, 0, 0, 0, 0, time.UTC) + processor := NewAnalyticsProcessorImpl(&analyticsRepositoryStub{ + parentCategories: []*entities.ProductAnalyticsPerParentCategory{ + {ParentCategoryName: "Food", OwnerFeePercent: constants.BudgetLimitOwnerPercent, TotalRevenue: 1000}, + {ParentCategoryName: "Drink", OwnerFeePercent: 35, TotalRevenue: 2000}, + }, + budgetCutOffWeeks: []*entities.BudgetCutOffWeek{ + // 1000 at the default 20% plus 2000 at 35% + {WeekStart: monday, Revenue: 3000, OrderCount: 4, SDL: 900}, + }, + }, expenseRepositoryStub{}) + + result, err := processor.GetProductAnalyticsPerParentCategory(context.Background(), &models.ProductAnalyticsPerParentCategoryRequest{ + OrganizationID: uuid.New(), + DateFrom: monday, + DateTo: monday.AddDate(0, 0, 6), + }) + + require.NoError(t, err) + require.Len(t, result.Data, 2) + require.Equal(t, float64(20), result.Data[0].OwnerFeePercent) + require.Equal(t, float64(200), result.Data[0].SDL) + require.Equal(t, float64(35), result.Data[1].OwnerFeePercent) + require.Equal(t, float64(700), result.Data[1].SDL) + + require.Len(t, result.Budget.Weekly, 1) + require.Equal(t, float64(900), result.Budget.Weekly[0].SDL) + require.Equal(t, float64(1800), result.Budget.Weekly[0].LimitPurchase) + require.Equal(t, float64(600), result.Budget.Weekly[0].LimitTeam) + require.Len(t, result.Budget.Monthly, 1) + require.Equal(t, float64(900), result.Budget.Monthly[0].SDL) + require.Equal(t, float64(900), result.Budget.Total.SDL) +} + +// A product sold at several outlet prices comes back as several rows, which must be +// added up before the best seller is picked. +func TestTopProductByRevenueAddsUpRowsOfTheSameProduct(t *testing.T) { + split, single := uuid.New(), uuid.New() + + top := topProductByRevenue([]*entities.ProductAnalytics{ + {ProductID: single, ProductName: "Es Teh", QuantitySold: 5, Revenue: 500}, + {ProductID: split, ProductName: "Nasi Goreng", QuantitySold: 2, Revenue: 300}, + {ProductID: split, ProductName: "Nasi Goreng", QuantitySold: 2, Revenue: 300}, + }) + + require.NotNil(t, top) + require.Equal(t, split, top.ProductID) + require.Equal(t, "Nasi Goreng", top.ProductName) + require.Equal(t, int64(4), top.QuantitySold) + require.Equal(t, float64(600), top.Revenue) + + require.Nil(t, topProductByRevenue(nil)) +} diff --git a/internal/processor/budget_cutoff_test.go b/internal/processor/budget_cutoff_test.go index 7386b4c..3feafa6 100644 --- a/internal/processor/budget_cutoff_test.go +++ b/internal/processor/budget_cutoff_test.go @@ -85,7 +85,7 @@ func TestBuildBudgetCutOffAppliesLimits(t *testing.T) { weekStart := time.Date(2026, 8, 3, 0, 0, 0, 0, loc) stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{ - {WeekStart: weekStart, Revenue: 10_000_000, OrderCount: 120}, + {WeekStart: weekStart, Revenue: 10_000_000, OrderCount: 120, SDL: 2_500_000}, }} processor := &AnalyticsProcessorImpl{analyticsRepo: stub} @@ -93,16 +93,18 @@ func TestBuildBudgetCutOffAppliesLimits(t *testing.T) { require.NoError(t, err) require.Len(t, budget.Weekly, 1) - // 60 / 20 / 20 of the week's revenue + // 60 / 20 of the week's revenue; the owner limit is whatever the repository + // summed from each parent category's own fee percent week := budget.Weekly[0] require.Equal(t, float64(6_000_000), week.LimitPurchase) - require.Equal(t, float64(2_000_000), week.LimitOwner) + require.Equal(t, float64(2_500_000), week.SDL) require.Equal(t, float64(2_000_000), week.LimitTeam) require.Equal(t, int64(120), week.OrderCount) // Totals mirror the single week require.Equal(t, week.Revenue, budget.Total.Revenue) require.Equal(t, week.LimitPurchase, budget.Total.LimitPurchase) + require.Equal(t, week.SDL, budget.Total.SDL) } func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) { diff --git a/internal/repository/analytics_repository.go b/internal/repository/analytics_repository.go index a4fddcb..7082b17 100644 --- a/internal/repository/analytics_repository.go +++ b/internal/repository/analytics_repository.go @@ -600,6 +600,7 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte Select(` pc.id as parent_category_id, pc.name as parent_category_name, + COALESCE(pc.owner_fee_percent, ?) as owner_fee_percent, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as total_revenue, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.quantity - COALESCE(oi.refund_quantity, 0) ELSE 0 END), 0) as total_quantity, COUNT(DISTINCT c.id) as category_count, @@ -608,7 +609,7 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(shpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_standard_hpp, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_cost * ((oi.quantity - COALESCE(oi.refund_quantity, 0))::float / NULLIF(oi.quantity, 0)) ELSE 0 END), 0) as total_fifo_hpp, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(mahpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_moving_average_hpp - `). + `, constants.BudgetLimitOwnerPercent). Joins("JOIN products p ON oi.product_id = p.id"). Joins("JOIN categories c ON p.category_id = c.id"). // Categories without a parent roll up to themselves, so top-level categories still appear @@ -640,11 +641,56 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte query = r.resolveOutletID(query, outletID, "o.outlet_id") err := query. - Group("pc.id, pc.name"). + Group("pc.id, pc.name, pc.owner_fee_percent"). Order("pc.name ASC"). Scan(&results).Error + if err != nil || len(results) == 0 { + return results, err + } - return results, err + // Best-selling product of each parent category. DISTINCT ON keeps the first row per + // parent category, which the ordering makes the one with the highest revenue. + var topProducts []*entities.ParentCategoryTopProduct + topQuery := r.db.WithContext(ctx). + Table("order_items oi"). + Select(` + DISTINCT ON (pc.id) + pc.id as parent_category_id, + p.id as product_id, + p.name as product_name, + COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.quantity - COALESCE(oi.refund_quantity, 0) ELSE 0 END), 0) as quantity_sold, + COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as revenue + `). + Joins("JOIN products p ON oi.product_id = p.id"). + Joins("JOIN categories c ON p.category_id = c.id"). + Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_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.is_refund = ?", false). + Where("o.payment_status = ?", entities.PaymentStatusCompleted). + Where("oi.status != ?", entities.OrderItemStatusCancelled). + Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo) + + topQuery = r.resolveOutletID(topQuery, outletID, "o.outlet_id") + + err = topQuery. + Group("pc.id, p.id, p.name"). + Order("pc.id, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) DESC, p.name ASC"). + Scan(&topProducts).Error + if err != nil { + return nil, err + } + + topByParent := make(map[uuid.UUID]*entities.ParentCategoryTopProduct, len(topProducts)) + for _, product := range topProducts { + topByParent[product.ParentCategoryID] = product + } + for _, result := range results { + result.TopProduct = topByParent[result.ParentCategoryID] + } + + return results, nil } // movingAverageHppSubquery builds the per-product moving-average HPP lookup shared by @@ -691,12 +737,13 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C // Resolve the category first so the endpoint still identifies the category when it // has no sales in the requested range, and rejects ids from another organization. var parent struct { - ID uuid.UUID - Name string + ID uuid.UUID + Name string + OwnerFeePercent float64 } if err := r.db.WithContext(ctx). Table("categories"). - Select("id, name"). + Select("id, name, COALESCE(owner_fee_percent, ?) as owner_fee_percent", constants.BudgetLimitOwnerPercent). Where("id = ? AND organization_id = ?", parentCategoryID, organizationID). Scan(&parent).Error; err != nil { return nil, err @@ -732,6 +779,7 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C } summary.ParentCategoryID = parent.ID summary.ParentCategoryName = parent.Name + summary.OwnerFeePercent = parent.OwnerFeePercent detail.Summary = summary // Sub-category rows. @@ -810,12 +858,15 @@ func (r *AnalyticsRepositoryImpl) GetBudgetCutOffWeekly(ctx context.Context, org Select(` DATE_TRUNC('week', o.created_at) as week_start, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as revenue, + COALESCE(SUM((CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END) * COALESCE(pc.owner_fee_percent, ?) / 100.0), 0) as sdl, COUNT(DISTINCT oi.order_id) as order_count - `). + `, constants.BudgetLimitOwnerPercent). // products and categories are joined to keep the scope identical to the report // the block is attached to, even when no parent category filter is applied Joins("JOIN products p ON oi.product_id = p.id"). Joins("JOIN categories c ON p.category_id = c.id"). + // The owner fee lives on the parent category; a category without a parent is its own group + Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)"). Joins("JOIN orders o ON oi.order_id = o.id"). Where("o.organization_id = ?", organizationID). Where("o.is_void = ?", false). diff --git a/internal/transformer/analytics_transformer.go b/internal/transformer/analytics_transformer.go index a6267cc..bb09349 100644 --- a/internal/transformer/analytics_transformer.go +++ b/internal/transformer/analytics_transformer.go @@ -405,6 +405,9 @@ func ProductAnalyticsPerParentCategoryModelToContract(resp *models.ProductAnalyt data = append(data, contract.ProductAnalyticsPerParentCategoryData{ ParentCategoryID: item.ParentCategoryID, ParentCategoryName: item.ParentCategoryName, + OwnerFeePercent: item.OwnerFeePercent, + TopProduct: parentCategoryTopProductModelToContract(item.TopProduct), + SDL: item.SDL, TotalRevenue: item.TotalRevenue, TotalQuantity: item.TotalQuantity, CategoryCount: item.CategoryCount, @@ -427,6 +430,19 @@ func ProductAnalyticsPerParentCategoryModelToContract(resp *models.ProductAnalyt } } +// parentCategoryTopProductModelToContract converts the top product of a parent category to contract +func parentCategoryTopProductModelToContract(product *models.ParentCategoryTopProduct) *contract.ParentCategoryTopProduct { + if product == nil { + return nil + } + return &contract.ParentCategoryTopProduct{ + ProductID: product.ProductID, + ProductName: product.ProductName, + QuantitySold: product.QuantitySold, + Revenue: product.Revenue, + } +} + // budgetPeriodModelToContract converts one budget period to contract func budgetPeriodModelToContract(period models.BudgetPeriod) contract.BudgetPeriod { return contract.BudgetPeriod{ @@ -435,7 +451,7 @@ func budgetPeriodModelToContract(period models.BudgetPeriod) contract.BudgetPeri Revenue: period.Revenue, OrderCount: period.OrderCount, LimitPurchase: period.LimitPurchase, - LimitOwner: period.LimitOwner, + SDL: period.SDL, LimitTeam: period.LimitTeam, } } @@ -548,6 +564,9 @@ func ParentCategoryAnalyticsDetailModelToContract(resp *models.ParentCategoryAna ParentCategoryID: resp.ParentCategoryID, ParentCategoryName: resp.ParentCategoryName, Summary: contract.ParentCategoryAnalyticsDetailSummary{ + OwnerFeePercent: resp.Summary.OwnerFeePercent, + TopProduct: parentCategoryTopProductModelToContract(resp.Summary.TopProduct), + SDL: resp.Summary.SDL, TotalRevenue: resp.Summary.TotalRevenue, TotalQuantity: resp.Summary.TotalQuantity, CategoryCount: resp.Summary.CategoryCount, diff --git a/internal/transformer/category_transformer.go b/internal/transformer/category_transformer.go index e20b831..1c6abfb 100644 --- a/internal/transformer/category_transformer.go +++ b/internal/transformer/category_transformer.go @@ -12,25 +12,30 @@ func CreateCategoryRequestToModel(apctx *appcontext.ContextInfo, req *contract.C order = *req.Order } return &models.CreateCategoryRequest{ - OrganizationID: apctx.OrganizationID, - OutletID: req.OutletID, - ParentID: req.ParentID, - Name: req.Name, - Description: req.Description, - ImageURL: nil, - Order: order, + OrganizationID: apctx.OrganizationID, + OutletID: req.OutletID, + ParentID: req.ParentID, + Name: req.Name, + Description: req.Description, + ImageURL: nil, + Order: order, + OwnerFeePercent: req.OwnerFeePercent, } } func UpdateCategoryRequestToModel(req *contract.UpdateCategoryRequest) *models.UpdateCategoryRequest { return &models.UpdateCategoryRequest{ - Name: req.Name, - Description: req.Description, - ImageURL: nil, - OutletID: req.OutletID, - ParentID: req.ParentID, - Order: req.Order, - IsActive: nil, + Name: req.Name, + Description: req.Description, + ImageURL: nil, + OutletID: req.OutletID, + ParentID: req.ParentID, + Order: req.Order, + OwnerFeePercent: req.OwnerFeePercent, + IsActive: nil, + + ClearParentID: req.ClearParentID, + ClearOwnerFeePercent: req.ClearOwnerFeePercent, } } @@ -40,18 +45,19 @@ func CategoryModelResponseToResponse(cat *models.CategoryResponse) *contract.Cat } return &contract.CategoryResponse{ - ID: cat.ID, - OrganizationID: cat.OrganizationID, - OutletID: cat.OutletID, - ParentID: cat.ParentID, - ParentName: cat.ParentName, - Name: cat.Name, - Description: cat.Description, - BusinessType: "restaurant", - Order: cat.Order, - Metadata: map[string]interface{}{}, - CreatedAt: cat.CreatedAt, - UpdatedAt: cat.UpdatedAt, + ID: cat.ID, + OrganizationID: cat.OrganizationID, + OutletID: cat.OutletID, + ParentID: cat.ParentID, + ParentName: cat.ParentName, + Name: cat.Name, + Description: cat.Description, + BusinessType: "restaurant", + Order: cat.Order, + OwnerFeePercent: cat.OwnerFeePercent, + Metadata: map[string]interface{}{}, + CreatedAt: cat.CreatedAt, + UpdatedAt: cat.UpdatedAt, } } diff --git a/internal/validator/category_validator.go b/internal/validator/category_validator.go index 125ed6e..a390035 100644 --- a/internal/validator/category_validator.go +++ b/internal/validator/category_validator.go @@ -37,6 +37,10 @@ func (v *CategoryValidatorImpl) ValidateCreateCategoryRequest(req *contract.Crea return errors.New("description cannot exceed 1000 characters"), constants.MalformedFieldErrorCode } + if req.OwnerFeePercent != nil && (*req.OwnerFeePercent < 0 || *req.OwnerFeePercent > 100) { + return errors.New("owner_fee_percent must be between 0 and 100"), constants.MalformedFieldErrorCode + } + if req.BusinessType != nil && strings.TrimSpace(*req.BusinessType) != "" { validBusinessTypes := map[string]bool{ "restaurant": true, @@ -59,7 +63,7 @@ func (v *CategoryValidatorImpl) ValidateUpdateCategoryRequest(req *contract.Upda } // At least one field should be provided for update - if req.Name == nil && req.Description == nil && req.BusinessType == nil && req.ParentID == nil && req.Metadata == nil { + if req.Name == nil && req.Description == nil && req.BusinessType == nil && req.ParentID == nil && req.Metadata == nil && req.OwnerFeePercent == nil && req.Order == nil && req.OutletID == nil && !req.ClearParentID && !req.ClearOwnerFeePercent { return errors.New("at least one field must be provided for update"), constants.MissingFieldErrorCode } @@ -76,6 +80,10 @@ func (v *CategoryValidatorImpl) ValidateUpdateCategoryRequest(req *contract.Upda return errors.New("description cannot exceed 1000 characters"), constants.MalformedFieldErrorCode } + if req.OwnerFeePercent != nil && (*req.OwnerFeePercent < 0 || *req.OwnerFeePercent > 100) { + return errors.New("owner_fee_percent must be between 0 and 100"), constants.MalformedFieldErrorCode + } + if req.BusinessType != nil && strings.TrimSpace(*req.BusinessType) != "" { validBusinessTypes := map[string]bool{ "restaurant": true, diff --git a/migrations/000100_add_owner_fee_percent_to_categories.down.sql b/migrations/000100_add_owner_fee_percent_to_categories.down.sql new file mode 100644 index 0000000..2273a14 --- /dev/null +++ b/migrations/000100_add_owner_fee_percent_to_categories.down.sql @@ -0,0 +1 @@ +ALTER TABLE categories DROP COLUMN owner_fee_percent; diff --git a/migrations/000100_add_owner_fee_percent_to_categories.up.sql b/migrations/000100_add_owner_fee_percent_to_categories.up.sql new file mode 100644 index 0000000..d370739 --- /dev/null +++ b/migrations/000100_add_owner_fee_percent_to_categories.up.sql @@ -0,0 +1,4 @@ +-- The owner's share of revenue in the parent category budget report. NULL keeps the +-- default share, so only the parent categories with a different fee carry a value. +ALTER TABLE categories ADD COLUMN owner_fee_percent NUMERIC(5,2) + CONSTRAINT chk_categories_owner_fee_percent CHECK (owner_fee_percent >= 0 AND owner_fee_percent <= 100); -- 2.54.0 From b59b7b4ddd8da2d272f23767fdad5ee8ea706fa1 Mon Sep 17 00:00:00 2001 From: efrilm Date: Sat, 3 Oct 2026 00:15:43 +0700 Subject: [PATCH 11/12] feat: update parent category detail --- internal/contract/analytics_contract.go | 3 +++ internal/models/analytics.go | 3 +++ internal/processor/analytics_processor.go | 11 +++++++++++ internal/transformer/analytics_transformer.go | 3 +++ 4 files changed, 20 insertions(+) diff --git a/internal/contract/analytics_contract.go b/internal/contract/analytics_contract.go index 97ec2a8..d5dccfe 100644 --- a/internal/contract/analytics_contract.go +++ b/internal/contract/analytics_contract.go @@ -329,6 +329,9 @@ type ParentCategoryAnalyticsDetailSummary struct { type ParentCategoryAnalyticsDetailData struct { CategoryID uuid.UUID `json:"category_id"` CategoryName string `json:"category_name"` + OwnerFeePercent float64 `json:"owner_fee_percent"` + SDL float64 `json:"sdl"` + TopProduct *ParentCategoryTopProduct `json:"top_product"` TotalRevenue float64 `json:"total_revenue"` TotalQuantity int64 `json:"total_quantity"` ProductCount int64 `json:"product_count"` diff --git a/internal/models/analytics.go b/internal/models/analytics.go index 1810dfd..0e23750 100644 --- a/internal/models/analytics.go +++ b/internal/models/analytics.go @@ -369,6 +369,9 @@ type ParentCategoryAnalyticsDetailSummary struct { type ParentCategoryAnalyticsDetailData struct { CategoryID uuid.UUID `json:"category_id"` CategoryName string `json:"category_name"` + OwnerFeePercent float64 `json:"owner_fee_percent"` + SDL float64 `json:"sdl"` + TopProduct *ParentCategoryTopProduct `json:"top_product"` TotalRevenue float64 `json:"total_revenue"` TotalQuantity int64 `json:"total_quantity"` ProductCount int64 `json:"product_count"` diff --git a/internal/processor/analytics_processor.go b/internal/processor/analytics_processor.go index 921015e..80d8bdd 100644 --- a/internal/processor/analytics_processor.go +++ b/internal/processor/analytics_processor.go @@ -469,7 +469,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co // Bucket the product rows by the category they belong to productsByCategory := make(map[uuid.UUID][]models.ParentCategoryAnalyticsProductData) + productRowsByCategory := make(map[uuid.UUID][]*entities.ProductAnalytics) for _, product := range detail.Products { + productRowsByCategory[product.CategoryID] = append(productRowsByCategory[product.CategoryID], product) productsByCategory[product.CategoryID] = append(productsByCategory[product.CategoryID], models.ParentCategoryAnalyticsProductData{ ProductID: product.ProductID, ProductName: product.ProductName, @@ -489,6 +491,12 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co }) } + // Sub-categories take the owner fee of the parent category they sit under + var ownerFeePercent float64 + if detail.Summary != nil { + ownerFeePercent = detail.Summary.OwnerFeePercent + } + categories := make([]models.ParentCategoryAnalyticsDetailData, 0, len(detail.Categories)) for _, category := range detail.Categories { products := productsByCategory[category.CategoryID] @@ -499,6 +507,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co categories = append(categories, models.ParentCategoryAnalyticsDetailData{ CategoryID: category.CategoryID, CategoryName: category.CategoryName, + OwnerFeePercent: ownerFeePercent, + SDL: category.TotalRevenue * ownerFeePercent / 100, + TopProduct: topProductByRevenue(productRowsByCategory[category.CategoryID]), TotalRevenue: category.TotalRevenue, TotalQuantity: category.TotalQuantity, ProductCount: category.ProductCount, diff --git a/internal/transformer/analytics_transformer.go b/internal/transformer/analytics_transformer.go index bb09349..0166d2a 100644 --- a/internal/transformer/analytics_transformer.go +++ b/internal/transformer/analytics_transformer.go @@ -544,6 +544,9 @@ func ParentCategoryAnalyticsDetailModelToContract(resp *models.ParentCategoryAna categories = append(categories, contract.ParentCategoryAnalyticsDetailData{ CategoryID: category.CategoryID, CategoryName: category.CategoryName, + OwnerFeePercent: category.OwnerFeePercent, + SDL: category.SDL, + TopProduct: parentCategoryTopProductModelToContract(category.TopProduct), TotalRevenue: category.TotalRevenue, TotalQuantity: category.TotalQuantity, ProductCount: category.ProductCount, -- 2.54.0 From 117e3529aa0885b76c8a7e57b1f9dbd2f623041c Mon Sep 17 00:00:00 2001 From: efrilm Date: Sun, 4 Oct 2026 21:54:13 +0700 Subject: [PATCH 12/12] feat: update profit sharing --- docs/migrasi-profit-sharing.md | 289 ++++++++++++++++++ internal/constants/budget.go | 12 +- internal/contract/analytics_contract.go | 18 +- internal/contract/category_contract.go | 3 + internal/entities/category.go | 10 +- internal/mappers/category_mapper.go | 12 + internal/mappers/category_mapper_test.go | 34 +++ internal/middleware/auth_middleware.go | 2 +- internal/models/analytics.go | 18 +- internal/models/category.go | 4 + internal/processor/analytics_processor.go | 24 +- .../processor/analytics_processor_test.go | 7 +- internal/processor/budget_cutoff_test.go | 22 +- internal/processor/team.go | 17 +- internal/processor/team_test.go | 64 ++++ internal/repository/analytics_repository.go | 14 +- internal/router/router.go | 6 +- internal/service/report_service.go | 32 +- internal/transformer/analytics_transformer.go | 18 +- internal/transformer/category_transformer.go | 3 + internal/validator/category_validator.go | 2 +- .../000101_add_is_team_to_categories.down.sql | 1 + .../000101_add_is_team_to_categories.up.sql | 4 + 23 files changed, 521 insertions(+), 95 deletions(-) create mode 100644 docs/migrasi-profit-sharing.md create mode 100644 internal/mappers/category_mapper_test.go create mode 100644 internal/processor/team_test.go create mode 100644 migrations/000101_add_is_team_to_categories.down.sql create mode 100644 migrations/000101_add_is_team_to_categories.up.sql diff --git a/docs/migrasi-profit-sharing.md b/docs/migrasi-profit-sharing.md new file mode 100644 index 0000000..32a838c --- /dev/null +++ b/docs/migrasi-profit-sharing.md @@ -0,0 +1,289 @@ +# Migrasi profit sharing + +4 Oktober 2026 + +## Ringkasan + +Ada tiga perubahan di backend: + +1. **Parent category bisa ditandai bukan team.** Kategori punya field baru `is_team`. Parent category dengan `is_team: false` tidak bisa dipilih sebagai team di purchase order dan cash advance, dan tidak ikut laporan profit sharing. +2. **Endpoint laporan pindah path.** `/api/v1/analytics/parent-categories` menjadi `/api/v1/analytics/profit-sharing`. +3. **Pembagian revenue tinggal dua porsi.** Porsi purchase (60%) dihapus. Revenue sekarang dibagi ke owner (SDL) dan team, dengan porsi team = 100% − fee owner. + +Nomor 2 dan 3 adalah breaking change. Setelah backend baru dirilis, client yang masih memanggil path lama mendapat 404, dan `limit_purchase` serta `percentages.purchase` tidak ada lagi di response. Karena itu client harus diupdate lebih dulu, lihat [Urutan rilis](#database-dan-urutan-rilis). + +Yang perlu bertindak, di dashboard maupun app mobile, mana pun yang punya layarnya: + +- **Form kategori**: tambah toggle team untuk parent category. +- **Laporan profit sharing**: ganti path, hapus porsi purchase, tampilkan dua porsi. +- **Form purchase order dan cash advance**: picker team tidak perlu diubah, tapi form edit perlu menyesuaikan, lihat [Purchase order dan cash advance](#purchase-order-dan-cash-advance). + +## Kategori: field `is_team` + +### Response + +Semua response kategori membawa `is_team` (boolean, tidak pernah `null`): `POST /api/v1/categories`, `PUT /api/v1/categories/:id`, `GET /api/v1/categories`, dan `GET /api/v1/categories/:id`. + +```json +{ + "id": "", + "name": "Merchandise", + "parent_id": null, + "owner_fee_percent": null, + "is_team": false +} +``` + +### Request + +`POST /api/v1/categories` dan `PUT /api/v1/categories/:id` menerima `is_team`. + +```json +{ + "name": "Merchandise", + "is_team": false +} +``` + +| Request | `is_team` yang dikirim | Hasil | +| --- | --- | --- | +| Create | tidak dikirim | `true` | +| Create | `false` | `false` | +| Update | tidak dikirim atau `null` | tidak berubah | +| Update | `true` atau `false` | diganti | + +Update yang hanya berisi `is_team` diterima. + +Aturan nilainya: + +- `is_team` hanya berpengaruh di parent category, yaitu kategori dengan `parent_id: null`. Di sub-category nilainya disimpan tapi tidak dipakai, jadi tampilkan toggle hanya untuk parent category. +- Semua kategori yang sudah ada sebelum rilis bernilai `true`. Tidak ada yang berubah sampai admin mematikannya. +- Flag dibaca saat request, bukan saat transaksi. Kalau parent category dimatikan, penjualannya di periode lampau juga hilang dari laporan profit sharing. Kalau dinyalakan lagi, semuanya muncul kembali. + +### Efek `is_team: false` + +| Endpoint | Efek | +| --- | --- | +| `GET /api/v1/purchase-orders/teams`, `GET /api/v1/cash-advances/teams` | Kategori tidak muncul. Pusat tetap ada. | +| Create dan update purchase order dan cash advance | `team_scope: "category"` dengan `team_category_id` kategori ini ditolak. | +| `GET /api/v1/analytics/profit-sharing` | Kategori tidak muncul di `data`, dan revenue-nya tidak dihitung di `budget`. | +| `GET /api/v1/analytics/profit-sharing/:parent_category_id` | Ditolak. | + +Data yang sudah ada tidak diubah. Purchase order dan cash advance yang sudah tercatat ke kategori itu tetap menyimpan team-nya. Laporan purchasing (`GET /api/v1/analytics/purchasing`) masih menampilkannya di `team_data`, dan filter `team=` tetap bisa dipakai. + +Laporan lain yang tidak menyaring `is_team`, misalnya `GET /api/v1/analytics/categories`, tetap menampilkan penjualan kategori itu. + +## Purchase order dan cash advance + +Picker team sudah mengambil dari `GET /api/v1/purchase-orders/teams` dan `GET /api/v1/cash-advances/teams`, jadi kategori non-team otomatis tidak muncul tanpa perubahan di client. + +Yang perlu diubah ada di form edit. Purchase order atau cash advance lama bisa tercatat ke kategori yang sekarang sudah non-team. Kalau form edit mengirim ulang `team_scope` dan `team_category_id` yang sama, request ditolak, walaupun user tidak mengubah team-nya. + +1. Kirim `team_scope` dan `team_category_id` hanya kalau user mengganti team. Kalau `team_scope` tidak dikirim, team yang tersimpan tidak berubah. +2. Kalau team yang tersimpan tidak ada di daftar `/teams`, tampilkan namanya dari field `team` di response apa adanya, dan jangan memilihkan team lain secara otomatis. + +Contoh error saat team ditolak, dengan HTTP status 500: + +```json +{ + "success": false, + "data": null, + "errors": [ + { + "code": "900", + "entity": "purchase_order_service", + "cause": "category Merchandise is not a team" + } + ] +} +``` + +Untuk cash advance, `entity` bernilai `cash_advance_service`. Cocokkan dengan teks `is not a team` di `cause` kalau perlu menampilkan pesan khusus. + +## Laporan profit sharing + +### Path baru + +| Lama | Baru | +| --- | --- | +| `GET /api/v1/analytics/parent-categories` | `GET /api/v1/analytics/profit-sharing` | +| `GET /api/v1/analytics/parent-categories/:parent_category_id` | `GET /api/v1/analytics/profit-sharing/:parent_category_id` | + +Query parameter dan role tidak berubah: + +- `date_from` dan `date_to` wajib, dengan format `DD-MM-YYYY`, misalnya `28-09-2026`. +- `outlet_id` opsional. +- Hanya bisa diakses superadmin, admin, manager, owner, dan purchasing. + +Path lama sudah tidak ada dan mengembalikan 404. + +### Pembagian revenue + +Revenue tiap parent category yang team dibagi dua: + +- **SDL (fee owner)** = revenue × `owner_fee_percent` / 100. Default-nya 20%, dan bisa diganti per parent category lewat `owner_fee_percent` di kategori. +- **Team** = revenue − SDL. + +Contoh dengan tiga parent category dalam satu minggu: + +| Parent category | `is_team` | Fee owner | Revenue | SDL | Team | +| --- | --- | --- | --- | --- | --- | +| Food | `true` | 20% (default) | 1.000.000 | 200.000 | 800.000 | +| Drink | `true` | 35% | 2.000.000 | 700.000 | 1.300.000 | +| Merchandise | `false` | - | 500.000 | tidak dihitung | tidak dihitung | +| **Budget minggu ini** | | | **3.000.000** | **900.000** | **2.100.000** | + +### Perubahan field + +| Field | Sebelum | Sesudah | +| --- | --- | --- | +| `data[]` | semua parent category | hanya parent category team | +| `budget.percentages.purchase` | `60` | dihapus | +| `budget.percentages.owner` | `20`, atau fee parent itu di endpoint detail | tidak berubah | +| `budget.percentages.team` | `20` | `100 − owner`: `80` di list, `100 − fee parent` di detail | +| `limit_purchase` di `budget.total`, `budget.weekly[]`, `budget.monthly[]` | 60% revenue | dihapus | +| `limit_team` di tempat yang sama | 20% revenue | `revenue − sdl` | +| `revenue` dan `sdl` di `budget` | semua parent category | hanya parent category team | + +Di endpoint list, `budget.percentages` selalu berisi default `20` dan `80`, walaupun ada parent dengan fee berbeda. Angka `sdl` dan `limit_team` dihitung per parent dengan fee masing-masing, jadi `limit_team / revenue` bisa tidak persis 80%. Tampilkan angka rupiah dari response, jangan dihitung ulang dari persentase. + +Baris di `data[]` membawa `sdl` tapi tidak membawa porsi team. Kalau porsi team per parent perlu ditampilkan, hitung dari `total_revenue − sdl`. + +Contoh response list, dipotong: + +```json +{ + "success": true, + "data": { + "date_from": "2026-09-28T00:00:00+07:00", + "date_to": "2026-10-04T23:59:59.999999999+07:00", + "data": [ + { + "parent_category_id": "", + "parent_category_name": "Drink", + "owner_fee_percent": 35, + "sdl": 700000, + "total_revenue": 2000000 + }, + { + "parent_category_id": "", + "parent_category_name": "Food", + "owner_fee_percent": 20, + "sdl": 200000, + "total_revenue": 1000000 + } + ], + "budget": { + "percentages": { "owner": 20, "team": 80 }, + "cut_off_from": "2026-09-28T00:00:00+07:00", + "cut_off_to": "2026-10-04T23:59:59.999999999+07:00", + "total": { + "period_start": "2026-09-28T00:00:00+07:00", + "period_end": "2026-10-04T23:59:59.999999999+07:00", + "revenue": 3000000, + "order_count": 4, + "sdl": 900000, + "limit_team": 2100000 + }, + "weekly": [ + { + "period_start": "2026-09-28T00:00:00+07:00", + "period_end": "2026-10-04T23:59:59.999999999+07:00", + "revenue": 3000000, + "order_count": 4, + "sdl": 900000, + "limit_team": 2100000 + } + ], + "monthly": [ + { + "month": "2026-09", + "week_count": 1, + "period_start": "2026-09-28T00:00:00+07:00", + "period_end": "2026-10-04T23:59:59.999999999+07:00", + "revenue": 3000000, + "order_count": 4, + "sdl": 900000, + "limit_team": 2100000 + } + ] + } + }, + "errors": null +} +``` + +Di endpoint detail, `budget` bentuknya sama, tapi `percentages` memakai fee parent itu, misalnya `{ "owner": 35, "team": 65 }` untuk Drink. + +### Detail kategori non-team + +Detail untuk parent category non-team ditolak dengan HTTP status 500: + +```json +{ + "success": false, + "data": null, + "errors": [ + { + "code": "internal_error", + "entity": "AnalyticsHandler::GetParentCategoryAnalyticsDetail", + "cause": "failed to get parent category analytics detail: failed to get parent category analytics detail: category Merchandise is not a team" + } + ] +} +``` + +Ini bisa terjadi kalau user membuka link lama atau bookmark ke parent yang baru dimatikan. Cocokkan dengan teks `is not a team` di `cause`, lalu arahkan user kembali ke list. + +## Migrasi client + +### Laporan profit sharing + +1. Ganti path ke `/api/v1/analytics/profit-sharing`. Selama backend lama masih jalan, path baru mengembalikan 404. Kalau dapat 404, panggil path lama `/api/v1/analytics/parent-categories`, supaya client baru bisa dirilis sebelum backend. +2. Hapus tampilan limit purchase dan persentase purchase. Jangan menganggap `limit_purchase` atau `percentages.purchase` selalu ada. +3. Tampilkan dua porsi dengan label "SDL / Fee owner" dan "Team", ambil angkanya dari `sdl` dan `limit_team`. +4. Kalau detail ditolak dengan `is not a team`, arahkan kembali ke list. + +Selama fallback ke backend lama, `limit_team` masih berisi 20% revenue. Angkanya baru jadi `revenue − sdl` setelah backend baru dirilis. + +### Form kategori + +1. Tambah toggle `is_team` untuk parent category, misalnya berlabel "Ikut profit sharing (team)". Untuk kategori baru, toggle menyala secara default. +2. Saat membuka form edit, isi toggle dari `is_team`. Selama backend lama masih jalan, field ini tidak ada di response, jadi anggap `true`. +3. Saat admin mematikan toggle, tampilkan konfirmasi bahwa kategori itu tidak akan muncul di pilihan team dan di laporan profit sharing, termasuk untuk periode lampau. +4. Di daftar kategori, beri penanda untuk parent category dengan `is_team: false`. + +Backend lama mengabaikan `is_team` di request, jadi toggle bisa dirilis lebih dulu, tapi belum berpengaruh sampai backend baru jalan. Pengecualiannya update yang hanya berisi `is_team`: backend lama menolaknya dengan error code `303` dan pesan `at least one field must be provided for update`. Selama masa transisi, kirim `is_team` bersama field form lainnya. + +## Database dan urutan rilis + +Migration `000101_add_is_team_to_categories` menambah kolom `categories.is_team` (`BOOLEAN NOT NULL DEFAULT TRUE`). Semua kategori yang ada otomatis bernilai `true`. Migration ini hanya menambah kolom, jadi backend lama tetap jalan normal setelahnya. + +Urutan rilis: + +1. Rilis client baru: path profit sharing dengan fallback ke path lama, tanpa porsi purchase, dan dengan toggle `is_team`. Untuk app mobile, pastikan versi baru sudah dipakai sebagian besar user sebelum langkah 3, karena versi lama yang memanggil `/parent-categories` mendapat 404 setelah itu. +2. Jalankan migration `000101`. +3. Deploy backend baru. +4. Hapus fallback path lama di client. +5. Admin mematikan `is_team` di parent category yang bukan team. + +Rollback: deploy backend lama, lalu jalankan down migration yang menghapus kolom `is_team`. Client dengan fallback tetap jalan di backend lama. Nilai `is_team` yang sudah diatur admin hilang saat kolom dihapus. + +## Checklist + +- [ ] Client baru (fallback path, tanpa porsi purchase, toggle `is_team`) dirilis +- [ ] Migration `000101` dan backend baru dirilis di staging +- [ ] Uji: parent category yang dimatikan hilang dari `/purchase-orders/teams` dan `/cash-advances/teams` +- [ ] Uji: purchase order dan cash advance baru dengan kategori itu ditolak, dan edit purchase order lama tanpa mengganti team tetap berhasil +- [ ] Uji: kategori itu hilang dari `/analytics/profit-sharing`, dan detailnya ditolak +- [ ] Uji: `limit_team = revenue − sdl`, dan `sdl` mengikuti fee masing-masing parent +- [ ] Migration `000101` dan backend baru dirilis di production +- [ ] Fallback path lama di client dihapus + +## FAQ + +**Kenapa porsi team jadi 100% − fee owner, bukan tetap 20%?** Porsi purchase sudah tidak ada, jadi seluruh revenue dibagi dua. Owner mengambil fee-nya, dan sisanya untuk team. Kalau fee owner sebuah parent dinaikkan, porsi team parent itu turun sebesar yang sama. + +**Apakah sub-category bisa dijadikan non-team sendiri?** Tidak. Team dan profit sharing dihitung per parent category, jadi semua sub-category ikut status parent-nya. + +**Bagaimana dengan kategori top-level yang tidak punya sub-category?** Kategori itu tetap parent category, jadi `is_team` berlaku untuknya. diff --git a/internal/constants/budget.go b/internal/constants/budget.go index ac62e5a..06f625a 100644 --- a/internal/constants/budget.go +++ b/internal/constants/budget.go @@ -1,10 +1,6 @@ package constants -// Budget allocation of revenue used by the parent category cut-off report. -// The three shares are expected to add up to 100. BudgetLimitOwnerPercent is only the -// default: a parent category can override it with categories.owner_fee_percent. -const ( - BudgetLimitPurchasePercent = 60.0 - BudgetLimitOwnerPercent = 20.0 - BudgetLimitTeamPercent = 20.0 -) +// Revenue split used by the profit sharing report: the owner takes its fee as SDL and +// the team takes the rest. BudgetLimitOwnerPercent is only the default: a parent +// category can override it with categories.owner_fee_percent. +const BudgetLimitOwnerPercent = 20.0 diff --git a/internal/contract/analytics_contract.go b/internal/contract/analytics_contract.go index d5dccfe..2b4e3e5 100644 --- a/internal/contract/analytics_contract.go +++ b/internal/contract/analytics_contract.go @@ -372,19 +372,17 @@ type BudgetCutOff struct { } type BudgetPercentages struct { - Purchase float64 `json:"purchase"` - Owner float64 `json:"owner"` - Team float64 `json:"team"` + Owner float64 `json:"owner"` + Team float64 `json:"team"` } type BudgetPeriod struct { - PeriodStart time.Time `json:"period_start"` - PeriodEnd time.Time `json:"period_end"` - Revenue float64 `json:"revenue"` - OrderCount int64 `json:"order_count"` - LimitPurchase float64 `json:"limit_purchase"` - SDL float64 `json:"sdl"` - LimitTeam float64 `json:"limit_team"` + PeriodStart time.Time `json:"period_start"` + PeriodEnd time.Time `json:"period_end"` + Revenue float64 `json:"revenue"` + OrderCount int64 `json:"order_count"` + SDL float64 `json:"sdl"` + LimitTeam float64 `json:"limit_team"` } type BudgetMonthPeriod struct { diff --git a/internal/contract/category_contract.go b/internal/contract/category_contract.go index 322f3c1..83d1aa1 100644 --- a/internal/contract/category_contract.go +++ b/internal/contract/category_contract.go @@ -16,6 +16,7 @@ type CreateCategoryRequest struct { ParentID *uuid.UUID `json:"parent_id,omitempty"` Order *int `json:"order,omitempty"` OwnerFeePercent *float64 `json:"owner_fee_percent,omitempty"` + IsTeam *bool `json:"is_team,omitempty"` Metadata map[string]interface{} `json:"metadata,omitempty"` } @@ -27,6 +28,7 @@ type UpdateCategoryRequest struct { ParentID *uuid.UUID `json:"parent_id,omitempty"` Order *int `json:"order,omitempty"` OwnerFeePercent *float64 `json:"owner_fee_percent,omitempty"` + IsTeam *bool `json:"is_team,omitempty"` Metadata map[string]interface{} `json:"metadata,omitempty"` // Set when the field is sent as null (or "" for parent_id), which asks for the @@ -99,6 +101,7 @@ type CategoryResponse struct { BusinessType string `json:"business_type"` Order int `json:"order"` OwnerFeePercent *float64 `json:"owner_fee_percent"` + IsTeam bool `json:"is_team"` Metadata map[string]interface{} `json:"metadata"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` diff --git a/internal/entities/category.go b/internal/entities/category.go index ca85c8f..53a2c86 100644 --- a/internal/entities/category.go +++ b/internal/entities/category.go @@ -42,9 +42,13 @@ type Category struct { BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"` Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"` // OwnerFeePercent overrides the owner's share in the parent category budget report; nil uses the default - OwnerFeePercent *float64 `gorm:"type:numeric(5,2)" json:"owner_fee_percent"` - CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` - UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` + OwnerFeePercent *float64 `gorm:"type:numeric(5,2)" json:"owner_fee_percent"` + // IsTeam marks a parent category as a team in the revenue split. It has no gorm + // default on purpose: GORM would turn an explicit false into the default on insert, + // so callers creating a category set it themselves. + IsTeam bool `gorm:"not null" json:"is_team"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` Organization Organization `gorm:"foreignKey:OrganizationID" json:"organization,omitempty"` Products []Product `gorm:"foreignKey:CategoryID" json:"products,omitempty"` diff --git a/internal/mappers/category_mapper.go b/internal/mappers/category_mapper.go index 8130bc2..5b377ce 100644 --- a/internal/mappers/category_mapper.go +++ b/internal/mappers/category_mapper.go @@ -58,6 +58,12 @@ func CreateCategoryRequestToEntity(req *models.CreateCategoryRequest) *entities. metadata["image_url"] = *req.ImageURL } + // A category is a team unless the request says otherwise + isTeam := true + if req.IsTeam != nil { + isTeam = *req.IsTeam + } + return &entities.Category{ OrganizationID: req.OrganizationID, OutletID: req.OutletID, @@ -66,6 +72,7 @@ func CreateCategoryRequestToEntity(req *models.CreateCategoryRequest) *entities. Description: req.Description, Order: req.Order, OwnerFeePercent: req.OwnerFeePercent, + IsTeam: isTeam, BusinessType: "restaurant", Metadata: metadata, } @@ -105,6 +112,7 @@ func CategoryEntityToResponse(entity *entities.Category) *models.CategoryRespons ImageURL: imageURL, Order: entity.Order, OwnerFeePercent: entity.OwnerFeePercent, + IsTeam: entity.IsTeam, IsActive: true, CreatedAt: entity.CreatedAt, UpdatedAt: entity.UpdatedAt, @@ -142,6 +150,10 @@ func UpdateCategoryEntityFromRequest(entity *entities.Category, req *models.Upda entity.OwnerFeePercent = req.OwnerFeePercent } + if req.IsTeam != nil { + entity.IsTeam = *req.IsTeam + } + if req.OutletID != nil { entity.OutletID = req.OutletID } diff --git a/internal/mappers/category_mapper_test.go b/internal/mappers/category_mapper_test.go new file mode 100644 index 0000000..3a096fc --- /dev/null +++ b/internal/mappers/category_mapper_test.go @@ -0,0 +1,34 @@ +package mappers + +import ( + "testing" + + "apskel-pos-be/internal/models" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" +) + +func TestCreateCategoryRequestToEntityDefaultsToTeam(t *testing.T) { + notTeam := false + + tests := []struct { + name string + isTeam *bool + want bool + }{ + {name: "omitted is a team", isTeam: nil, want: true}, + {name: "false is not a team", isTeam: ¬Team, want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + entity := CreateCategoryRequestToEntity(&models.CreateCategoryRequest{ + OrganizationID: uuid.New(), + Name: "Merchandise", + IsTeam: tt.isTeam, + }) + require.Equal(t, tt.want, entity.IsTeam) + }) + } +} diff --git a/internal/middleware/auth_middleware.go b/internal/middleware/auth_middleware.go index 9bfc7a8..a1fa52b 100644 --- a/internal/middleware/auth_middleware.go +++ b/internal/middleware/auth_middleware.go @@ -82,7 +82,7 @@ func (m *AuthMiddleware) RequireRole(allowedRoles ...string) gin.HandlerFunc { } func (m *AuthMiddleware) RequireAdminOrManager() gin.HandlerFunc { - return m.RequireRole("superadmin", "admin", "manager", "owner", "purchasing") + return m.RequireRole("superadmin", "admin", "manager", "owner", "purchasing") } // RequireLoyaltyManager guards what moves or prices EnakPoint and EnakCoin: loyalty diff --git a/internal/models/analytics.go b/internal/models/analytics.go index 0e23750..ca11f70 100644 --- a/internal/models/analytics.go +++ b/internal/models/analytics.go @@ -412,19 +412,17 @@ type BudgetCutOff struct { } type BudgetPercentages struct { - Purchase float64 `json:"purchase"` - Owner float64 `json:"owner"` - Team float64 `json:"team"` + Owner float64 `json:"owner"` + Team float64 `json:"team"` } type BudgetPeriod struct { - PeriodStart time.Time `json:"period_start"` - PeriodEnd time.Time `json:"period_end"` - Revenue float64 `json:"revenue"` - OrderCount int64 `json:"order_count"` - LimitPurchase float64 `json:"limit_purchase"` - SDL float64 `json:"sdl"` - LimitTeam float64 `json:"limit_team"` + PeriodStart time.Time `json:"period_start"` + PeriodEnd time.Time `json:"period_end"` + Revenue float64 `json:"revenue"` + OrderCount int64 `json:"order_count"` + SDL float64 `json:"sdl"` + LimitTeam float64 `json:"limit_team"` } type BudgetMonthPeriod struct { diff --git a/internal/models/category.go b/internal/models/category.go index 7953863..7b47b45 100644 --- a/internal/models/category.go +++ b/internal/models/category.go @@ -28,6 +28,8 @@ type CreateCategoryRequest struct { ImageURL *string `validate:"omitempty,url"` Order int `validate:"min=0"` OwnerFeePercent *float64 `validate:"omitempty,min=0,max=100"` + // IsTeam defaults to true when left out + IsTeam *bool } type UpdateCategoryRequest struct { @@ -38,6 +40,7 @@ type UpdateCategoryRequest struct { ParentID *uuid.UUID Order *int `validate:"omitempty,min=0"` OwnerFeePercent *float64 `validate:"omitempty,min=0,max=100"` + IsTeam *bool IsActive *bool // Clear flags remove the value; a nil pointer above only means "leave unchanged" @@ -56,6 +59,7 @@ type CategoryResponse struct { ImageURL *string Order int OwnerFeePercent *float64 + IsTeam bool IsActive bool CreatedAt time.Time UpdatedAt time.Time diff --git a/internal/processor/analytics_processor.go b/internal/processor/analytics_processor.go index 80d8bdd..804747f 100644 --- a/internal/processor/analytics_processor.go +++ b/internal/processor/analytics_processor.go @@ -545,6 +545,7 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co // The block covers a single parent category, so it reports that category's own fee if detail.Summary != nil { budget.Percentages.Owner = detail.Summary.OwnerFeePercent + budget.Percentages.Team = 100 - detail.Summary.OwnerFeePercent } return &models.ParentCategoryAnalyticsDetailResponse{ @@ -597,17 +598,17 @@ func endOfWeek(t time.Time) time.Time { return startOfWeek(t).AddDate(0, 0, 7).Add(-time.Nanosecond) } -// newBudgetPeriod splits a period's revenue into the spending limits. The owner limit -// is passed in because a parent category can carry its own owner fee percent. +// newBudgetPeriod splits a period's revenue between the owner and the team. The owner +// share is passed in because a parent category can carry its own owner fee percent, +// and the team takes whatever the owner does not. func newBudgetPeriod(start, end time.Time, revenue, sdl float64, orderCount int64) models.BudgetPeriod { return models.BudgetPeriod{ - PeriodStart: start, - PeriodEnd: end, - Revenue: revenue, - OrderCount: orderCount, - LimitPurchase: revenue * constants.BudgetLimitPurchasePercent / 100, - SDL: sdl, - LimitTeam: revenue * constants.BudgetLimitTeamPercent / 100, + PeriodStart: start, + PeriodEnd: end, + Revenue: revenue, + OrderCount: orderCount, + SDL: sdl, + LimitTeam: revenue - sdl, } } @@ -621,9 +622,8 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza budget := models.BudgetCutOff{ Percentages: models.BudgetPercentages{ - Purchase: constants.BudgetLimitPurchasePercent, - Owner: constants.BudgetLimitOwnerPercent, - Team: constants.BudgetLimitTeamPercent, + Owner: constants.BudgetLimitOwnerPercent, + Team: 100 - constants.BudgetLimitOwnerPercent, }, CutOffFrom: cutOffFrom, CutOffTo: cutOffTo, diff --git a/internal/processor/analytics_processor_test.go b/internal/processor/analytics_processor_test.go index fe84ea4..aef6306 100644 --- a/internal/processor/analytics_processor_test.go +++ b/internal/processor/analytics_processor_test.go @@ -607,7 +607,7 @@ func TestPaymentMethodAnalytics_EnakPointIsNotCashIn(t *testing.T) { } // A parent category with its own owner fee percent moves the owner limit away from the -// default share, while purchase and team stay on the default split of revenue. +// default share, and the team limit shrinks by the same amount. func TestAnalyticsProcessorParentCategoryUsesOwnerFeePercent(t *testing.T) { monday := time.Date(2026, 9, 28, 0, 0, 0, 0, time.UTC) processor := NewAnalyticsProcessorImpl(&analyticsRepositoryStub{ @@ -636,8 +636,9 @@ func TestAnalyticsProcessorParentCategoryUsesOwnerFeePercent(t *testing.T) { require.Len(t, result.Budget.Weekly, 1) require.Equal(t, float64(900), result.Budget.Weekly[0].SDL) - require.Equal(t, float64(1800), result.Budget.Weekly[0].LimitPurchase) - require.Equal(t, float64(600), result.Budget.Weekly[0].LimitTeam) + require.Equal(t, float64(2100), result.Budget.Weekly[0].LimitTeam) + require.Equal(t, float64(20), result.Budget.Percentages.Owner) + require.Equal(t, float64(80), result.Budget.Percentages.Team) require.Len(t, result.Budget.Monthly, 1) require.Equal(t, float64(900), result.Budget.Monthly[0].SDL) require.Equal(t, float64(900), result.Budget.Total.SDL) diff --git a/internal/processor/budget_cutoff_test.go b/internal/processor/budget_cutoff_test.go index 3feafa6..70033fd 100644 --- a/internal/processor/budget_cutoff_test.go +++ b/internal/processor/budget_cutoff_test.go @@ -93,18 +93,17 @@ func TestBuildBudgetCutOffAppliesLimits(t *testing.T) { require.NoError(t, err) require.Len(t, budget.Weekly, 1) - // 60 / 20 of the week's revenue; the owner limit is whatever the repository - // summed from each parent category's own fee percent + // The owner limit is whatever the repository summed from each parent category's + // own fee percent, and the team takes the rest of the week's revenue week := budget.Weekly[0] - require.Equal(t, float64(6_000_000), week.LimitPurchase) require.Equal(t, float64(2_500_000), week.SDL) - require.Equal(t, float64(2_000_000), week.LimitTeam) + require.Equal(t, float64(7_500_000), week.LimitTeam) require.Equal(t, int64(120), week.OrderCount) // Totals mirror the single week require.Equal(t, week.Revenue, budget.Total.Revenue) - require.Equal(t, week.LimitPurchase, budget.Total.LimitPurchase) require.Equal(t, week.SDL, budget.Total.SDL) + require.Equal(t, week.LimitTeam, budget.Total.LimitTeam) } func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) { @@ -112,8 +111,8 @@ func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) { first := time.Date(2026, 8, 3, 0, 0, 0, 0, loc) stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{ - {WeekStart: first, Revenue: 10_000_000, OrderCount: 100}, - {WeekStart: first.AddDate(0, 0, 7), Revenue: 5_000_000, OrderCount: 60}, + {WeekStart: first, Revenue: 10_000_000, OrderCount: 100, SDL: 2_000_000}, + {WeekStart: first.AddDate(0, 0, 7), Revenue: 5_000_000, OrderCount: 60, SDL: 1_000_000}, }} processor := &AnalyticsProcessorImpl{analyticsRepo: stub} @@ -127,9 +126,10 @@ func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) { require.Equal(t, float64(15_000_000), month.Revenue) require.Equal(t, int64(160), month.OrderCount) - // The month limit is the accumulation of its weeks - require.Equal(t, float64(9_000_000), month.LimitPurchase) - require.Equal(t, budget.Weekly[0].LimitPurchase+budget.Weekly[1].LimitPurchase, month.LimitPurchase) + // The month limits are the accumulation of its weeks + require.Equal(t, float64(3_000_000), month.SDL) + require.Equal(t, float64(12_000_000), month.LimitTeam) + require.Equal(t, budget.Weekly[0].LimitTeam+budget.Weekly[1].LimitTeam, month.LimitTeam) } func TestBuildBudgetCutOffEmitsWeeksWithoutSales(t *testing.T) { @@ -147,7 +147,7 @@ func TestBuildBudgetCutOffEmitsWeeksWithoutSales(t *testing.T) { require.Len(t, budget.Weekly, 3) require.Zero(t, budget.Weekly[0].Revenue) - require.Zero(t, budget.Weekly[0].LimitPurchase) + require.Zero(t, budget.Weekly[0].LimitTeam) require.Zero(t, budget.Weekly[1].Revenue) require.Equal(t, float64(4_000_000), budget.Weekly[2].Revenue) require.Equal(t, float64(4_000_000), budget.Total.Revenue) diff --git a/internal/processor/team.go b/internal/processor/team.go index a38a533..04f7ee3 100644 --- a/internal/processor/team.go +++ b/internal/processor/team.go @@ -11,12 +11,13 @@ import ( "github.com/google/uuid" ) -// Teams are the parent product categories, plus Pusat for spending that belongs to -// no single team. Both purchase orders and cash advances are charged to one, so the rules -// for picking and storing a team live here rather than in either processor. +// Teams are the parent product categories flagged is_team, plus Pusat for spending +// that belongs to no single team. Both purchase orders and cash advances are charged to +// one, so the rules for picking and storing a team live here rather than in either +// processor. -// listTeams returns the teams money can be charged to: the parent categories of the -// outlet in scope, followed by Pusat. Pusat has no category row, so it is appended +// listTeams returns the teams money can be charged to: the team parent categories of +// the outlet in scope, followed by Pusat. Pusat has no category row, so it is appended // here rather than read from the database. func listTeams(ctx context.Context, categoryRepo CategoryRepository, organizationID uuid.UUID, outletID *uuid.UUID) (*models.ListPurchaseTeamsResponse, error) { categories, err := categoryRepo.ListParentCategories(ctx, organizationID, outletID) @@ -26,6 +27,9 @@ func listTeams(ctx context.Context, categoryRepo CategoryRepository, organizatio teams := make([]models.PurchaseTeam, 0, len(categories)+1) for _, category := range categories { + if !category.IsTeam { + continue + } categoryID := category.ID teams = append(teams, models.PurchaseTeam{ Scope: constants.PurchaseTeamScopeCategory, @@ -75,6 +79,9 @@ func resolveTeamSelection(ctx context.Context, categoryRepo CategoryRepository, if category.ParentID != nil { return nil, nil, fmt.Errorf("team must be a parent category") } + if !category.IsTeam { + return nil, nil, fmt.Errorf("category %s is not a team", category.Name) + } // Categories without an outlet are shared, so only an outlet-specific // category has to match the outlet the record is booked against. if category.OutletID != nil && outletID != nil && *category.OutletID != *outletID { diff --git a/internal/processor/team_test.go b/internal/processor/team_test.go new file mode 100644 index 0000000..c8781e1 --- /dev/null +++ b/internal/processor/team_test.go @@ -0,0 +1,64 @@ +package processor + +import ( + "context" + "errors" + "testing" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" +) + +// teamCategoryRepositoryStub serves the two lookups the team rules make. The embedded +// interface is left nil, so any other call panics and shows up in the test. +type teamCategoryRepositoryStub struct { + CategoryRepository + categories []*entities.Category +} + +func (s *teamCategoryRepositoryStub) ListParentCategories(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID) ([]*entities.Category, error) { + return s.categories, nil +} + +func (s *teamCategoryRepositoryStub) GetByID(ctx context.Context, id uuid.UUID) (*entities.Category, error) { + for _, category := range s.categories { + if category.ID == id { + return category, nil + } + } + return nil, errors.New("record not found") +} + +func TestListTeamsSkipsParentCategoriesThatAreNotTeams(t *testing.T) { + organizationID := uuid.New() + food := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Food", IsTeam: true} + merch := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Merchandise", IsTeam: false} + repo := &teamCategoryRepositoryStub{categories: []*entities.Category{food, merch}} + + result, err := listTeams(context.Background(), repo, organizationID, nil) + require.NoError(t, err) + + require.Len(t, result.Teams, 2) + require.Equal(t, "Food", result.Teams[0].Name) + require.Equal(t, &food.ID, result.Teams[0].CategoryID) + require.Equal(t, constants.PurchaseTeamCentralName, result.Teams[1].Name) +} + +func TestResolveTeamSelectionRejectsParentCategoryThatIsNotATeam(t *testing.T) { + organizationID := uuid.New() + food := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Food", IsTeam: true} + merch := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Merchandise", IsTeam: false} + repo := &teamCategoryRepositoryStub{categories: []*entities.Category{food, merch}} + scope := constants.PurchaseTeamScopeCategory + + resolvedScope, resolvedID, err := resolveTeamSelection(context.Background(), repo, organizationID, nil, &scope, &food.ID) + require.NoError(t, err) + require.Equal(t, constants.PurchaseTeamScopeCategory, *resolvedScope) + require.Equal(t, food.ID, *resolvedID) + + _, _, err = resolveTeamSelection(context.Background(), repo, organizationID, nil, &scope, &merch.ID) + require.EqualError(t, err, "category Merchandise is not a team") +} diff --git a/internal/repository/analytics_repository.go b/internal/repository/analytics_repository.go index 7082b17..b788f9e 100644 --- a/internal/repository/analytics_repository.go +++ b/internal/repository/analytics_repository.go @@ -614,6 +614,8 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte Joins("JOIN categories c ON p.category_id = c.id"). // Categories without a parent roll up to themselves, so top-level categories still appear Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)"). + // Profit sharing only covers the parent categories that are teams + Where("pc.is_team = ?", true). Joins("JOIN orders o ON oi.order_id = o.id"). Joins("LEFT JOIN (SELECT pr.product_id, SUM(pr.quantity * (1 + COALESCE(pr.waste_percentage, 0)/100.0) * i.cost) as hpp_per_unit FROM product_recipes pr JOIN ingredients i ON pr.ingredient_id = i.id GROUP BY pr.product_id) shpp ON shpp.product_id = p.id"). Joins("LEFT JOIN (?) mahpp ON mahpp.product_id = p.id", @@ -665,6 +667,7 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte Joins("JOIN categories c ON p.category_id = c.id"). Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)"). Joins("JOIN orders o ON oi.order_id = o.id"). + Where("pc.is_team = ?", true). Where("o.organization_id = ?", organizationID). Where("o.is_void = ?", false). Where("o.is_refund = ?", false). @@ -739,11 +742,12 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C var parent struct { ID uuid.UUID Name string + IsTeam bool OwnerFeePercent float64 } if err := r.db.WithContext(ctx). Table("categories"). - Select("id, name, COALESCE(owner_fee_percent, ?) as owner_fee_percent", constants.BudgetLimitOwnerPercent). + Select("id, name, is_team, COALESCE(owner_fee_percent, ?) as owner_fee_percent", constants.BudgetLimitOwnerPercent). Where("id = ? AND organization_id = ?", parentCategoryID, organizationID). Scan(&parent).Error; err != nil { return nil, err @@ -751,6 +755,9 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C if parent.ID == uuid.Nil { return nil, fmt.Errorf("category not found") } + if !parent.IsTeam { + return nil, fmt.Errorf("category %s is not a team", parent.Name) + } detail := &entities.ParentCategoryAnalyticsDetail{ ParentCategoryID: parent.ID, @@ -849,7 +856,8 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C // GetBudgetCutOffWeekly buckets revenue and cost of goods sold into Monday-to-Sunday // weeks. DATE_TRUNC('week') is ISO, so the buckets start on Monday, and the connection // runs with TimeZone=Asia/Jakarta so the boundaries land on local midnight. -// A nil parentCategoryID covers every category in scope. +// A nil parentCategoryID covers every team in scope; parent categories that are not a +// team stay out of the split. func (r *AnalyticsRepositoryImpl) GetBudgetCutOffWeekly(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, parentCategoryID *uuid.UUID, cutOffFrom, cutOffTo time.Time) ([]*entities.BudgetCutOffWeek, error) { var results []*entities.BudgetCutOffWeek @@ -868,6 +876,8 @@ func (r *AnalyticsRepositoryImpl) GetBudgetCutOffWeekly(ctx context.Context, org // The owner fee lives on the parent category; a category without a parent is its own group Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)"). Joins("JOIN orders o ON oi.order_id = o.id"). + // Only teams take part in the revenue split + Where("pc.is_team = ?", true). Where("o.organization_id = ?", organizationID). Where("o.is_void = ?", false). Where("o.is_refund = ?", false). diff --git a/internal/router/router.go b/internal/router/router.go index 55bc014..2022cfd 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -63,7 +63,7 @@ type Router struct { customerDeviceHandler *handler.CustomerDeviceHandler customerOutletHandler *handler.CustomerOutletHandler customerOrderHandler *handler.CustomerOrderHandler - authMiddleware *middleware.AuthMiddleware + authMiddleware *middleware.AuthMiddleware customerAuthMiddleware *middleware.CustomerAuthMiddleware redisClient *redis.Client } @@ -374,8 +374,8 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { analytics.GET("/purchasing", r.analyticsHandler.GetPurchasingAnalytics) analytics.GET("/products", r.analyticsHandler.GetProductAnalytics) analytics.GET("/categories", r.analyticsHandler.GetProductAnalyticsPerCategory) - analytics.GET("/parent-categories", r.analyticsHandler.GetProductAnalyticsPerParentCategory) - analytics.GET("/parent-categories/:parent_category_id", r.analyticsHandler.GetParentCategoryAnalyticsDetail) + analytics.GET("/profit-sharing", r.analyticsHandler.GetProductAnalyticsPerParentCategory) + analytics.GET("/profit-sharing/:parent_category_id", r.analyticsHandler.GetParentCategoryAnalyticsDetail) analytics.GET("/dashboard", r.analyticsHandler.GetDashboardAnalytics) analytics.GET("/profit-loss", r.analyticsHandler.GetProfitLossAnalytics) analytics.GET("/exclusive-summary/period", r.analyticsHandler.GetExclusiveSummaryPeriod) diff --git a/internal/service/report_service.go b/internal/service/report_service.go index 8ba124f..afcfe5c 100644 --- a/internal/service/report_service.go +++ b/internal/service/report_service.go @@ -224,23 +224,23 @@ func getPLPctByID(rows []models.ProfitLossSummaryRow, id string) float64 { // profitLossReportData holds data for the profit/loss PDF template type profitLossReportData struct { - OrganizationName string - MonthName string - ReportDate string - ReportDateUpper string - TotalPenjualan string - TotalBiaya string - LabaRugi string - LabaRugiClass string - LabaRugiValueClass string - LabaRugiMtd string - LabaRugiMtdClass string + OrganizationName string + MonthName string + ReportDate string + ReportDateUpper string + TotalPenjualan string + TotalBiaya string + LabaRugi string + LabaRugiClass string + LabaRugiValueClass string + LabaRugiMtd string + LabaRugiMtdClass string LabaRugiMtdValueClass string - MainSummary []profitLossSummaryRowView - PurchasingItems []profitLossPurchasingItem - PurchasingTotal string - GeneratedBy string - PrintTime string + MainSummary []profitLossSummaryRowView + PurchasingItems []profitLossPurchasingItem + PurchasingTotal string + GeneratedBy string + PrintTime string } type profitLossSummaryRowView struct { diff --git a/internal/transformer/analytics_transformer.go b/internal/transformer/analytics_transformer.go index 0166d2a..79327d0 100644 --- a/internal/transformer/analytics_transformer.go +++ b/internal/transformer/analytics_transformer.go @@ -446,13 +446,12 @@ func parentCategoryTopProductModelToContract(product *models.ParentCategoryTopPr // budgetPeriodModelToContract converts one budget period to contract func budgetPeriodModelToContract(period models.BudgetPeriod) contract.BudgetPeriod { return contract.BudgetPeriod{ - PeriodStart: period.PeriodStart, - PeriodEnd: period.PeriodEnd, - Revenue: period.Revenue, - OrderCount: period.OrderCount, - LimitPurchase: period.LimitPurchase, - SDL: period.SDL, - LimitTeam: period.LimitTeam, + PeriodStart: period.PeriodStart, + PeriodEnd: period.PeriodEnd, + Revenue: period.Revenue, + OrderCount: period.OrderCount, + SDL: period.SDL, + LimitTeam: period.LimitTeam, } } @@ -474,9 +473,8 @@ func BudgetCutOffModelToContract(budget models.BudgetCutOff) contract.BudgetCutO return contract.BudgetCutOff{ Percentages: contract.BudgetPercentages{ - Purchase: budget.Percentages.Purchase, - Owner: budget.Percentages.Owner, - Team: budget.Percentages.Team, + Owner: budget.Percentages.Owner, + Team: budget.Percentages.Team, }, CutOffFrom: budget.CutOffFrom, CutOffTo: budget.CutOffTo, diff --git a/internal/transformer/category_transformer.go b/internal/transformer/category_transformer.go index 1c6abfb..386cf12 100644 --- a/internal/transformer/category_transformer.go +++ b/internal/transformer/category_transformer.go @@ -20,6 +20,7 @@ func CreateCategoryRequestToModel(apctx *appcontext.ContextInfo, req *contract.C ImageURL: nil, Order: order, OwnerFeePercent: req.OwnerFeePercent, + IsTeam: req.IsTeam, } } @@ -32,6 +33,7 @@ func UpdateCategoryRequestToModel(req *contract.UpdateCategoryRequest) *models.U ParentID: req.ParentID, Order: req.Order, OwnerFeePercent: req.OwnerFeePercent, + IsTeam: req.IsTeam, IsActive: nil, ClearParentID: req.ClearParentID, @@ -55,6 +57,7 @@ func CategoryModelResponseToResponse(cat *models.CategoryResponse) *contract.Cat BusinessType: "restaurant", Order: cat.Order, OwnerFeePercent: cat.OwnerFeePercent, + IsTeam: cat.IsTeam, Metadata: map[string]interface{}{}, CreatedAt: cat.CreatedAt, UpdatedAt: cat.UpdatedAt, diff --git a/internal/validator/category_validator.go b/internal/validator/category_validator.go index a390035..8895cd8 100644 --- a/internal/validator/category_validator.go +++ b/internal/validator/category_validator.go @@ -63,7 +63,7 @@ func (v *CategoryValidatorImpl) ValidateUpdateCategoryRequest(req *contract.Upda } // At least one field should be provided for update - if req.Name == nil && req.Description == nil && req.BusinessType == nil && req.ParentID == nil && req.Metadata == nil && req.OwnerFeePercent == nil && req.Order == nil && req.OutletID == nil && !req.ClearParentID && !req.ClearOwnerFeePercent { + if req.Name == nil && req.Description == nil && req.BusinessType == nil && req.ParentID == nil && req.Metadata == nil && req.OwnerFeePercent == nil && req.IsTeam == nil && req.Order == nil && req.OutletID == nil && !req.ClearParentID && !req.ClearOwnerFeePercent { return errors.New("at least one field must be provided for update"), constants.MissingFieldErrorCode } diff --git a/migrations/000101_add_is_team_to_categories.down.sql b/migrations/000101_add_is_team_to_categories.down.sql new file mode 100644 index 0000000..1c85ac5 --- /dev/null +++ b/migrations/000101_add_is_team_to_categories.down.sql @@ -0,0 +1 @@ +ALTER TABLE categories DROP COLUMN is_team; diff --git a/migrations/000101_add_is_team_to_categories.up.sql b/migrations/000101_add_is_team_to_categories.up.sql new file mode 100644 index 0000000..c55290c --- /dev/null +++ b/migrations/000101_add_is_team_to_categories.up.sql @@ -0,0 +1,4 @@ +-- Whether a parent category is a team: it can be charged with purchases and cash +-- advances, and its revenue takes part in the parent category budget split. Every +-- existing category stays a team, since that is how parent categories were treated. +ALTER TABLE categories ADD COLUMN is_team BOOLEAN NOT NULL DEFAULT TRUE; -- 2.54.0