ids-svc-product/internal/freight/rules_json.go
robinj0726 eeb3efa996 feat: add region indexing and rules validation for freight templates
- Implemented RegionIndex to manage region codes and their relationships from embedded region.json.
- Added ValidateRulesJSON function to validate freight rules against specified criteria, including region code existence and overlap checks.
- Created unit tests for rules validation covering various scenarios including valid rules, overlap detection, and error handling for invalid inputs.
- Updated freight_template_server to integrate rules validation during freight template creation and updates, ensuring compliance with the new rules structure.
2026-10-10 18:54:45 +08:00

157 lines
4.8 KiB
Go

package freight
import (
"encoding/json"
"fmt"
"math"
"strings"
)
// RulesDocument is the version-1 express freight rules_json contract.
type RulesDocument struct {
Version int `json:"version"`
Delivery string `json:"delivery"`
ChargeType string `json:"charge_type"`
Rules []RuleRow `json:"rules"`
}
// RuleRow is one deliverable-area pricing row.
type RuleRow struct {
RegionCodes []string `json:"region_codes"`
RegionNames []string `json:"region_names"`
RegionPaths []string `json:"region_paths"`
FirstUnit float64 `json:"first_unit"`
FirstFee int64 `json:"first_fee"`
AdditionalUnit float64 `json:"additional_unit"`
AdditionalFee int64 `json:"additional_fee"`
}
// ValidateRulesJSON validates mode=2 rules_json bytes against docs/admin-freight-template.md.
// region_paths is required (new writes). Codes must be strings present in region.json; overlap includes parent/child.
func ValidateRulesJSON(raw []byte) error {
idx, err := DefaultRegionIndex()
if err != nil {
return fmt.Errorf("region index unavailable: %w", err)
}
return ValidateRulesJSONWithIndex(raw, idx)
}
// ValidateRulesJSONWithIndex is the testable core of ValidateRulesJSON.
func ValidateRulesJSONWithIndex(raw []byte, idx *RegionIndex) error {
if len(strings.TrimSpace(string(raw))) == 0 {
return fmt.Errorf("rules_json is required")
}
var doc RulesDocument
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
if err := dec.Decode(&doc); err != nil {
return fmt.Errorf("rules_json invalid: %w", err)
}
if doc.Version != 1 {
return fmt.Errorf("rules_json.version must be 1")
}
if doc.Delivery != "express" {
return fmt.Errorf("rules_json.delivery must be \"express\"")
}
if doc.ChargeType != "piece" && doc.ChargeType != "weight" {
return fmt.Errorf("rules_json.charge_type must be \"piece\" or \"weight\"")
}
if len(doc.Rules) == 0 {
return fmt.Errorf("rules_json.rules must contain at least one rule")
}
occupied := make([]string, 0)
for i, rule := range doc.Rules {
prefix := fmt.Sprintf("rules_json.rules[%d]", i)
if err := validateRuleRow(prefix, doc.ChargeType, rule, idx); err != nil {
return err
}
for _, code := range rule.RegionCodes {
for _, prev := range occupied {
if idx.Overlap(code, prev) {
return fmt.Errorf("%s: region %s overlaps occupied region %s", prefix, code, prev)
}
}
occupied = append(occupied, code)
}
}
return nil
}
func validateRuleRow(prefix, chargeType string, rule RuleRow, idx *RegionIndex) error {
if len(rule.RegionCodes) == 0 {
return fmt.Errorf("%s.region_codes must not be empty", prefix)
}
if len(rule.RegionNames) != len(rule.RegionCodes) {
return fmt.Errorf("%s.region_names length must match region_codes", prefix)
}
if len(rule.RegionPaths) != len(rule.RegionCodes) {
return fmt.Errorf("%s.region_paths length must match region_codes (required for new writes)", prefix)
}
seen := make(map[string]struct{}, len(rule.RegionCodes))
for j, code := range rule.RegionCodes {
code = strings.TrimSpace(code)
if code == "" {
return fmt.Errorf("%s.region_codes[%d] is empty", prefix, j)
}
if _, dup := seen[code]; dup {
return fmt.Errorf("%s.region_codes contains duplicate %s", prefix, code)
}
seen[code] = struct{}{}
if !idx.Known(code) {
return fmt.Errorf("%s.region_codes[%d]=%s is not a known region", prefix, j, code)
}
if strings.TrimSpace(rule.RegionNames[j]) == "" {
return fmt.Errorf("%s.region_names[%d] is empty", prefix, j)
}
if strings.TrimSpace(rule.RegionPaths[j]) == "" {
return fmt.Errorf("%s.region_paths[%d] is empty", prefix, j)
}
}
for a := range seen {
for b := range seen {
if a >= b {
continue
}
if idx.Overlap(a, b) {
return fmt.Errorf("%s: region_codes %s and %s overlap", prefix, a, b)
}
}
}
if rule.FirstFee < 0 || rule.AdditionalFee < 0 {
return fmt.Errorf("%s fees must be >= 0 (fen)", prefix)
}
switch chargeType {
case "piece":
if !isPositiveInt(rule.FirstUnit) || !isPositiveInt(rule.AdditionalUnit) {
return fmt.Errorf("%s first_unit/additional_unit must be positive integers for piece", prefix)
}
case "weight":
if err := validateWeightUnit(prefix+".first_unit", rule.FirstUnit); err != nil {
return err
}
if err := validateWeightUnit(prefix+".additional_unit", rule.AdditionalUnit); err != nil {
return err
}
}
return nil
}
func isPositiveInt(v float64) bool {
if v <= 0 || math.IsNaN(v) || math.IsInf(v, 0) {
return false
}
return v == math.Trunc(v)
}
func validateWeightUnit(field string, v float64) error {
if v <= 0 || math.IsNaN(v) || math.IsInf(v, 0) {
return fmt.Errorf("%s must be > 0", field)
}
scaled := v * 1000
if math.Abs(scaled-math.Round(scaled)) > 1e-6 {
return fmt.Errorf("%s allows at most 3 decimal places", field)
}
return nil
}