crontab_sync_product.go 1.9 KB
package crontab

import (
	"context"
	"fmt"
	"github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
	"runtime/debug"
	"time"
)

// SyncProduct 定时同步产品
func SyncProduct(ctx context.Context) error {
	defer func() {
		if r := recover(); r != nil {
			log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "定时同步产品", "stack": string(debug.Stack())})
		}
	}()
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return err
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		if err != nil {
			log.Logger.Error("【定时同步产品信息】 失败:" + err.Error())
		}
		transactionContext.RollbackTransaction()
	}()

	log.Logger.Debug("【定时同步同步产品信息】 启动")
	pullK3CloudService := syncdata.PullDataK3CloudService{}
	var fromTime time.Time
	if ctx != nil {
		t := ctx.Value("fromTime")
		if t != nil {
			if v, ok := t.(time.Time); ok {
				fromTime = v
			}
		}
	}
	if fromTime.IsZero() {
		// fromTime, err = redis.GetLastFetchTime(redis.MaterialK3cloudFetchTimeKey())
		fromTime = utils.GetZeroTime(time.Now()).Add(-time.Hour * 24) //前一天有修改的记录
		if err != nil {
			log.Logger.Error(err.Error())
			return nil
		}
	}
	if err := pullK3CloudService.SyncDataProduct(transactionContext.(*pg.TransactionContext), fromTime); err != nil {
		log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时同步产品"})
		return nil
	}
	if err = transactionContext.CommitTransaction(); err != nil {
		return err
	}
	return nil
}