123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- package label
- import (
- "context"
- "entgo.io/ent/dialect/sql"
- "strings"
- "time"
- "wechat-api/ent"
- "wechat-api/ent/label"
- "wechat-api/internal/svc"
- "wechat-api/internal/types"
- "github.com/zeromicro/go-zero/core/logx"
- )
- type LabelImportLogic struct {
- logx.Logger
- ctx context.Context
- svcCtx *svc.ServiceContext
- }
- func NewLabelImportLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LabelImportLogic {
- return &LabelImportLogic{
- Logger: logx.WithContext(ctx),
- ctx: ctx,
- svcCtx: svcCtx}
- }
- func (l *LabelImportLogic) LabelImport(req *types.LabelImportReq) (resp *types.LabelImportResp, err error) {
- // todo: add your logic here and delete this line
- organizationId := l.ctx.Value("organizationId").(uint64)
- contentString := req.Content
- // contentString := "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34
- //逗号分隔contentString
- contents := strings.Split(contentString, ",")
- //查找已经存在的标签
- uniqueContents := make(map[string]struct{})
- for _, tag := range contents {
- tag = strings.TrimSpace(tag)
- if tag != "" {
- uniqueContents[tag] = struct{}{}
- }
- }
- contentList := make([]string, 0, len(uniqueContents))
- for tag := range uniqueContents {
- contentList = append(contentList, tag)
- }
- existingLabels, err := l.svcCtx.DB.Label.Query().
- Where(
- label.NameIn(contentList...),
- label.OrganizationID(organizationId),
- ).
- Select(label.FieldName).
- All(l.ctx)
- if err != nil {
- return nil, err
- }
- //var toInsert []string
- existMap := make(map[string]bool)
- for _, tag := range existingLabels {
- existMap[tag.Name] = true
- }
- labelCreates := make([]*ent.LabelCreate, 0)
- inserted := make([]string, 0)
- existed := make([]string, 0)
- for _, tag := range contentList {
- if existMap[tag] {
- existed = append(existed, tag)
- continue
- }
- if !existMap[tag] {
- labelCreates = append(labelCreates, l.svcCtx.DB.Label.Create().
- SetName(tag).
- SetType(*req.Type).
- SetStatus(1).
- SetOrganizationID(organizationId).
- SetFrom(2).
- SetMode(1).
- SetConditions(`{}`).
- SetCreatedAt(time.Now()).
- SetUpdatedAt(time.Now()),
- )
- }
- inserted = append(inserted, tag)
- }
- if len(labelCreates) > 0 {
- err := l.svcCtx.DB.Label.CreateBulk(labelCreates...).
- OnConflict(sql.ConflictColumns(label.FieldName, label.FieldOrganizationID)).
- DoNothing().
- Exec(l.ctx)
- if err != nil {
- logx.Error("label 批量插入失败", labelCreates)
- return nil, err
- }
- }
- return &types.LabelImportResp{
- BaseDataInfo: types.BaseDataInfo{
- Code: 0,
- Msg: "success",
- },
- Data: types.LabelImportInfo{
- Inserted: inserted,
- Existed: existed,
- },
- }, nil
- }
|