service.go 18.5 KB
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 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 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 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/utils/excel"
	"github.com/xuri/excelize/v2"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/web/excelData/command"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/web/excelData/query"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/domainService"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_manufacture"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/cost_structured"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/util/converter"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/util/oss"
	"io"
	"strconv"
	"strings"
)

type ExcelDataService struct {
}

func NewExcelDataService(param map[string]interface{}) *ExcelDataService {
	return &ExcelDataService{}
}

// ImportCooperationUser 导入共创用户信息
func (srv ExcelDataService) ImportCooperationUser(importDataCommand *command.ImportDataCommand) (interface{}, error) {
	initPassword, _, err := domainService.GetInitPassword(importDataCommand.Operator)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	userGateway := allied_creation_user.NewHttplibAlliedCreationUser(importDataCommand.Operator)
	orgResult, err := userGateway.OrgGet(allied_creation_user.ReqOrgGet{
		OrgId: int(importDataCommand.Operator.OrgId),
	})
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 3 //第二行开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "userCode", CnName: "*用户编码"},
		{EnName: "userName", CnName: "*用户姓名"},
		{EnName: "cooperationCompany", CnName: "合伙公司"},
		{EnName: "cooperationDeadline", CnName: "合伙到期"},
		{EnName: "enableStatus", CnName: "*用户状态"},
		{EnName: "phone", CnName: "*手机号"},
		{EnName: "email", CnName: "邮箱"},
	}
	excelData, err := converter.OpenImportFileFromIoReader(excelImport, importDataCommand.Reader, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	users := make([]allied_creation_user.BatchAddUserItem, 0)
	for _, v := range excelData {
		item := allied_creation_user.BatchAddUserItem{
			CompanyId:           importDataCommand.Operator.CompanyId,
			UserType:            domain.UserTypeCooperation,
			UserCode:            v["userCode"],
			Org:                 orgResult.OrgCode,
			UserName:            strings.TrimSpace(v["userName"]),
			Phone:               strings.TrimSpace(v["phone"]),
			Email:               strings.TrimSpace(v["email"]),
			EnableStatus:        strings.TrimSpace(v["enableStatus"]),
			CooperationCompany:  v["cooperationCompany"],
			CooperationDeadline: v["cooperationDeadline"],
		}
		users = append(users, item)
	}

	result, err := userGateway.UserBatchAdd(allied_creation_user.ReqBatchAddUser{
		Users:    users,
		Password: initPassword,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return srv.importResultWithHeader(excelImport.DataFields, result.FailRows, len(users)), nil
}

// ImportCompanyUser 导入公司用户信息
func (srv ExcelDataService) ImportCompanyUser(importDataCommand *command.ImportDataCommand) (interface{}, error) {
	initPassword, _, err := domainService.GetInitPassword(importDataCommand.Operator)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 3 //第二行开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "userCode", CnName: "*用户编码"},
		{EnName: "userName", CnName: "*用户姓名"},
		{EnName: "org", CnName: "*组织机构"},
		{EnName: "department", CnName: "*所属部门"},
		{EnName: "enableStatus", CnName: "*用户状态"},
		{EnName: "phone", CnName: "*手机号"},
		{EnName: "employeeType", CnName: "*员工类型"},
		{EnName: "icCardNumber", CnName: "IC卡号"},
		{EnName: "email", CnName: "邮箱"},
	}
	excelData, err := excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	users := make([]allied_creation_user.BatchAddUserItem, 0)
	for _, v := range excelData {
		if srv.fieldValueAllEmpty(v) {
			continue
		}
		item := allied_creation_user.BatchAddUserItem{
			CompanyId:    importDataCommand.Operator.CompanyId,
			UserType:     domain.UserTypeEmployee,
			UserCode:     strings.TrimSpace(v["userCode"]),
			Org:          strings.TrimSpace(v["org"]),
			Department:   strings.TrimSpace(v["department"]),
			UserName:     strings.TrimSpace(v["userName"]),
			Phone:        strings.TrimSpace(v["phone"]),
			Email:        strings.TrimSpace(v["email"]),
			EnableStatus: strings.TrimSpace(v["enableStatus"]),
			EmployeeType: strings.TrimSpace(v["employeeType"]),
			IcCardNumber: strings.TrimSpace(v["icCardNumber"]),
		}
		users = append(users, item)
	}
	userGateway := allied_creation_user.NewHttplibAlliedCreationUser(importDataCommand.Operator)
	result, err := userGateway.UserBatchAdd(allied_creation_user.ReqBatchAddUser{
		Users:    users,
		Password: initPassword,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return srv.importResultWithHeader(excelImport.DataFields, result.FailRows, len(users)), nil
}

// ImportOrganization 导入组织
func (srv ExcelDataService) ImportOrganization(importDataCommand *command.ImportDataCommand) (interface{}, error) {
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 3 //第二行开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "orgCode", CnName: "*部门编码"},
		{EnName: "orgName", CnName: "*部门名称"},
		{EnName: "parentOrgCode", CnName: "*上级部门编码"},
	}
	excelData, err := excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	items := make([]allied_creation_user.BatchAddOrgItem, 0)
	for _, v := range excelData {
		if srv.fieldValueAllEmpty(v) {
			continue
		}
		item := allied_creation_user.BatchAddOrgItem{
			CompanyId:     importDataCommand.Operator.CompanyId,
			OrgCode:       v["orgCode"],
			OrgName:       v["orgName"],
			ParentOrgCode: v["parentOrgCode"],
		}
		items = append(items, item)
	}
	userGateway := allied_creation_user.NewHttplibAlliedCreationUser(importDataCommand.Operator)
	result, err := userGateway.OrgBatchAdd(allied_creation_user.ReqBatchAddOrg{
		OrgList: items,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return srv.importResultWithHeader(excelImport.DataFields, result.FailRows, len(items)), nil
}

// ImportProduct 导入生产信息
func (srv ExcelDataService) ImportProduct(importDataCommand *command.ImportDataCommand) (interface{}, error) {
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 3 //第二行开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "productCode", CnName: "产品编号"},
		{EnName: "productName", CnName: "*品名"},
		{EnName: "unit", CnName: "*规格"},
		{EnName: "productCategory", CnName: "*类别"},
		{EnName: "unitWeight", CnName: "投入单份重量"},
	}
	excelData, err := converter.OpenImportFileFromIoReader(excelImport, importDataCommand.Reader, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	items := make([]*domain.ImportProductItem, 0)
	for _, v := range excelData {
		item := &domain.ImportProductItem{
			ProductCode:     strings.TrimSpace(v["productCode"]),
			ProductName:     strings.TrimSpace(v["productName"]),
			ProductCategory: strings.TrimSpace(v["productCategory"]),
			Unit:            strings.TrimSpace(v["unit"]),
			UnitWeight:      strings.TrimSpace(v["unitWeight"]),
		}
		items = append(items, item)
	}

	svr := allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(importDataCommand.Operator)
	result, err := svr.BatchAddProduct(allied_creation_manufacture.BatchAddProductRequest{
		List: items,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return srv.importResultWithHeader(excelImport.DataFields, *result, len(items)), nil
}

// ImportProduct 导入生产信息
func (srv ExcelDataService) ImportDevice(importDataCommand *command.ImportDataCommand) (interface{}, error) {
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 3 //第二行开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "deviceCode", CnName: "*设备编号"},
		{EnName: "deviceName", CnName: "*设备名称"},
		{EnName: "deviceModel", CnName: "*设备型号"},
		{EnName: "deviceType", CnName: "*设备类型"},
		{EnName: "brand", CnName: "品牌"},
		{EnName: "status", CnName: "*状态"},
		{EnName: "level", CnName: "*风险等级"},
	}
	excelData, err := converter.OpenImportFileFromIoReader(excelImport, importDataCommand.Reader, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	items := make([]*domain.ImportDeviceItem, 0)
	for _, v := range excelData {
		item := &domain.ImportDeviceItem{
			DeviceCode:  strings.TrimSpace(v["deviceCode"]),
			DeviceName:  strings.TrimSpace(v["deviceName"]),
			DeviceModel: strings.TrimSpace(v["deviceModel"]),
			DeviceType:  strings.TrimSpace(v["deviceType"]),
			Brand:       strings.TrimSpace(v["brand"]),
			Status:      strings.TrimSpace(v["status"]),
			Level:       strings.TrimSpace(v["level"]),
		}
		items = append(items, item)
	}

	svr := allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(importDataCommand.Operator)
	result, err := svr.BatchAddDevice(allied_creation_manufacture.BatchAddDeviceRequest{
		List: items,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return srv.importResultWithHeader(excelImport.DataFields, *result, len(items)), nil
}

// ImportCost 导入成本结构化
func (srv ExcelDataService) ImportCost(importDataCommand *command.ImportDataCommand) (interface{}, error) {
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 2 //第二行开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "projectCode", CnName: "*项目编码"},
		{EnName: "itemName", CnName: "*细项名称"},
		{EnName: "choiceId", CnName: "*节点类型"},
		{EnName: "text", CnName: "文本(数值)内容"},
		{EnName: "image", CnName: "图片"},
		{EnName: "formula", CnName: "计算公式"},
		{EnName: "chargePersons", CnName: "*负责人"},
		{EnName: "target", CnName: "目标值"},
		{EnName: "targetPeriod", CnName: "目标值期限"},
		{EnName: "present", CnName: "现状值"},
		{EnName: "schedulePlanPercent", CnName: "进度计划比"},
		{EnName: "benchmark", CnName: "标杆值"},
		{EnName: "highest", CnName: "历史最高值"},
		{EnName: "yesterdayActual", CnName: "昨日实际值"},
	}
	var buf bytes.Buffer
	tee := io.TeeReader(importDataCommand.Reader, &buf)
	excelData, err := converter.OpenImportFileFromIoReader(excelImport, tee, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	importCostCommand := &command.ImportCostDataCommand{}
	err = json.Unmarshal([]byte(importDataCommand.Where), importCostCommand)
	if err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, "风险类型不能为空")
	}
	if importCostCommand.Types <= 0 {
		return nil, application.ThrowError(application.ARG_ERROR, "风险类型不能为空")
	}
	f, err := excelize.OpenReader(&buf)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	index := f.GetActiveSheetIndex()
	//获取公司下所有用户
	users, err := allied_creation_user.NewHttplibAlliedCreationUser(importDataCommand.Operator).UserSearch(allied_creation_user.ReqUserSearch{CompanyId: importDataCommand.Operator.CompanyId, Limit: 10000})
	if err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, "获取用户数据失败")
	}
	userMap := make(map[string]allied_creation_user.UserDetail)
	for _, item := range users.Users {
		userMap[item.UserInfo.UserName] = item
	}
	createCostManagemant := cost_structured.BatchAddCostManagemantRequest{
		BatchCreateCostManagemant: &domain.BatchCreateCostManagemant{
			UserId:          importDataCommand.Operator.UserId,
			CompanyId:       importDataCommand.Operator.CompanyId,
			ProjectName:     importDataCommand.FileName,
			Types:           importCostCommand.Types,
			CostManagemants: make([]*domain.CostManagemant, 0),
		},
	}
	for key, v := range excelData {
		_, mBytes, err := f.GetPicture(f.GetSheetName(index), "E"+fmt.Sprintf("%v", excelImport.RowBegin+key))
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "读取图片失败")
		}
		var ossFile string
		if mBytes != nil {
			ossFile, err = oss.UploadOss(mBytes)
			if err != nil {
				return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传图片失败")
			}
		}
		//choiceId, err := strconv.Atoi(v["choiceId"])
		choiceId := domain.NodeType{}.GetIdByName(strings.TrimSpace(v["choiceId"]))
		// 负责人
		chargePersons := make([]string, 0)
		names := strings.Split(strings.TrimSpace(v["chargePersons"]), " ")
		for _, userName := range names {
			if userName == "" {
				continue
			}
			if user, ok := userMap[userName]; ok {
				chargePersons = append(chargePersons, fmt.Sprintf("%v", user.UserId))
			} else {
				chargePersons = append(chargePersons, "0")
			}
		}
		//目标值期限
		targetPeriod, _ := strconv.Atoi(strings.TrimSpace(v["targetPeriod"]))
		item := &domain.CostManagemant{
			ProjectCode:         strings.TrimSpace(v["projectCode"]),
			ItemName:            strings.TrimSpace(v["itemName"]),
			ChoiceId:            choiceId,
			Text:                strings.TrimSpace(v["text"]),
			Formula:             strings.TrimSpace(v["formula"]),
			ChargePersons:       chargePersons,
			Target:              strings.TrimSpace(v["target"]),
			TargetPeriod:        targetPeriod,
			Present:             strings.TrimSpace(v["present"]),
			SchedulePlanPercent: strings.TrimSpace(v["schedulePlanPercent"]),
			Benchmark:           strings.TrimSpace(v["benchmark"]),
			Highest:             strings.TrimSpace(v["highest"]),
			YesterdayActual:     strings.TrimSpace(v["yesterdayActual"]),
			Types:               importCostCommand.Types,
		}
		if ossFile != "" {
			item.Urls = []string{ossFile}
		} else {
			item.Urls = []string{}
		}
		createCostManagemant.CostManagemants = append(createCostManagemant.CostManagemants, item)
	}
	result, err := cost_structured.NewHttpLibCostStructured(importDataCommand.Operator).BatchCreateCostManagemant(createCostManagemant)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return result.Data, nil
}

// 导入结果
func (srv ExcelDataService) importResultWithHeader(headers []excel.DataField, failRows []interface{}, totalRow int) interface{} {
	var result = map[string]interface{}{
		"successCount": 0,
		"fail":         struct{}{},
	}
	if len(failRows) == 0 {
		result["successCount"] = totalRow
	}
	if len(failRows) > 0 {
		fail := map[string]interface{}{
			"body": failRows,
		}
		var header = make(map[string]string)
		for i := 0; i < len(headers); i++ {
			item := headers[i]
			header[item.EnName] = item.CnName
		}
		fail["header"] = header
		result["fail"] = fail
	}
	return result
}

func (srv ExcelDataService) fieldValueAllEmpty(param map[string]string) bool {
	isAllEmpty := true
	for _, v := range param {
		value := strings.TrimSpace(v)
		if len(value) > 0 {
			isAllEmpty = false
		}
	}
	return isAllEmpty
}

// FileImportTemplate 导入模板
func (srv ExcelDataService) FileImportTemplate(importDataCommand *command.ImportDataCommand) (interface{}, error) {
	var mapTemplate = map[string]string{
		domain.ImportCompanyUser:           "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/opportunity/dev_online/20220222/object/1645495589_cFNDGRTfCxYMZ5hPYzfKxThYd3ywARRz.xlsx",
		domain.ImportOrganization:          "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20210916/object/1631807490_r2XWhGmbWWmpbeePBkZ3EJQFKcZEMpEm.xlsx",
		domain.ImportDividendsOrders:       "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20210927/object/1632743206_NPYTKw6RGhXn4TpYNEQhGGdCkXKXTnxM.xlsx",
		domain.ImportCooperationUser:       "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20210926/object/1632635345_SbfzmkXjQHhCwPw4MB7zb5EBBtdp2MSE.xlsx",
		domain.ImportDividendsReturnOrders: "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20210927/object/1632743214_rNHm6ZBXZaC5xKTrsE7M4h45MY6n6Ff3.xlsx",
		domain.ImportProducts:              "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220120/object/1642670543_cbraNKjNPHcbN6RNBYQBrwhC7BXGbDWp.xlsx",
		domain.ImportDevices:               "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220126/object/1643184320_hT6sY5BKHmBa4TynfSGSCGyZ2KTTtzkj.xlsx",
		domain.ImportCosts:                 "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220311/object/1646977166_ATAD4tJbBDp4WhNFABatTZzkJDeZWB3K.xlsx",
	}
	var url string
	var ok bool
	if url, ok = mapTemplate[importDataCommand.Code]; !ok {
		return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("模板:%v 不存在", importDataCommand.Code))
	}
	return map[string]string{
		"url": url,
	}, nil
}

func (srv ExcelDataService) GetExcelDataFields(param *query.ExcelDataFieldsQuery) (interface{}, error) {
	dataFileds := []DataFieldOptions{}
	switch param.Code {
	case domain.ExportCompanyUser:
		dataFileds = (ExportCompanyUserData{}).AllFields()
	case domain.ExportCooperationUser:
		dataFileds = (ExportCooperationUserData{}).AllFields()
	}
	return dataFileds, nil
}