Merge pull request 'Fix/customer register organization' (#39) from fix/customer-register-organization into main

Reviewed-on: #39
This commit was merged in pull request #39.
This commit is contained in:
2026-09-30 18:52:34 +02:00
21 changed files with 1632 additions and 3 deletions
+49 -2
View File
@@ -3,6 +3,7 @@ package processor
import (
"context"
"fmt"
"strings"
"time"
"apskel-pos-be/internal/contract"
@@ -142,6 +143,13 @@ func (p *customerAuthProcessor) StartRegistration(ctx context.Context, req *cont
return nil, fmt.Errorf("phone number already registered")
}
// 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
}
// Generate registration token and create OTP session
registrationToken := uuid.New().String()
@@ -156,6 +164,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 +303,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,
@@ -438,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")
}
}
@@ -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,
}
}
@@ -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)
}
@@ -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
}
@@ -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)
}