byte_table_data_logic.go 2.4 KB
package consumer

import (
	"context"
	"encoding/json"
	"github.com/pkg/errors"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/types"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/db/transaction"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/gateway/bytelib"
)

type ByteTableDataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewByteTableDataLogic(svcCtx *svc.ServiceContext) *ByteTableDataLogic {
	return &ByteTableDataLogic{
		svcCtx: svcCtx,
		ctx:    context.Background(),
	}
}

func (logic *ByteTableDataLogic) Sync(pusherStr string) error {
	pusher := &types.SyncTableDataPusher{}
	err := json.Unmarshal([]byte(pusherStr), pusher)
	if err != nil {
		return err
	}
	conn := logic.svcCtx.DefaultDBConn()
	//验证是否有使用数据源
	used, err := logic.svcCtx.ChartSettingRepository.CheckUseDataSource(logic.ctx, conn, pusher.ObjectId)
	if err != nil || !used {
		return err
	}
	accessToken, _ := types.TableAccessToken{CompanyId: pusher.CompanyId}.GenerateToken()
	tableDataPreview, err := logic.svcCtx.ByteMetadataService.TableDataPreview(logic.ctx, &bytelib.TableDataPreviewRequest{
		Token:      accessToken,
		ObjectId:   int64(pusher.ObjectId),
		ObjectType: bytelib.ObjectMetaTable,
		Where: &bytelib.TableQueryWhere{
			PageNumber: 1,
			PageSize:   bytelib.MaxPageSize,
		},
		UseCache:   true,
		HiddenData: false,
	})
	if err != nil {
		return err
	}
	err = transaction.UseTrans(logic.ctx, conn.DB(), func(ctx context.Context, conn transaction.Conn) error {
		err = logic.svcCtx.ObjectTableDataRepository.InsertWithTableData(logic.ctx, conn, bytelib.TableData(tableDataPreview))
		if err != nil {
			return err
		}
		//更新标记本地存储
		err = logic.updateTableWithLocal(conn, int(tableDataPreview.ObjectId))
		if err != nil {
			return err
		}
		return nil
	}, true)
	return err
}

// updateTableWithLocal 更新表标记本地存储
func (logic *ByteTableDataLogic) updateTableWithLocal(conn transaction.Conn, tableId int) error {
	objectTable, err := logic.svcCtx.ObjectTableRepository.FindOneByTableId(logic.ctx, conn, tableId)
	if err == nil && objectTable.Id > 0 {
		objectTable.IsLocal = true
		_, err = logic.svcCtx.ObjectTableRepository.Update(logic.ctx, conn, objectTable)
		return err
	}
	return errors.New("表不存在")
}