Files
apskel-pos-backend/internal/repository/customer_outlet_repository.go
T

61 lines
1.9 KiB
Go
Raw Normal View History

2026-09-30 19:21:13 +07:00
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
}