审查视图

pkg/port/beego/controllers/import_controller.go 13.3 KB
庄敏学 authored
1 2 3
package controllers

import (
4 5
	"archive/zip"
	"bufio"
6
	"bytes"
7
	"encoding/json"
8
	"fmt"
9 10 11 12 13
	service "gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/evaluation_template"
	templateCommand "gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/evaluation_template/command"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/import/command"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/xredis"
14
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/utils"
15 16
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
17
	"io"
18
	"io/ioutil"
19 20 21 22
	"mime/multipart"
	"os"
	"path"
	"path/filepath"
tangxvhui authored
23 24
	"strconv"
	"strings"
25
	"time"
tangxvhui authored
26
庄敏学 authored
27
	"github.com/linmadan/egglib-go/core/application"
郑周 authored
28
	"github.com/linmadan/egglib-go/utils/tool_funs"
庄敏学 authored
29 30
	"github.com/linmadan/egglib-go/web/beego"
	"github.com/xuri/excelize/v2"
郑周 authored
31
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
庄敏学 authored
32
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
郑周 authored
33
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/middlewares"
庄敏学 authored
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
)

type ImportController struct {
	beego.BaseController
}

func (controller *ImportController) Import() {
	_, header, err := controller.GetFile("file")
	if err != nil {
		controller.Response(nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传错误:"+err.Error()))
		return
	}
	file, err := header.Open()
	if err != nil {
		controller.Response(nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传错误:"+err.Error()))
		return
	}
	reader, err := excelize.OpenReader(file)
	if err != nil {
		controller.Response(nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传错误:"+err.Error()))
		return
	}
	index := reader.GetActiveSheetIndex()
	rows, err := reader.GetRows(reader.GetSheetName(index))
	if err != nil {
		controller.Response(nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "读取excel错误:"+err.Error()))
		return
	}
庄敏学 authored
62 63 64
	formType := controller.GetString("type")
	switch formType {
	case "PerformanceDimension":
庄敏学 authored
65 66 67 68
		dimensions, err := domain.LoadPerformanceDimensions(rows)
		if err != nil {
			controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
		}
69 70 71 72 73
		if err, list := controller.parseTemplateNodeContent(dimensions); err != nil {
			controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
		} else {
			controller.Response(tool_funs.SimpleWrapGridMap(int64(len(list)), list), nil)
		}
庄敏学 authored
74 75 76
	default:
		controller.Response(nil, application.ThrowError(application.ARG_ERROR, "请确认您导入的表单类型"))
	}
庄敏学 authored
77
}
郑周 authored
78
79
func (controller *ImportController) parseTemplateNodeContent(data []*domain.PerformanceDimension) (error, []*domain.NodeContent) {
郑周 authored
80 81 82 83
	nodeContents := make([]*domain.NodeContent, 0)

	transactionContext, err := factory.StartTransaction()
	if err != nil {
84
		return err, nodeContents
郑周 authored
85 86 87 88 89 90
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	// 获取当前公司下的默认规则
	ua := middlewares.GetUser(controller.Ctx)
91 92

	// 系统默认规则确认
郑周 authored
93 94 95
	ruleRepository := factory.CreateEvaluationRuleRepository(map[string]interface{}{"transactionContext": transactionContext})
	_, rules, err := ruleRepository.Find(map[string]interface{}{"companyId": ua.CompanyId, "sysType": domain.EvaluationSysTypeSystem, "limit": 1})
	if err != nil {
96
		return err, nodeContents
郑周 authored
97 98 99 100 101
	}
	var ruleId = int64(0)
	if len(rules) == 0 {
		newRule := domain.GenerateSysRule(ua.CompanyId) // 生成一个系统默认规则
		if rule, err := ruleRepository.Insert(newRule); err != nil {
102
			return err, nodeContents
郑周 authored
103 104 105 106
		} else {
			ruleId = rule.Id
		}
		if err := transactionContext.CommitTransaction(); err != nil {
107
			return err, nodeContents
郑周 authored
108 109 110 111 112
		}
	} else {
		ruleId = rules[0].Id
	}
113 114 115 116
	// 评估内容主导人名称
	evaluatorNames := make([]string, 0)
	evaluatorMap := map[string]string{}
117
	weightTotal := 0.0
郑周 authored
118 119 120 121 122 123 124 125 126 127 128
	for i := range data {
		dimension := data[i]
		for i2 := range dimension.PerformanceModule {
			nc := &domain.NodeContent{}
			nc.Category = dimension.Name // 类别

			module := dimension.PerformanceModule[i2]
			nc.Name = module.ModuleName                 // 名称
			nc.RuleId = ruleId                          // 规则ID
			sIndex := strings.Index(module.Weight, "%") // 权重
			if sIndex != -1 {
tangxvhui authored
129
				iWeight, _ := strconv.ParseFloat(module.Weight[:sIndex], 64)
郑周 authored
130 131 132 133
				nc.Weight = iWeight
			} else {
				nc.Weight = 0
			}
134
			weightTotal += nc.Weight                     // 总权重
郑周 authored
135 136 137 138 139 140
			nc.PromptTitle = ""                          // 提示项标题
			nc.PromptText = module.Standard              // 提示项内容
			nc.EntryItems = make([]*domain.EntryItem, 0) // 输入项
			for i3 := range module.Target {
				target := module.Target[i3]
				nc.EntryItems = append(nc.EntryItems, &domain.EntryItem{
庄敏学 authored
141 142 143
					Title:      target.Task,       // 输入型标题
					HintText:   "",                // 输入项提示文本
					Definition: target.Definition, //定义
郑周 authored
144 145 146 147 148 149 150 151 152 153
				})
			}
			// 没有任何输入项时,默认1个
			if len(nc.EntryItems) == 0 {
				nc.EntryItems = append(nc.EntryItems, &domain.EntryItem{
					Title:    "填写反馈",
					HintText: "",
				})
			}
154
			// 必填项
155
			nc.Required = module.Required
156 157 158 159 160 161 162 163 164
			// 项目评估人
			if module.Evaluator == "HRBP" {
				nc.EvaluatorId = -1
			} else {
				if len(module.Evaluator) > 0 {
					evaluatorNames = append(evaluatorNames, module.Evaluator) // 项目评估人名称数组
					evaluatorMap[nc.Category+nc.Name] = module.Evaluator      // k,v = (类别+名称, 项目评估人名称)
				}
			}
165 166
			// 指标类型(0指标、1任务)
			nc.IndicatorType = module.IndicatorType
167
郑周 authored
168 169 170 171
			nodeContents = append(nodeContents, nc)
		}
	}
172 173 174 175 176 177
	// 权重总数不等于100%,提示报错
	if weightTotal != 100 {
		sprintf := fmt.Sprintf("当前导入的总权重值为:%s%%(必须等于100%%)", utils.FormatFloatDecimal(weightTotal, 2))
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, sprintf), nodeContents
	}
178 179 180 181
	if len(evaluatorNames) > 0 {
		userRepository := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
		_, users, err := userRepository.Find(map[string]interface{}{"companyId": ua.CompanyId, "names": evaluatorNames})
		if err != nil {
182
			return err, nodeContents
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
		}
		nameIdMap := map[string]int64{}
		for i := range users {
			nameIdMap[users[i].Name] = users[i].Id
		}

		// 名称 -> ID
		var nc *domain.NodeContent
		for i := range nodeContents {
			nc = nodeContents[i]
			if nc.EvaluatorId == -1 { // HRBP
				continue
			}
			if evaluatorName, ok := evaluatorMap[nc.Category+nc.Name]; ok {
				if userId, ok := nameIdMap[evaluatorName]; ok {
					nc.EvaluatorId = userId
				}
			}
		}
	}
204
	return nil, nodeContents
郑周 authored
205
}
206 207 208 209 210 211 212

func (controller *ImportController) ZipVerify() {
	in := &command.VerifyKeyCommand{}
	if err := controller.Unmarshal(in); err != nil {
		controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
	} else {
		bytes, err := xredis.GetBytes(in.VerifyKey)
213
		if err == nil {
214
			out := &command.OutResult{}
215 216
			err = json.Unmarshal(bytes, out)
			if err == nil {
217
				controller.Response(out, nil)
218
				return
219 220
			}
		}
221 222 223 224 225 226 227

		// 有异常直接返回完成标记
		if err != nil {
			out := &command.OutResult{}
			out.Status = "completed"
			controller.Response(out, nil)
		}
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
	}
}

func (controller *ImportController) ZipImport() {
	_, header, err := controller.GetFile("file")
	if err != nil {
		controller.Response(nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传错误:"+err.Error()))
		return
	}
	file, err := header.Open()
	if err != nil {
		controller.Response(nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "文件错误:"+err.Error()))
		return
	}

	// 写入本地
	zipPath, day, id, err := controller.writeLocal(file)
	if err != nil {
		controller.Response(nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error()))
		return
	}

	out := command.OutResult{
		Status:  "uncompleted",
		Success: make([]command.ErrorI, 0),
		Failure: make([]command.ErrorI, 0),
	}
	key := xredis.CreateUploadZipKey(id)
	_ = xredis.Set(key, out, 2*time.Hour)
	controller.Response(map[string]string{"key": key}, nil)
	go func() {
		// 解压目标文件夹
260
		dstDir := constant.UPLOAD_ZIP_PATH + "/" + day + "-" + id
261 262 263
		fileNames, err := controller.Unzip(zipPath, dstDir)
		if err != nil {
			_ = xredis.Remove(key)
264
			_ = os.RemoveAll(dstDir)
265 266 267 268 269 270 271 272 273 274 275 276 277
		} else {
			success := make([]command.ErrorI, 0)
			failure := make([]command.ErrorI, 0)
			for i := range fileNames {
				fn := fileNames[i]
				f, err := os.Open(path.Join(dstDir, fn))
				if err != nil {
					failure = append(failure, command.ErrorI{
						FileName: fn,
						Message:  err.Error(),
					})
					continue
				}
郑周 authored
278
				if err = controller.parserAndInsert(f, fn); err != nil {
279 280 281 282
					failure = append(failure, command.ErrorI{
						FileName: fn,
						Message:  err.Error(),
					})
郑周 authored
283 284 285 286 287
				} else {
					success = append(success, command.ErrorI{
						FileName: fn,
						Message:  "",
					})
288 289
				}
			}
290
郑周 authored
291
			// 解析完成
292 293 294 295 296
			out = command.OutResult{
				Status:  "completed",
				Success: success,
				Failure: failure,
			}
297 298 299 300 301 302

			// 30分钟后失效
			_ = xredis.Set(key, out, 30*time.Minute)

			// 删除临时文件夹
			_ = os.RemoveAll(dstDir)
303 304 305 306 307 308 309 310 311 312 313 314 315 316
		}

	}()

}

func (controller *ImportController) writeLocal(file multipart.File) (string, string, string, error) {
	var err error
	id, err := utils.NewSnowflakeId()
	if err != nil {
		return "", "", "", err
	}
	id2 := fmt.Sprintf("%v", id)
	day := time.Now().Format("2006-01-02")
317
	zipPath := constant.UPLOAD_ZIP_PATH + "/" + day + "-" + id2 + "/" + "temp"
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

	var fd *os.File

	dir := filepath.Dir(zipPath)
	err = os.MkdirAll(dir, os.ModePerm)
	if err != nil {
		return "", "", "", err
	}

	fd, err = os.OpenFile(zipPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		return "", "", "", err
	}
	defer func(fd *os.File) {
		if err = fd.Close(); err != nil {

		}
	}(fd)

	wt := bufio.NewWriter(fd)
	_, err = file.Seek(0, io.SeekStart)
	if err != nil {
		return "", "", "", err
	}
	_, err = io.Copy(wt, file)
	if err != nil {
		return "", "", "", err
	}

	err = wt.Flush()
	if err != nil {
		return "", "", "", err
	}

	return zipPath, day, id2, err
}

func (controller *ImportController) Unzip(zipPath, dstDir string) ([]string, error) {
	// 文件名称
	fileNames := make([]string, 0)
	// open zip file
	reader, err := zip.OpenReader(zipPath)
	if err != nil {
		return fileNames, err
	}
	defer reader.Close()
365 366 367 368 369 370 371 372 373 374 375 376
	var decodeName string
	for _, f := range reader.File {
		if f.Flags == 0 { // 如果标致位是0,则是默认的本地编码(默认为gbk),如果标志为是 1 << 11也就是 2048(则是utf-8编码)
			r := bytes.NewReader([]byte(f.Name))
			decoder := transform.NewReader(r, simplifiedchinese.GB18030.NewDecoder())
			content, _ := ioutil.ReadAll(decoder)
			decodeName = string(content)
		} else {
			decodeName = f.Name
		}

		if err := controller.unzipFile(f, decodeName, dstDir); err != nil {
377 378
			return fileNames, err
		} else {
379 380 381
			if !(f.FileInfo().IsDir()) {
				fileNames = append(fileNames, decodeName)
			}
382 383 384 385 386 387
		}
	}
	return fileNames, nil
}

// 解析文件并插入数据
388 389 390 391 392 393 394 395
func (controller *ImportController) parserAndInsert(file *os.File, fileName string) error {
	defer func() {
		err := file.Close()
		if err != nil {
			return
		}
	}()
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
	reader, err := excelize.OpenReader(file)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传错误:"+err.Error())
	}
	index := reader.GetActiveSheetIndex()
	rows, err := reader.GetRows(reader.GetSheetName(index))
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "读取excel错误:"+err.Error())
	}
	dimensions, err := domain.LoadPerformanceDimensions(rows)
	if err != nil {
		return application.ThrowError(application.ARG_ERROR, err.Error())
	}
	if err, list := controller.parseTemplateNodeContent(dimensions); err != nil {
		return application.ThrowError(application.ARG_ERROR, err.Error())
	} else {
		if len(list) == 0 {
			return application.ThrowError(application.ARG_ERROR, "没有数据内容")
		}
郑周 authored
416 417 418
		var nameWithSuffix = path.Base(fileName)
		var suffix = path.Ext(nameWithSuffix)
		var nameOnly = strings.TrimSuffix(nameWithSuffix, suffix)
419
420 421 422 423 424 425
		ruService := service.NewEvaluationTemplateService()
		in := &templateCommand.CreateTemplateCommand{}

		ua := middlewares.GetUser(controller.Ctx)
		in.CompanyId = ua.CompanyId
		in.CreatorId = ua.UserId
郑周 authored
426
		in.Name = nameOnly
427 428
		in.Describe = ""
		in.NodeContents = list
429
		in.State = domain.TemplateStateWaitActive
430 431

		if _, err := ruService.Create(in); err != nil {
432
			return application.ThrowError(application.ARG_ERROR, err.Error())
433 434 435 436 437
		}
	}
	return nil
}
438
func (controller *ImportController) unzipFile(f *zip.File, fName string, dstDir string) error {
439
	// create the directory of file
440 441
	filePath := path.Join(dstDir, fName)
	if f.FileInfo().IsDir() {
442 443 444 445 446 447 448 449 450 451
		if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
			return err
		}
		return nil
	}
	if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
		return err
	}

	// open the file
452
	rc, err := f.Open()
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
	if err != nil {
		return err
	}
	defer rc.Close()

	// create the file
	w, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer w.Close()

	// save the decompressed file content
	_, err = io.Copy(w, rc)
	return err
}