93 lines
2.6 KiB
Go
93 lines
2.6 KiB
Go
package customerverification
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var ErrNotFound = errors.New("verification not found")
|
|
|
|
type Repository interface {
|
|
Upsert(ctx context.Context, v *CustomerVerification) error
|
|
FindByUserID(ctx context.Context, userID uuid.UUID) (*CustomerVerification, error)
|
|
FindByID(ctx context.Context, id uuid.UUID) (*CustomerVerification, error)
|
|
List(ctx context.Context, status string) ([]*CustomerVerification, error)
|
|
UpdateStatus(ctx context.Context, id uuid.UUID, status, adminNote string) (*CustomerVerification, error)
|
|
}
|
|
|
|
type gormRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewRepository(db *gorm.DB) Repository {
|
|
return &gormRepository{db: db}
|
|
}
|
|
|
|
// Upsert inserts a new submission or overwrites the customer's existing one
|
|
// (a resubmission after rejection reuses the same row, reset to pending).
|
|
func (r *gormRepository) Upsert(ctx context.Context, v *CustomerVerification) error {
|
|
existing, err := r.FindByUserID(ctx, v.UserID)
|
|
if errors.Is(err, ErrNotFound) {
|
|
return r.db.WithContext(ctx).Create(v).Error
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
v.ID = existing.ID
|
|
v.CreatedAt = existing.CreatedAt
|
|
return r.db.WithContext(ctx).Save(v).Error
|
|
}
|
|
|
|
func (r *gormRepository) FindByUserID(ctx context.Context, userID uuid.UUID) (*CustomerVerification, error) {
|
|
var v CustomerVerification
|
|
err := r.db.WithContext(ctx).Where("user_id = ?", userID).First(&v).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &v, nil
|
|
}
|
|
|
|
func (r *gormRepository) FindByID(ctx context.Context, id uuid.UUID) (*CustomerVerification, error) {
|
|
var v CustomerVerification
|
|
err := r.db.WithContext(ctx).Where("id = ?", id).First(&v).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &v, nil
|
|
}
|
|
|
|
func (r *gormRepository) List(ctx context.Context, status string) ([]*CustomerVerification, error) {
|
|
q := r.db.WithContext(ctx).Order("created_at asc")
|
|
if status != "" {
|
|
q = q.Where("status = ?", status)
|
|
}
|
|
var list []*CustomerVerification
|
|
if err := q.Find(&list).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return list, nil
|
|
}
|
|
|
|
func (r *gormRepository) UpdateStatus(ctx context.Context, id uuid.UUID, status, adminNote string) (*CustomerVerification, error) {
|
|
res := r.db.WithContext(ctx).Model(&CustomerVerification{}).Where("id = ?", id).Updates(map[string]any{
|
|
"status": status,
|
|
"admin_note": adminNote,
|
|
})
|
|
if res.Error != nil {
|
|
return nil, res.Error
|
|
}
|
|
if res.RowsAffected == 0 {
|
|
return nil, ErrNotFound
|
|
}
|
|
return r.FindByID(ctx, id)
|
|
}
|