product_code.go 2.5 KB
package redis

import (
	"fmt"
	"github.com/go-redis/redis"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
	"time"
)

func GenCode(ca CacheCode) (string, error) {
	key := ca.CacheKey()
	client := GetRedis()
	result := client.Get(key)
	index, err := result.Int()
	if err == redis.Nil {
		index = 1
		err = nil
		if ret := client.Set(key, index, ca.Expire()); ret.Err() != nil {
			return "", ret.Err()
		}
		return ca.Format(index), nil
	}
	if err != nil {
		return "", err
	}
	if ret := client.Incr(key); ret.Err() != nil {
		return "", ret.Err()
	} else {
		index = int(ret.Val())
	}
	return ca.Format(index), nil
}

type CacheCode interface {
	CacheKey() string
	Expire() time.Duration
	Format(index int) string
}

type ProductCodeCache struct {
	CompanyId int
	Time      time.Time
}

func (ca ProductCodeCache) CacheKey() string {
	str := fmt.Sprintf("%v:product-code:%v:%v", constant.CACHE_PREFIX, ca.CompanyId, ca.Time.Format("20060102"))
	return str
}
func (ca ProductCodeCache) Format(index int) string {
	if index <= 999 {
		return fmt.Sprintf("CP%v%03d", ca.Time.Format("060102"), index)
	}
	return fmt.Sprintf("CP%v%d", ca.Time.Format("060102"), index)
}
func (ca ProductCodeCache) Expire() time.Duration {
	return time.Hour * 24
}
func NewProductCodeCache(id int) ProductCodeCache {
	return ProductCodeCache{
		CompanyId: id,
		Time:      time.Now(),
	}
}

type PlanBatchCodeCache struct {
	CompanyId int
	Time      time.Time
}

func (ca PlanBatchCodeCache) CacheKey() string {
	str := fmt.Sprintf("%v:plan-batch-code:%v:%v", constant.CACHE_PREFIX, ca.CompanyId, ca.Time.Format("20060102"))
	return str
}
func (ca PlanBatchCodeCache) Format(index int) string {
	if index <= 999 {
		return fmt.Sprintf("%v%03d", ca.Time.Format("20060102"), index)
	}
	return fmt.Sprintf("%v%d", ca.Time.Format("20060102"), index)
}
func (ca PlanBatchCodeCache) Expire() time.Duration {
	return time.Hour * 24
}
func NewPlanBatchCodeCache(id int) PlanBatchCodeCache {
	return PlanBatchCodeCache{
		CompanyId: id,
		Time:      time.Now(),
	}
}

type BillNoCodeCache struct {
	CompanyId int
	BillNo    string
}

func (ca BillNoCodeCache) CacheKey() string {
	str := fmt.Sprintf("%v:bill-no:%v:%v", constant.CACHE_PREFIX, ca.CompanyId, ca.BillNo)
	return str
}
func (ca BillNoCodeCache) Format(index int) string {
	return fmt.Sprintf("%v-%v", ca.BillNo, index)
}
func (ca BillNoCodeCache) Expire() time.Duration {
	return time.Hour * 24 * 5
}
func NewBillNoCodeCache(id int, billNo string) BillNoCodeCache {
	return BillNoCodeCache{
		CompanyId: id,
		BillNo:    billNo,
	}
}