delete_chart_logic.go 2.4 KB
package chart

import (
	"context"
	"fmt"
	"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/domain"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/contextdata"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/xerr"

	"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"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteChartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteChartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteChartLogic {
	return &DeleteChartLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteChartLogic) DeleteChart(req *types.ChartDeleteRequest) (resp *types.ChartDeleteResponse, err error) {
	var (
		conn     = l.svcCtx.DefaultDBConn()
		chart    *domain.Chart
		tenantId = contextdata.GetTenantFromCtx(l.ctx)
		appPage  *domain.AppPage
	)
	resp = &types.ChartDeleteResponse{}

	if chart, err = l.svcCtx.ChartRepository.FindOne(l.ctx, conn, req.Id); err != nil {
		return nil, xerr.NewErrMsgErr("不存在", err)
	}
	if chart.TenantId != tenantId {
		return nil, xerr.NewErrMsgErr("无权限", nil)
	}
	// 图表被引用不能删除
	if appPage, err = l.svcCtx.AppPageRepository.FindOneByChartId(l.ctx, conn, tenantId, chart.Id); err != nil {
		return nil, xerr.NewErrMsgErr("删除失败", err)
	}
	if appPage.Identify() != nil {
		return nil, xerr.NewErrMsgErr(fmt.Sprintf("该图表已被页面\"%v\"引用", appPage.Name), err)
	}

	err = transaction.UseTrans(l.ctx, conn.DB(), func(ctx context.Context, conn transaction.Conn) error {
		if chart, err = l.svcCtx.ChartRepository.Delete(l.ctx, conn, chart); err != nil {
			return xerr.NewErrMsgErr("删除失败", err)
		}
		//删除数据源
		chartSetting, err := l.svcCtx.ChartSettingRepository.FindOne(l.ctx, conn, chart.Id)
		if err == nil && len(chartSetting.DataSourceIds) > 0 {
			for _, sourceId := range chartSetting.DataSourceIds {
				err = DeleteObjectTable(l.ctx, l.svcCtx, conn, int(sourceId))
				if err != nil {
					return xerr.NewErrMsg("删除失败")
				}
			}
		}
		return nil
	}, true)

	resp = &types.ChartDeleteResponse{}
	return
}