excel_data_controller.go 16.2 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
package web_client

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/url"
	"strings"

	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/middleware"

	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"

	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/web/excelData/command"

	"github.com/beego/beego/v2/server/web/context"
	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/utils/excel"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/web/excelData/query"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/web/excelData/service"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_cooperation"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"
)

type ExcelDataController struct {
	baseController
}

func (controller *ExcelDataController) responseExcelByFile(ctx *context.Context, excelExport *excel.ExcelExport, fileName string) error {
	ctx.Output.Header("Content-Disposition", "attachment; filename="+fileName)
	ctx.Output.Header("Content-Description", "File Transfer")
	ctx.Output.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	ctx.Output.Header("Content-Transfer-Encoding", "binary")
	ctx.Output.Header("Expires", "0")
	ctx.Output.Header("Cache-Control", "must-revalidate")
	ctx.Output.Header("Pragma", "public")
	//跳过保存文件,直接写入ctx.ResponseWriter
	excelExport.ExcelFile.Write(ctx.ResponseWriter)
	return nil
}

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

// ImportDividendsOrder 导入分红订单
func (controller *ExcelDataController) ImportDividendsOrder() {
	importDividendsOrder(controller)
}

func importDividendsOrder(controller *ExcelDataController) {

	fileReader, err := controller.GetExcelFile()
	if err != nil {
		controller.Response(nil, err)
		return
	}
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 3 //第3行开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "OriginalOrderNum", CnName: "*来源单号"},
		{EnName: "DividendsCustomerName", CnName: "*客户名称"},
		{EnName: "OrderGoodName", CnName: "*产品名称"},
		{EnName: "OrderTime", CnName: "*订单日期"},
		{EnName: "RegionName", CnName: "*订单区域"},
		{EnName: "OrderGoodQuantity", CnName: "*产品数量"},
		{EnName: "OrderGoodPrice", CnName: "*产品价格"},
		{EnName: "Expense", CnName: "费用"},
		{EnName: "CooperationContractNumber", CnName: "*项目合约编号"},
	}
	excelData, err := excelImport.OpenExcelFromIoReader(fileReader)
	if err != nil {
		log.Logger.Error("解析excel文件失败," + err.Error())
		controller.Response(nil, err)
		return
	}
	//订单数据
	var returnedOrderData []allied_creation_cooperation.ImportDividendsOrderData
	for _, v := range excelData {
		if allEmpty := controller.fieldValueAllEmpty(v); allEmpty {
			//以全字段空跳过
			break
		}
		//TODO 按需转化
		item := allied_creation_cooperation.ImportDividendsOrderData{
			OriginalOrderNum:          strings.TrimSpace(v["OriginalOrderNum"]),
			DividendsCustomerName:     strings.TrimSpace(v["DividendsCustomerName"]),
			OrderGoodName:             strings.TrimSpace(v["OrderGoodName"]),
			OrderTime:                 strings.TrimSpace(v["OrderTime"]),
			RegionName:                strings.TrimSpace(v["RegionName"]),
			OrderGoodQuantity:         strings.TrimSpace(v["OrderGoodQuantity"]),
			OrderGoodPrice:            strings.TrimSpace(v["OrderGoodPrice"]),
			Expense:                   strings.TrimSpace(v["Expense"]),
			CooperationContractNumber: strings.TrimSpace(v["CooperationContractNumber"]),
		}
		returnedOrderData = append(returnedOrderData, item)
	}
	creationCooperationGate := allied_creation_cooperation.NewHttplibAlliedCreationCooperation(controller.GetOperator())
	result, err := creationCooperationGate.ImportDividendsOrder(allied_creation_cooperation.ReqImportDividendsOrder{
		DividendsOrderData: returnedOrderData,
	})
	if err != nil {
		controller.Response(nil, err)
		return
	}
	controller.Response(result, nil)
}

// ImportDividendsReturnedOrder 导入分红退货单
func (controller *ExcelDataController) ImportDividendsReturnedOrder() {
	importDividendsReturnedOrder(controller)
}

func importDividendsReturnedOrder(controller *ExcelDataController) {

	fileReader, err := controller.GetExcelFile()
	if err != nil {
		controller.Response(nil, err)
		return
	}
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 3 //第2行表头开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "OriginalOrderNum", CnName: "*来源单号"},
		{EnName: "DividendsReturnedCustomerName", CnName: "*客户名称"},
		{EnName: "OrderGoodName", CnName: "*产品名称"},
		{EnName: "DividendsReturnedDate", CnName: "*退货日期"},
		{EnName: "OrderTime", CnName: "*订单日期"},
		{EnName: "RegionName", CnName: "*退货区域"},
		{EnName: "OrderGoodQuantity", CnName: "*退货数量"},
		{EnName: "OrderGoodPrice", CnName: "*退货价格"},
		{EnName: "CooperationContractNumber", CnName: "*项目合约编号"},
	}
	excelData, err := excelImport.OpenExcelFromIoReader(fileReader)
	if err != nil {
		log.Logger.Error("解析excel文件失败," + err.Error())
		controller.Response(nil, err)
		return
	}
	//退货单数据
	returnedOrderData := []allied_creation_cooperation.ImportDividendsReturnedOrderData{}
	for _, v := range excelData {
		if allEmpty := controller.fieldValueAllEmpty(v); allEmpty {
			//以全字段空跳过
			break
		}
		//TODO 按需转化
		item := allied_creation_cooperation.ImportDividendsReturnedOrderData{
			OriginalOrderNum:              strings.TrimSpace(v["OriginalOrderNum"]),
			DividendsReturnedCustomerName: strings.TrimSpace(v["DividendsReturnedCustomerName"]),
			OrderGoodName:                 strings.TrimSpace(v["OrderGoodName"]),
			DividendsReturnedDate:         strings.TrimSpace(v["DividendsReturnedDate"]),
			OrderTime:                     strings.TrimSpace(v["OrderTime"]),
			RegionName:                    strings.TrimSpace(v["RegionName"]),
			OrderGoodQuantity:             strings.TrimSpace(v["OrderGoodQuantity"]),
			OrderGoodPrice:                strings.TrimSpace(v["OrderGoodPrice"]),
			CooperationContractNumber:     strings.TrimSpace(v["CooperationContractNumber"]),
		}
		returnedOrderData = append(returnedOrderData, item)
	}
	creationCooperationGate := allied_creation_cooperation.NewHttplibAlliedCreationCooperation(controller.GetOperator())
	result, err := creationCooperationGate.ImportDividendsReturnedOrder(allied_creation_cooperation.ReqImportDividendsReturnedOrder{
		DividendsReturnedOrderData: returnedOrderData,
	})
	if err != nil {
		controller.Response(nil, err)
		return
	}
	controller.Response(result, nil)
}

// FileImport 文件导入
func (controller *ExcelDataController) FileImport() {
	code := controller.GetString("code")
	switch code {
	case domain.ImportDividendsOrders:
		importDividendsOrder(controller)
	case domain.ImportDividendsReturnOrders:
		importDividendsReturnedOrder(controller)
	case "ImportProductRecordLevel2", "ImportAttendance", "ImportProductTrouble":
		sourceFile, err := controller.GetExcelFile()
		if err != nil {
			e := application.ThrowError(application.TRANSACTION_ERROR, err.Error())
			controller.Response(nil, e)
			return
		}
		bodyBuf := &bytes.Buffer{}
		formWriter := multipart.NewWriter(bodyBuf)
		fileWriter, _ := formWriter.CreateFormFile("file", code+".xlsx")
		io.Copy(fileWriter, sourceFile)
		formWriter.WriteField("code", code)
		formWriter.Close()
		target, _ := url.Parse(constant.ALLIED_CREATION_MANUFACTURE_HOST)
		targetPath := strings.Replace(controller.Ctx.Request.URL.Path, "/v1/web", "", 1)
		newReq, _ := http.NewRequest(http.MethodPost, target.String()+targetPath, bodyBuf)
		// 传递当前登录信息(可配置)
		loginToken, ok := middleware.FormCtxLoginToken(controller.Ctx)
		if ok && loginToken.CompanyId > 0 && loginToken.OrgId > 0 {
			newReq.Header.Set("companyId", fmt.Sprintf("%v", loginToken.CompanyId))
			newReq.Header.Set("orgId", fmt.Sprintf("%v", loginToken.OrgId))
			newReq.Header.Set("userId", fmt.Sprintf("%v", loginToken.UserId))
			orgIdList := make([]string, 0)
			for i := range loginToken.OrgIds {
				orgIdList = append(orgIdList, fmt.Sprintf("%d", loginToken.OrgIds[i]))
			}
			newReq.Header.Add("orgIds", fmt.Sprintf("%v", strings.Join(orgIdList, ",")))
		}
		newReq.Header.Set("Content-Type", formWriter.FormDataContentType())
		resp, err := http.DefaultClient.Do(newReq)
		if err != nil {
			e := application.ThrowError(application.TRANSACTION_ERROR, err.Error())
			controller.Response(nil, e)
			return
		}
		respData, _ := io.ReadAll(resp.Body)
		controller.Ctx.ResponseWriter.Write(respData)
	default:
		defaultImport(controller)
	}
}

func defaultImport(controller *ExcelDataController) {
	var (
		data     interface{}
		err      error
		r        io.Reader
		ext      string
		fileName string
	)
	excelService := service.NewExcelDataService(nil)
	r, ext, fileName, err = controller.GetFileWithExt()
	if err != nil {
		controller.Response(nil, err)
		return
	}
	cmd := &command.ImportDataCommand{}
	controller.ParseForm(cmd)
	cmd.Operator = controller.GetOperator()
	cmd.Reader = r
	cmd.FileExt = ext
	cmd.FileName = fileName
	switch cmd.Code {
	case domain.ImportCompanyUser:
		data, err = excelService.ImportCompanyUser(cmd)
	case domain.ImportCooperationUser:
		data, err = excelService.ImportCooperationUser(cmd)
	case domain.ImportOrganization:
		data, err = excelService.ImportOrganization(cmd)
	case domain.ImportProducts:
		data, err = excelService.ImportProduct(cmd)
	case domain.ImportDevices:
		data, err = excelService.ImportDevice(cmd)
	case domain.ImportCosts:
		data, err = excelService.ImportCost(cmd)
	default:
		err = fmt.Errorf("导入不存在 Code:%v", cmd.Code)
	}
	controller.Response(data, err)
}

func (controller *ExcelDataController) FileImportTemplate() {
	excelService := service.NewExcelDataService(nil)
	cmd := &command.ImportDataCommand{}
	code := controller.GetString(":code")
	cmd.Code = code
	var data interface{}
	data, err := excelService.FileImportTemplate(cmd)
	controller.Response(data, err)
}

// FileExport 文件导出
func (controller *ExcelDataController) FileExport() {
	fileExport(controller, "")
}

func fileExport(controller *ExcelDataController, code string) {
	// 1.读取command
	exportDataCommand := &command.ExportDataCommand{}
	err := controller.Unmarshal(exportDataCommand)
	if err != nil {
		log.Logger.Debug("json err:" + err.Error())
		controller.Response(nil, err)
		return
	}
	exportDataCommand.Operator = controller.GetOperator()

	if exportDataCommand.Code == "" && code != "" {
		exportDataCommand.Code = code
	}
	// 2.读取data
	var data excel.ExcelMaker
	var filename string
	var excelService = service.NewExcelDataService(nil)
	switch exportDataCommand.Code {
	case domain.ExportCompanyUser:
		companyUserListQuery := &query.CompanyUserListQuery{}
		exportDataCommand.UnmarshalQuery(companyUserListQuery)
		companyUserListQuery.Operator = exportDataCommand.Operator
		data, err = excelService.ExportCompanyUser(companyUserListQuery)
		filename = "导出公司用户"
	case domain.ExportCooperationUser:
		companyUserListQuery := &query.CooperationUserListQuery{}
		exportDataCommand.UnmarshalQuery(companyUserListQuery)
		companyUserListQuery.Operator = exportDataCommand.Operator
		data, err = excelService.ExportCooperationUser(companyUserListQuery)
		filename = "导出共创用户"
	case domain.ExportProducts:
		companyUserListQuery := &query.SearchProductQuery{}
		exportDataCommand.UnmarshalQuery(companyUserListQuery)
		companyUserListQuery.Operator = exportDataCommand.Operator
		data, err = excelService.ExportProducts(companyUserListQuery)
		filename = "导出商品"
	case domain.ExportManufactureEmployeeProductive:
		companyUserListQuery := &query.ManufactureEmployeeProductiveQuery{}
		exportDataCommand.UnmarshalQuery(companyUserListQuery)
		companyUserListQuery.Operator = exportDataCommand.Operator
		data, err = excelService.ExportEmployeeProductive(companyUserListQuery)
		filename = "导出员工产能统计"
	case domain.ExportManufactureWorkshopProductive:
		companyUserListQuery := &query.ManufactureWorkshopProductiveQuery{}
		exportDataCommand.UnmarshalQuery(companyUserListQuery)
		companyUserListQuery.Operator = exportDataCommand.Operator
		data, err = excelService.ExportWorkshopProductive(companyUserListQuery)
		filename = "导出车间产能汇总"
	case domain.ExportManufactureEmployeeAttendanceStatics:
		companyUserListQuery := &query.ManufactureExportEmployeeAttendanceStaticsQuery{}
		controllers.Must(exportDataCommand.UnmarshalQuery(companyUserListQuery))
		companyUserListQuery.Operator = exportDataCommand.Operator
		data, err = excelService.ExportEmployeeAttendanceStatics(companyUserListQuery)
		filename = "导出员工工时统计"
	case domain.ExportManufactureWorkshopAttendanceStatics:
		companyUserListQuery := &query.ManufactureExportWorkshopAttendanceStaticsQuery{}
		controllers.Must(exportDataCommand.UnmarshalQuery(companyUserListQuery))
		companyUserListQuery.Operator = exportDataCommand.Operator
		data, err = excelService.ExportWorkshopAttendanceStatics(companyUserListQuery)
		filename = "导出车间工时汇总"

	case domain.ExportCostStructuredDailyFillingAbnormalLog:
		query := &query.CostDailyFillingAbnormalLogQuery{}
		controllers.Must(exportDataCommand.UnmarshalQuery(query))
		query.Operator = exportDataCommand.Operator
		data, err = excelService.ExportDailyFillingAbnormalLog(query)
		filename = "异常记录"
	default:
		err = fmt.Errorf("export type :%v not exists", exportDataCommand.Code)
	}
	if err != nil {
		log.Logger.Debug("excelService.Export err:" + err.Error())
		controller.Response(nil, err)
		return
	}

	// 3.返回文件
	excelTool := excel.NewExcelExport()
	err = excelTool.ExportData(data, "")
	if err != nil {
		log.Logger.Debug("excelTool.ExportData err:" + err.Error())
		controller.Response(nil, err)
		return
	}
	controller.responseExcelByFile(controller.Ctx, excelTool, filename)
}

// ExportCompanyUser 导出公司用户
func (controller *ExcelDataController) ExportCompanyUser() {
	fileExport(controller, domain.ExportCompanyUser)
}

// ExportCooperationUser 导出共创用户
func (controller *ExcelDataController) ExportCooperationUser() {
	fileExport(controller, domain.ExportCooperationUser)
}

// ExportProducts 导出生产制造产品
func (controller *ExcelDataController) ExportProducts() {
	fileExport(controller, domain.ExportProducts)
}

// ExportManufactureEmployeeProductive 导出生产制造-员工产能统计
func (controller *ExcelDataController) ExportManufactureEmployeeProductive() {
	fileExport(controller, domain.ExportManufactureEmployeeProductive)
}

// ExportManufactureEmployeeProductive 导出生产制造-车间产能统计
func (controller *ExcelDataController) ExportManufactureWorkshopProductive() {
	fileExport(controller, domain.ExportManufactureWorkshopProductive)
}

// ExportManufactureEmployeeAttendanceStatics 导出生产制造-员工工时统计
func (controller *ExcelDataController) ExportManufactureEmployeeAttendanceStatics() {
	fileExport(controller, domain.ExportManufactureEmployeeAttendanceStatics)
}

// ExportManufactureWorkshopAttendanceStatics 导出生产制造-车间工时统计
func (controller *ExcelDataController) ExportManufactureWorkshopAttendanceStatics() {
	fileExport(controller, domain.ExportManufactureWorkshopAttendanceStatics)
}

func (controller *ExcelDataController) ExportCostStructuredDailyFillingAbnormalLog() {
	fileExport(controller, domain.ExportCostStructuredDailyFillingAbnormalLog)
}

// GetExcelDataFields 获取导出excel数据的可选字段
func (controller *ExcelDataController) GetExcelDataFields() {
	code := controller.GetString(":code")
	var excelService = service.NewExcelDataService(nil)
	data, _ := excelService.GetExcelDataFields(&query.ExcelDataFieldsQuery{Code: code})
	controller.Response(data, nil)
}