quotation bff
This commit is contained in:
@@ -3,10 +3,14 @@ package store
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/billing/fees/storage"
|
||||
"github.com/tech/sendico/billing/fees/storage/model"
|
||||
dmath "github.com/tech/sendico/pkg/decimal"
|
||||
"github.com/tech/sendico/pkg/db/repository"
|
||||
"github.com/tech/sendico/pkg/db/repository/builder"
|
||||
ri "github.com/tech/sendico/pkg/db/repository/index"
|
||||
@@ -53,6 +57,19 @@ func NewPlans(logger mlogger.Logger, db *mongo.Database) (storage.PlansStore, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Recommended index to speed up active-plan lookups (org/global + active + dates).
|
||||
activeIndex := &ri.Definition{
|
||||
Keys: []ri.Key{
|
||||
{Field: m.OrganizationRefField, Sort: ri.Asc},
|
||||
{Field: "active", Sort: ri.Asc},
|
||||
{Field: "effectiveFrom", Sort: ri.Asc},
|
||||
{Field: "effectiveTo", Sort: ri.Asc},
|
||||
},
|
||||
}
|
||||
if err := repo.CreateIndex(activeIndex); err != nil {
|
||||
logger.Warn("failed to ensure fee plan active index", zap.Error(err))
|
||||
}
|
||||
|
||||
return &plansStore{
|
||||
logger: logger.Named("plans"),
|
||||
repo: repo,
|
||||
@@ -60,9 +77,13 @@ func NewPlans(logger mlogger.Logger, db *mongo.Database) (storage.PlansStore, er
|
||||
}
|
||||
|
||||
func (p *plansStore) Create(ctx context.Context, plan *model.FeePlan) error {
|
||||
if plan == nil {
|
||||
return merrors.InvalidArgument("plansStore: nil fee plan")
|
||||
if err := validatePlan(plan); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.ensureNoOverlap(ctx, plan); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := p.repo.Insert(ctx, plan, nil); err != nil {
|
||||
if errors.Is(err, merrors.ErrDataConflict) {
|
||||
return storage.ErrDuplicateFeePlan
|
||||
@@ -77,6 +98,13 @@ func (p *plansStore) Update(ctx context.Context, plan *model.FeePlan) error {
|
||||
if plan == nil || plan.GetID() == nil || plan.GetID().IsZero() {
|
||||
return merrors.InvalidArgument("plansStore: invalid fee plan reference")
|
||||
}
|
||||
if err := validatePlan(plan); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.ensureNoOverlap(ctx, plan); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := p.repo.Update(ctx, plan); err != nil {
|
||||
p.logger.Warn("failed to update fee plan", zap.Error(err))
|
||||
return err
|
||||
@@ -99,13 +127,42 @@ func (p *plansStore) Get(ctx context.Context, planRef primitive.ObjectID) (*mode
|
||||
}
|
||||
|
||||
func (p *plansStore) GetActivePlan(ctx context.Context, orgRef primitive.ObjectID, at time.Time) (*model.FeePlan, error) {
|
||||
// Compatibility shim: prefer org plan, fall back to global; allow zero org to mean global.
|
||||
if orgRef.IsZero() {
|
||||
return p.FindActiveGlobalPlan(ctx, at)
|
||||
}
|
||||
|
||||
plan, err := p.FindActiveOrgPlan(ctx, orgRef, at)
|
||||
if err == nil {
|
||||
return plan, nil
|
||||
}
|
||||
if errors.Is(err, storage.ErrFeePlanNotFound) {
|
||||
return p.FindActiveGlobalPlan(ctx, at)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (p *plansStore) FindActiveOrgPlan(ctx context.Context, orgRef primitive.ObjectID, at time.Time) (*model.FeePlan, error) {
|
||||
if orgRef.IsZero() {
|
||||
return nil, merrors.InvalidArgument("plansStore: zero organization reference")
|
||||
}
|
||||
query := repository.Query().Filter(repository.OrgField(), orgRef)
|
||||
return p.findActivePlan(ctx, query, at)
|
||||
}
|
||||
|
||||
limit := int64(1)
|
||||
query := repository.Query().
|
||||
Filter(repository.OrgField(), orgRef).
|
||||
func (p *plansStore) FindActiveGlobalPlan(ctx context.Context, at time.Time) (*model.FeePlan, error) {
|
||||
globalQuery := repository.Query().Or(
|
||||
repository.Exists(repository.OrgField(), false),
|
||||
repository.Query().Filter(repository.OrgField(), nil),
|
||||
)
|
||||
return p.findActivePlan(ctx, globalQuery, at)
|
||||
}
|
||||
|
||||
var _ storage.PlansStore = (*plansStore)(nil)
|
||||
|
||||
func (p *plansStore) findActivePlan(ctx context.Context, orgQuery builder.Query, at time.Time) (*model.FeePlan, error) {
|
||||
limit := int64(2)
|
||||
query := orgQuery.
|
||||
Filter(repository.Field("active"), true).
|
||||
Comparison(repository.Field("effectiveFrom"), builder.Lte, at).
|
||||
Sort(repository.Field("effectiveFrom"), false).
|
||||
@@ -118,13 +175,13 @@ func (p *plansStore) GetActivePlan(ctx context.Context, orgRef primitive.ObjectI
|
||||
),
|
||||
)
|
||||
|
||||
var plan *model.FeePlan
|
||||
var plans []*model.FeePlan
|
||||
decoder := func(cursor *mongo.Cursor) error {
|
||||
target := &model.FeePlan{}
|
||||
if err := cursor.Decode(target); err != nil {
|
||||
return err
|
||||
}
|
||||
plan = target
|
||||
plans = append(plans, target)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -135,10 +192,127 @@ func (p *plansStore) GetActivePlan(ctx context.Context, orgRef primitive.ObjectI
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if plan == nil {
|
||||
if len(plans) == 0 {
|
||||
return nil, storage.ErrFeePlanNotFound
|
||||
}
|
||||
return plan, nil
|
||||
if len(plans) > 1 {
|
||||
return nil, storage.ErrConflictingFeePlans
|
||||
}
|
||||
return plans[0], nil
|
||||
}
|
||||
|
||||
var _ storage.PlansStore = (*plansStore)(nil)
|
||||
func validatePlan(plan *model.FeePlan) error {
|
||||
if plan == nil {
|
||||
return merrors.InvalidArgument("plansStore: nil fee plan")
|
||||
}
|
||||
if len(plan.Rules) == 0 {
|
||||
return merrors.InvalidArgument("plansStore: fee plan must contain at least one rule")
|
||||
}
|
||||
if plan.Active && plan.EffectiveTo != nil && plan.EffectiveTo.Before(plan.EffectiveFrom) {
|
||||
return merrors.InvalidArgument("plansStore: effectiveTo cannot be before effectiveFrom")
|
||||
}
|
||||
|
||||
// Ensure unique priority per (trigger, appliesTo) combination.
|
||||
seen := make(map[string]struct{})
|
||||
for _, rule := range plan.Rules {
|
||||
if strings.TrimSpace(rule.Percentage) != "" {
|
||||
if _, err := dmath.RatFromString(rule.Percentage); err != nil {
|
||||
return merrors.InvalidArgument("plansStore: invalid rule percentage")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(rule.FixedAmount) != "" {
|
||||
if _, err := dmath.RatFromString(rule.FixedAmount); err != nil {
|
||||
return merrors.InvalidArgument("plansStore: invalid rule fixed amount")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(rule.MinimumAmount) != "" {
|
||||
if _, err := dmath.RatFromString(rule.MinimumAmount); err != nil {
|
||||
return merrors.InvalidArgument("plansStore: invalid rule minimum amount")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(rule.MaximumAmount) != "" {
|
||||
if _, err := dmath.RatFromString(rule.MaximumAmount); err != nil {
|
||||
return merrors.InvalidArgument("plansStore: invalid rule maximum amount")
|
||||
}
|
||||
}
|
||||
|
||||
appliesKey := normalizeAppliesTo(rule.AppliesTo)
|
||||
priorityKey := fmt.Sprintf("%s|%d|%s", rule.Trigger, rule.Priority, appliesKey)
|
||||
if _, ok := seen[priorityKey]; ok {
|
||||
return merrors.InvalidArgument("plansStore: duplicate priority for trigger/appliesTo")
|
||||
}
|
||||
seen[priorityKey] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeAppliesTo(applies map[string]string) string {
|
||||
if len(applies) == 0 {
|
||||
return ""
|
||||
}
|
||||
keys := make([]string, 0, len(applies))
|
||||
for k := range applies {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
parts := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
parts = append(parts, k+"="+applies[k])
|
||||
}
|
||||
return strings.Join(parts, ",")
|
||||
}
|
||||
|
||||
func (p *plansStore) ensureNoOverlap(ctx context.Context, plan *model.FeePlan) error {
|
||||
if plan == nil || !plan.Active {
|
||||
return nil
|
||||
}
|
||||
|
||||
orgQuery := repository.Query()
|
||||
if plan.OrganizationRef.IsZero() {
|
||||
orgQuery = repository.Query().Or(
|
||||
repository.Exists(repository.OrgField(), false),
|
||||
repository.Query().Filter(repository.OrgField(), nil),
|
||||
)
|
||||
} else {
|
||||
orgQuery = repository.Query().Filter(repository.OrgField(), plan.OrganizationRef)
|
||||
}
|
||||
|
||||
maxTime := time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
|
||||
newFrom := plan.EffectiveFrom
|
||||
newTo := maxTime
|
||||
if plan.EffectiveTo != nil {
|
||||
newTo = *plan.EffectiveTo
|
||||
}
|
||||
|
||||
query := orgQuery.
|
||||
Filter(repository.Field("active"), true).
|
||||
Comparison(repository.Field("effectiveFrom"), builder.Lte, newTo).
|
||||
And(repository.Query().Or(
|
||||
repository.Query().Filter(repository.Field("effectiveTo"), nil),
|
||||
repository.Query().Comparison(repository.Field("effectiveTo"), builder.Gte, newFrom),
|
||||
))
|
||||
|
||||
if id := plan.GetID(); id != nil && !id.IsZero() {
|
||||
query = query.And(repository.Query().Comparison(repository.IDField(), builder.Ne, *id))
|
||||
}
|
||||
|
||||
limit := int64(1)
|
||||
query = query.Limit(&limit)
|
||||
|
||||
var overlapFound bool
|
||||
decoder := func(cursor *mongo.Cursor) error {
|
||||
overlapFound = true
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := p.repo.FindManyByFilter(ctx, query, decoder); err != nil {
|
||||
if errors.Is(err, merrors.ErrNoData) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if overlapFound {
|
||||
return storage.ErrConflictingFeePlans
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user