chore: 并入 iotlcm-openapi 历史到 openapi/(原提交 3b05d5a)
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package batchimport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
const (
|
||||
batchNoPrefixLength = 3
|
||||
batchNoSequenceLength = 3
|
||||
batchNoSequenceMax = 999
|
||||
batchNoSequenceTTL = 48 * time.Hour
|
||||
batchNoSequenceRedisPrefix = "iotlcm:batch:no:seq:"
|
||||
)
|
||||
|
||||
func NextBatchNo(prefix string) (string, error) {
|
||||
return NextBatchNoContext(context.Background(), prefix)
|
||||
}
|
||||
|
||||
func NextBatchNoContext(ctx context.Context, prefix string) (string, error) {
|
||||
prefix, err := normalizeBatchNoPrefix(prefix)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
now := time.Now()
|
||||
seq, err := nextDailyBatchSequence(ctx, now)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return formatBatchNo(prefix, now, seq)
|
||||
}
|
||||
|
||||
func normalizeBatchNoPrefix(prefix string) (string, error) {
|
||||
prefix = strings.TrimSpace(strings.ToUpper(prefix))
|
||||
if prefix == "" {
|
||||
return "", gerror.New("批次号前缀不能为空")
|
||||
}
|
||||
if len(prefix) != batchNoPrefixLength {
|
||||
return "", gerror.Newf("批次号前缀必须为%d位", batchNoPrefixLength)
|
||||
}
|
||||
return prefix, nil
|
||||
}
|
||||
|
||||
func nextDailyBatchSequence(ctx context.Context, now time.Time) (int64, error) {
|
||||
key := batchNoSequenceKey(now)
|
||||
script := `
|
||||
local v = redis.call("INCR", KEYS[1])
|
||||
if v == 1 then
|
||||
redis.call("EXPIRE", KEYS[1], ARGV[1])
|
||||
end
|
||||
return v`
|
||||
res, err := g.Redis().Do(ctx, "EVAL", script, 1, key, int(batchNoSequenceTTL.Seconds()))
|
||||
if err != nil {
|
||||
return 0, gerror.Wrap(err, "生成批次号序号失败")
|
||||
}
|
||||
seq := res.Int64()
|
||||
if seq <= 0 {
|
||||
return 0, gerror.New("生成批次号序号失败")
|
||||
}
|
||||
if seq > batchNoSequenceMax {
|
||||
return 0, gerror.Newf("当日批次号序号超过%03d", batchNoSequenceMax)
|
||||
}
|
||||
return seq, nil
|
||||
}
|
||||
|
||||
func batchNoSequenceKey(now time.Time) string {
|
||||
return batchNoSequenceRedisPrefix + now.Format("20060102")
|
||||
}
|
||||
|
||||
func formatBatchNo(prefix string, now time.Time, seq int64) (string, error) {
|
||||
if seq <= 0 || seq > batchNoSequenceMax {
|
||||
return "", gerror.Newf("批次号序号必须在1-%03d之间", batchNoSequenceMax)
|
||||
}
|
||||
return fmt.Sprintf("%s%s%0*d", prefix, now.Format("20060102150405"), batchNoSequenceLength, seq), nil
|
||||
}
|
||||
Reference in New Issue
Block a user