作者 yangfu

增加导入商品信息

... ... @@ -18,13 +18,14 @@ require (
github.com/onsi/gomega v1.11.0
github.com/sergi/go-diff v1.2.0 // indirect
github.com/smartystreets/goconvey v1.7.2 // indirect
github.com/tal-tech/go-zero v1.0.27
github.com/stretchr/testify v1.7.0
github.com/valyala/fasthttp v1.32.0 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
golang.org/x/text v0.3.6
)
replace github.com/linmadan/egglib-go v0.0.0-20210313060205-8b5e456b11f7 => github.com/tiptok/egglib-go v0.0.0-20210608073225-c852ce95ae34
replace github.com/linmadan/egglib-go v0.0.0-20210313060205-8b5e456b11f7 => github.com/tiptok/egglib-go v0.0.0-20220120032512-24dfab2b4987
... ...
... ... @@ -305,6 +305,10 @@ github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFB
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a h1:9ZKAASQSHhDYGoxY8uLVpewe1GDZ2vu2Tr/vTdVAkFQ=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/richardlehane/mscfb v1.0.3 h1:rD8TBkYWkObWO0oLDFCbwMeZ4KoalxQy+QgniCj3nKI=
github.com/richardlehane/mscfb v1.0.3/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=
github.com/richardlehane/msoleps v1.0.1 h1:RfrALnSNXzmXLbGct/P2b4xkFz4e8Gmj/0Vj9M9xC1o=
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
... ... @@ -347,8 +351,8 @@ github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2K
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
github.com/tal-tech/go-zero v1.0.27 h1:QMIbaTxibMc/OsO5RTAuKZ8ndbl2dGN6pITQEtp2x/A=
github.com/tal-tech/go-zero v1.0.27/go.mod h1:JtNXlsh/CgeIHyQnt5C5M2IcSevW7V0NAnqO93TQgm8=
github.com/tiptok/egglib-go v0.0.0-20210608073225-c852ce95ae34 h1:9iDNyYbfpv5KLWDLpDywD/aIODg+PNnwn+v9on7KGlE=
github.com/tiptok/egglib-go v0.0.0-20210608073225-c852ce95ae34/go.mod h1:KT8WFA2LPo5zVKbomCR6HocO4prnIY9DUVGekA3Ifo4=
github.com/tiptok/egglib-go v0.0.0-20220120032512-24dfab2b4987 h1:0e2hOSL+//5AL7e1r3xCGEugsOPsw2POAm82VZvWLe4=
github.com/tiptok/egglib-go v0.0.0-20220120032512-24dfab2b4987/go.mod h1:xl9i83IKNUkwlobRF6XLKn1RRbZsT+7yhCicpTGWTKc=
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/tmc/grpc-websocket-proxy v0.0.0-20171017195756-830351dc03c6/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo=
... ... @@ -381,6 +385,10 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg=
github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3 h1:EpI0bqf/eX9SdZDwlMmahKM+CDBgNbsXMhsN28XrM8o=
github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
github.com/xuri/excelize/v2 v2.4.1 h1:veeeFLAJwsNEBPBlDepzPIYS1eLyBVcXNZUW79exZ1E=
github.com/xuri/excelize/v2 v2.4.1/go.mod h1:rSu0C3papjzxQA3sdK8cU544TebhrPUoTOaGPIh0Q1A=
github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2/go.mod h1:hzfGeIUDq/j97IG+FhNqkowIyEcD88LrW6fyU3K3WqY=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI=
... ... @@ -427,9 +435,12 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210218145215-b8e89b74b9df/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a h1:kr2P4QFmQr29mSLA43kwrOcgcReGTfbE9N577tCTuBc=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 h1:/UOmuWzQfxxo9UtlXMwuQU8CMgg1eZXqTRwkSQJWKOI=
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb h1:fqpd0EBDzlHRCjiphRR5Zo/RSWWQlWv34418dnEixWk=
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
... ... @@ -463,8 +474,9 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210510120150-4163338589ed h1:p9UgmWI9wKpfYmgaV/IZKGdXc5qEK45tDwwwDyjS26I=
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985 h1:4CSI6oo7cOjJKajidEljs9h+uP0rRZBPPPhcCbj5mw8=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
... ... @@ -504,8 +516,9 @@ golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210218155724-8ebf48af031b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E=
golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
... ...
package command
import (
"encoding/json"
"fmt"
"github.com/beego/beego/v2/core/validation"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
type ExportDataCommand struct {
//操作人
Operator *domain.OperateInfo `json:"-"`
// 业务编码
Ids []string `json:"ids"`
Where json.RawMessage `json:"where"`
// 业务编码
Code string `form:"code"`
}
func (exportDataCommand *ExportDataCommand) Valid(validation *validation.Validation) {
}
func (exportDataCommand *ExportDataCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(exportDataCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
func (exportDataCommand *ExportDataCommand) UnmarshalQuery(query interface{}) error {
return json.Unmarshal(exportDataCommand.Where, query)
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"io"
)
type ImportDataCommand struct {
//操作人
Operator *domain.OperateInfo `json:"-"`
Reader io.Reader `json:"-"`
FileExt string `json:"-"`
// 业务编码
Code string `form:"code"`
}
func (importDataCommand *ImportDataCommand) Valid(validation *validation.Validation) {
}
func (importDataCommand *ImportDataCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(importDataCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import ()
type CooperationUserListQuery struct {
//操作人
//Operator domain.Operator `json:"-"`
//用户名称
UserName string `json:"userName"`
//共创公司
CooperationCompany string `json:"cooperationCompany"`
SelectedField []string `json:"selectedField"`
}
... ...
package service
// ExportCompanyUser 导出公司用户信息列表
//func (srv ExcelDataService) ExportCompanyUser(companyUserListQuery *query.CompanyUserListQuery) (ExportCompanyUserData, error) {
// creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(companyUserListQuery.Operator)
// result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
// Limit: 10000,
// CompanyId: companyUserListQuery.Operator.CompanyId,
// OrganizationId: 0,
// DepartmentId: 0,
// UserName: companyUserListQuery.UserName,
// DepName: companyUserListQuery.DepartmentName,
// Phone: "",
// UserType: domain.UserTypeEmployee,
// InOrgIds: companyUserListQuery.Operator.OrgIds,
// PullRealTime: true,
// })
// if err != nil {
// return ExportCompanyUserData{}, fmt.Errorf("获取企业用户数据失败:%w", err)
// }
// return ExportCompanyUserData{
// SourceData: result.Users,
// SelectedField: companyUserListQuery.SelectedField,
// }, nil
//}
// ExportCooperationUser 导出共创用户信息列表
//func (srv ExcelDataService) ExportCooperationUser(companyUserListQuery *query.CooperationUserListQuery) (ExportCooperationUserData, error) {
// creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(companyUserListQuery.Operator)
// result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
// Limit: 10000,
// CompanyId: companyUserListQuery.Operator.CompanyId,
// OrganizationId: 0,
// DepartmentId: 0,
// UserName: companyUserListQuery.UserName,
// CooperationCompany: companyUserListQuery.CooperationCompany,
// Phone: "",
// UserType: domain.UserTypeCooperation,
// InOrgIds: companyUserListQuery.Operator.OrgIds,
// })
// if err != nil {
// return ExportCooperationUserData{}, fmt.Errorf("获取企业用户数据失败:%w", err)
// }
// return ExportCooperationUserData{SourceData: result.Users, SelectedField: companyUserListQuery.SelectedField}, nil
//}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
"strings"
"github.com/linmadan/egglib-go/utils/excel"
)
type ExcelDataService struct {
}
func NewExcelDataService(param map[string]interface{}) *ExcelDataService {
return &ExcelDataService{}
}
// 导入结果
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/open-api/dev_online/20210916/object/1631807485_EaxECeRz23WpzrMZmbwdEPRJ3Pdxpx5X.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",
}
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(code string) (interface{}, error) {
dataFields := []DataFieldOptions{}
//switch code {
//case domain.ExportCompanyUser:
// dataFileds = (ExportCompanyUserData{}).AllFields()
//case domain.ExportCooperationUser:
// dataFileds = (ExportCooperationUserData{}).AllFields()
//}
return dataFields, nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/excel"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
productService "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/product/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils/converter"
"strings"
)
// 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 := productService.NewProductService(nil)
failRows, err := svr.BatchAddProduct(importDataCommand.Operator, items)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return srv.importResultWithHeader(excelImport.DataFields, failRows, len(items)), nil
}
... ...
package service
type DataFieldOptions struct {
EnName string `json:"enName"`
CnName string `json:"cnName"`
IsDefault bool `json:"isDefault"`
}
//
//// ExportCompanyUserData 导出公司用户数据
//type ExportCompanyUserData struct {
// SourceData []allied_creation_user.UserDetail
// SelectedField []string
//}
//
//var _ excel.ExcelMaker = (*ExportCompanyUserData)(nil)
//
//func (data ExportCompanyUserData) AllFields() []DataFieldOptions {
// return []DataFieldOptions{
// {EnName: "UserCode", CnName: "用户编码"},
// {EnName: "UserName", CnName: "用户姓名"},
// {EnName: "Phone", CnName: "手机号"},
// {EnName: "DepartmentName", CnName: "所属部门"},
// {EnName: "EnableStatus", CnName: "状态"},
// {EnName: "OrgName", CnName: "组织机构"},
// }
//}
//
//func (data ExportCompanyUserData) DataFieldList() []excel.DataField {
// fields := []excel.DataField{}
// allFields := data.AllFields()
// for _, value2 := range allFields {
// if len(data.SelectedField) == 0 || value2.IsDefault {
// fields = append(fields, excel.DataField{EnName: value2.EnName, CnName: value2.CnName})
// continue
// }
// for _, value3 := range data.SelectedField {
// if value2.EnName == value3 {
// fields = append(fields, excel.DataField{EnName: value2.EnName, CnName: value2.CnName})
// }
// }
// }
// return fields
//}
//
//func (data ExportCompanyUserData) CellValue(index int, enName string) (value interface{}) {
// if index > data.DataListLen() {
// return ""
// }
// switch enName {
// case "UserCode":
// return data.SourceData[index].UserCode
// case "UserName":
// return data.SourceData[index].UserInfo.UserName
// case "Phone":
// return data.SourceData[index].UserInfo.Phone
// case "DepartmentName":
// if data.SourceData[index].Department != nil {
// return data.SourceData[index].Department.DepartmentName
// } else {
// return ""
// }
// case "EnableStatus":
// status := data.SourceData[index].EnableStatus
// statusName := ""
// // 状态(1:启用 2:禁用 3:注销)
// switch status {
// case 1:
// statusName = "启用"
// case 2:
// statusName = "禁用"
// case 3:
// statusName = "注销"
// }
// return statusName
// case "OrgName":
// if data.SourceData[index].Org != nil {
// return data.SourceData[index].Org.OrgName
// } else {
// return ""
// }
// }
// return nil
//}
//
//func (data ExportCompanyUserData) DataListLen() int {
// return len(data.SourceData)
//}
//
//func (data ExportCompanyUserData) TableTitle() []string {
// return nil
//}
//
////ExportCooperationUserData 导出共创用户数据
//type ExportCooperationUserData struct {
// SourceData []allied_creation_user.UserDetail
// SelectedField []string
//}
//
//var _ excel.ExcelMaker = (*ExportCooperationUserData)(nil)
//
//func (data ExportCooperationUserData) AllFields() []DataFieldOptions {
// return []DataFieldOptions{
// {EnName: "UserCode", CnName: "用户编码"},
// {EnName: "UserName", CnName: "用户姓名"},
// {EnName: "Phone", CnName: "手机号"},
// {EnName: "CooperationCompany", CnName: "共创公司"},
// {EnName: "CooperationDeadline", CnName: "共创到期"},
// {EnName: "EnableStatus", CnName: "状态"},
// }
//}
//
//func (data ExportCooperationUserData) DataFieldList() []excel.DataField {
// fields := []excel.DataField{}
// allFields := data.AllFields()
// for _, value2 := range allFields {
// if len(data.SelectedField) == 0 || value2.IsDefault {
// fields = append(fields, excel.DataField{EnName: value2.EnName, CnName: value2.CnName})
// continue
// }
// for _, value3 := range data.SelectedField {
// if value2.EnName == value3 {
// fields = append(fields, excel.DataField{EnName: value2.EnName, CnName: value2.CnName})
// }
// }
// }
// return fields
//}
//
//func (data ExportCooperationUserData) CellValue(index int, enName string) (value interface{}) {
// if index > data.DataListLen() {
// return ""
// }
// switch enName {
// case "UserCode":
// return data.SourceData[index].UserCode
// case "UserName":
// return data.SourceData[index].UserInfo.UserName
// case "CooperationCompany":
// return data.SourceData[index].CooperationInfo.CooperationCompany
// case "CooperationDeadline":
// if data.SourceData[index].CooperationInfo.CooperationDeadline.IsZero() || data.SourceData[index].CooperationInfo.CooperationDeadline.Unix() == 0 {
// return ""
// }
// return data.SourceData[index].CooperationInfo.CooperationDeadline.Format("2006-01-02")
// case "Phone":
// return data.SourceData[index].UserInfo.Phone
// case "Email":
// return data.SourceData[index].UserInfo.Email
// case "EnableStatus":
// status := data.SourceData[index].EnableStatus
// statusName := ""
// // 状态(1:启用 2:禁用 3:注销)
// switch status {
// case 1:
// statusName = "启用"
// case 2:
// statusName = "禁用"
// case 3:
// statusName = "注销"
// }
// return statusName
// }
// return nil
//}
//
//func (data ExportCooperationUserData) DataListLen() int {
// return len(data.SourceData)
//}
//
//func (data ExportCooperationUserData) TableTitle() []string {
// return nil
//}
... ...
... ... @@ -3,12 +3,14 @@ package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/product/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/product/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/product/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
... ... @@ -275,6 +277,33 @@ func (productService *ProductService) SearchProduct(operateInfo *domain.OperateI
}
// 创建产品服务
func (productService *ProductService) BatchAddProduct(opt *domain.OperateInfo, list []*domain.ImportProductItem) ([]interface{}, error) {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
batchAddProductService, _ := domainService.NewPGBatchAddProductService(transactionContext.(*pgTransaction.TransactionContext))
var failRows []interface{}
if failRows, err = batchAddProductService.BatchAddProduct(opt, list); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if len(failRows) != 0 {
return failRows, nil //有错误行,回滚
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return failRows, nil
}
func NewProductService(options map[string]interface{}) *ProductService {
newProductService := &ProductService{}
return newProductService
... ...
... ... @@ -28,6 +28,8 @@ type SearchProductJobQuery struct {
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
}
func (cmd *SearchProductJobQuery) Valid(validation *validation.Validation) {
... ...
... ... @@ -38,6 +38,7 @@ func (productSectionService *ProductSectionService) CreateProductSection(createP
newProductSection := &domain.ProductSection{
SectionId: uniqueId,
SectionName: createProductSectionCommand.SectionName,
Removed: domain.NotDeleted,
}
var workshopRepository domain.WorkshopRepository
var workshop *domain.Workshop
... ...
... ... @@ -30,6 +30,6 @@ func (dto *WorkshopDto) LoadDto(m *domain.Workshop) *WorkshopDto {
dto.WorkshopId = m.WorkshopId
dto.WorkshopName = m.WorkshopName
dto.Principal = m.Principal
dto.ProductLines = m.ProductLines
dto.ProductLines = m.GetProductLines(domain.NotDeleted)
return dto
}
... ...
... ... @@ -279,6 +279,49 @@ func (workshopService *WorkshopService) SearchWorkshop(operateInfo *domain.Opera
}
// 搜索车间服务列表
func (workshopService *WorkshopService) SelectorWorkshop(operateInfo *domain.OperateInfo, listWorkshopQuery *query.SearchWorkshopQuery) (interface{}, error) {
if err := listWorkshopQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
workshopRepository, _, err := factory.FastPgWorkshop(transactionContext, 0)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var count int64
var workshops []*domain.Workshop
options := utils.ObjectToMap(listWorkshopQuery)
options["companyId"] = operateInfo.CompanyId
options["orgId"] = operateInfo.OrgId
if count, workshops, err = workshopRepository.Find(options); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var results = make([]*dto.WorkshopDto, 0)
for i := range workshops {
newItem := &dto.WorkshopDto{}
results = append(results, newItem.LoadDto(workshops[i]))
}
return map[string]interface{}{
"count": count,
"workshops": results,
}, nil
}
func NewWorkshopService(options map[string]interface{}) *WorkshopService {
newWorkshopService := &WorkshopService{}
return newWorkshopService
... ...
... ... @@ -18,6 +18,12 @@ var (
ErrorNotFound = fmt.Errorf("没有此资源")
)
// excel 编码
var (
ExcelImportProduct = "MANUFACTURE_EXCEL_IMPORT_PRODUCT"
ExcelExportProduct = "MANUFACTURE_EXCEL_EXPORT_PRODUCT"
)
/***** 1.数据权限 *****/
// DataAuthor 数据验证器
type DataAuthor interface {
... ...
package domain
import "time"
import (
"fmt"
"strconv"
"time"
)
// 产品信息
type Product struct {
... ... @@ -62,3 +66,38 @@ func (product *Product) Update(data map[string]interface{}) error {
product.UpdatedAt = time.Now()
return nil
}
// 导入数据体
type ImportProductItem struct {
// 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001
ProductCode string `json:"productCode,omitempty"`
// 产品名称
ProductName string `json:"productName,omitempty"`
// 产品类别
ProductCategory string `json:"productCategory,omitempty"`
// 单位
Unit string `json:"unit,omitempty"`
// 单份重量(原材料)
UnitWeight string `json:"unitWeight,omitempty"`
// 失败理由
FailReason string `json:"failReason"`
}
func (item *ImportProductItem) Valid() error {
if len(item.ProductName) == 0 {
return fmt.Errorf("品名不能为空")
}
if len(item.Unit) == 0 {
return fmt.Errorf("规格不能为空")
}
if len(item.ProductCategory) == 0 {
return fmt.Errorf("类别不能为空")
}
if len(item.UnitWeight) == 0 {
item.UnitWeight = "0"
}
if _, err := strconv.ParseFloat(item.UnitWeight, 64); err != nil {
return fmt.Errorf("投入单份重量格式有误")
}
return nil
}
... ...
... ... @@ -8,6 +8,19 @@ type ProductLine struct {
LineName string `json:"lineName,omitempty"`
// 工段列表
ProductSections []*ProductSection `json:"productSections,omitempty"`
// 已删除标识 0:正常 1:已删除
// 已删除标识 1:正常 2:已删除
Removed int `json:"removed,omitempty"`
}
func (productLine *ProductLine) GetProductSections(removed int) []*ProductSection {
var result = make([]*ProductSection, 0)
for i := range productLine.ProductSections {
if removed > 0 && productLine.ProductSections[i].Removed != removed {
continue
}
item := productLine.ProductSections[i]
item.Removed = 0
result = append(result, item)
}
return result
}
... ...
... ... @@ -6,6 +6,6 @@ type ProductSection struct {
SectionId int `json:"sectionId,omitempty"`
// 工段名称
SectionName string `json:"sectionName,omitempty"`
// 已删除标识 0:正常 1:已删除
// 已删除标识 1:正常 2:已删除
Removed int `json:"removed,omitempty"`
}
... ...
... ... @@ -7,9 +7,9 @@ import (
const (
// 未删除
NotDeleted = 0
NotDeleted = 1
// 已删除
Deleted = 1
Deleted = 2
)
// 车间
... ... @@ -203,3 +203,17 @@ func (workshop *Workshop) FindWorkStation(workshopId, lineId, sectionId int) (*W
}
return NewWorkStation(workshop, line, section), nil
}
func (workshop *Workshop) GetProductLines(removed int) []*ProductLine {
var result = make([]*ProductLine, 0)
for i := range workshop.ProductLines {
if removed > 0 && workshop.ProductLines[i].Removed != removed {
continue
}
item := workshop.ProductLines[i]
item.Removed = 0 // 隐藏
item.ProductSections = item.GetProductSections(removed)
result = append(result, item)
}
return result
}
... ...
package domainService
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"strconv"
"time"
)
type PGBatchAddProductService struct {
transactionContext *pgTransaction.TransactionContext
}
func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, list []*domain.ImportProductItem) ([]interface{}, error) {
var failRows = make([]interface{}, 0)
productRepository, _ := repository.NewProductRepository(ptr.transactionContext)
_, products, _ := productRepository.Find(map[string]interface{}{"companyId": opt.CompanyId, "orgId": opt.OrgId})
var mapProduct = make(map[string]*domain.Product)
for i := range products {
mapProduct[products[i].ProductCode] = products[i]
}
var generator = redis.NewProductCodeCache(opt.CompanyId)
for i := range list {
item := list[i]
if err := item.Valid(); err != nil {
item.FailReason = err.Error()
failRows = append(failRows, item)
continue
}
unitWeight, _ := strconv.ParseFloat(item.UnitWeight, 64)
newItem := &domain.Product{
CompanyId: opt.CompanyId,
OrgId: opt.OrgId,
ProductCode: item.ProductCode,
ProductName: item.ProductName,
ProductCategory: item.ProductCategory,
ProductSpec: &domain.UnitQuantity{
Unit: item.Unit,
UnitWeight: unitWeight,
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if len(newItem.ProductCode) == 0 {
code, err := redis.GenCode(generator)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
}
newItem.ProductCode = code
}
if _, ok := mapProduct[newItem.ProductCode]; !ok {
mapProduct[newItem.ProductCode] = newItem
} else {
item.FailReason = "导入的产品编号已存在"
failRows = append(failRows, item)
continue
}
if _, err := productRepository.Save(newItem); err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
}
}
return failRows, nil
}
func NewPGBatchAddProductService(transactionContext *pgTransaction.TransactionContext) (*PGBatchAddProductService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &PGBatchAddProductService{
transactionContext: transactionContext,
}, nil
}
}
... ...
package converter
import (
"bytes"
"encoding/csv"
"fmt"
"github.com/linmadan/egglib-go/utils/excel"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
"io"
"strings"
"unicode/utf8"
)
type (
CSVReader struct {
Data *excel.ExcelImport
}
)
func (cr *CSVReader) ToMap(reader io.Reader) ([]map[string]string, error) {
var err error
if reader, err = cr.PrepareCheck(reader); err != nil {
return nil, err
}
r := csv.NewReader(reader)
rows := make([]map[string]string, 0)
var header = make([]string, 0)
var headerMap = make(map[string]string)
var index int = 0
for i := range cr.Data.DataFields {
item := cr.Data.DataFields[i]
headerMap[item.CnName] = item.EnName
}
for {
index++
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if index <= cr.Data.RowBegin-1 {
continue
}
if len(header) == 0 {
header = record
} else {
dict := map[string]string{}
for i := range header {
if column, ok := headerMap[header[i]]; ok {
dict[column] = record[i]
}
}
rows = append(rows, dict)
}
}
return rows, nil
}
func (cr *CSVReader) PrepareCheck(reader io.Reader) (io.Reader, error) {
return GBKToUtf8(reader)
}
func GBKToUtf8(readIn io.Reader) (io.Reader, error) {
var (
err error
fileByte []byte
)
fileByte, err = io.ReadAll(readIn)
if err != nil {
return nil, err
}
if utf8.Valid(fileByte) {
return bytes.NewReader(fileByte), nil
} else {
utf8Reader := transform.NewReader(bytes.NewReader(fileByte), simplifiedchinese.GBK.NewDecoder())
return utf8Reader, nil
}
}
func OpenImportFileFromIoReader(ex *excel.ExcelImport, reader io.Reader, ext string) ([]map[string]string, error) {
var tmp []map[string]string
var err error
if ext == "csv" || ext == ".csv" {
csvReader := &CSVReader{ex}
tmp, err = csvReader.ToMap(reader)
} else {
tmp, err = ex.OpenExcelFromIoReader(reader)
}
if err != nil {
return nil, err
}
var response []map[string]string
for i := range tmp {
if fieldValueAllEmpty(tmp[i]) {
continue
}
response = append(response, tmp[i])
}
return response, nil
}
func fieldValueAllEmpty(param map[string]string) bool {
isAllEmpty := true
for _, v := range param {
value := strings.TrimSpace(v)
if len(value) > 0 {
isAllEmpty = false
}
}
return isAllEmpty
}
// TODO: export csv
func MakeToCsv(sourData excel.ExcelMaker, w io.Writer) error {
_, err := w.Write([]byte("\xEF\xBB\xBF")) //写入UTF-8 BOM
if err != nil {
return err
}
csvWriter := csv.NewWriter(w)
fields := sourData.DataFieldList()
firstRow := []string{}
for i := range fields {
firstRow = append(firstRow, fields[i].CnName)
}
title := sourData.TableTitle()
if len(title) > 0 {
csvWriter.Write(title)
}
csvWriter.Write(firstRow)
dataLenght := sourData.DataListLen()
for i := 0; i < dataLenght; i++ {
rowData := []string{}
for ii := range fields {
cellValue := sourData.CellValue(i, fields[ii].EnName)
str := ""
if cellValue != nil {
str = fmt.Sprintf("%v", cellValue)
}
rowData = append(rowData, str)
}
csvWriter.Write(rowData)
}
csvWriter.Flush()
return csvWriter.Error()
}
... ...
... ... @@ -262,3 +262,29 @@ func CopyObject(src, dst interface{}) {
}
}
}
/*
时间计算
*/
func ValidWorkTime(t string) error {
ts := strings.Split(t, ":")
if len(ts) != 2 {
return fmt.Errorf("时间格式有误")
}
ts1, err := strconv.Atoi(ts[0])
if err != nil {
return fmt.Errorf("小时格式有误")
}
if !(ts1 < 24 && ts1 >= 0) {
return fmt.Errorf("小时格式有误")
}
ts2, err := strconv.Atoi(ts[1])
if err != nil {
return fmt.Errorf("分钟格式有误")
}
if !(ts2 < 60 && ts2 >= 0) {
return fmt.Errorf("分钟格式有误")
}
return nil
}
... ...
package utils
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestTimeSpan(t *testing.T) {
inputs := []struct {
t string
e bool
}{
{"10:00", false},
{"10:11", false},
{"24:00", true},
{"-1:00", true},
{"10:60", true},
{"A:B", true},
}
for i := range inputs {
err := ValidWorkTime(inputs[i].t)
if inputs[i].e {
assert.NotNil(t, err)
} else {
assert.Nil(t, err)
}
}
}
... ...
package controllers
import (
"fmt"
"github.com/beego/beego/v2/server/web/context"
"github.com/linmadan/egglib-go/utils/excel"
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"io"
"path/filepath"
)
type ExcelDataController struct {
beego.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) FileImport() {
var (
data interface{}
err error
r io.Reader
ext string
)
//excelService := service.NewExcelDataService(nil)
r, ext, err = controller.GetFileWithExt()
if err != nil {
controller.Response(nil, err)
return
}
cmd := &command.ImportDataCommand{}
controller.ParseForm(cmd)
cmd.Operator = ParseOperateInfo(controller.BaseController)
cmd.Reader = r
cmd.FileExt = ext
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)
default:
err = fmt.Errorf("导入不存在 Code:%v", cmd.Code)
}
controller.Response(data, err)
}
// FileExport 文件导出
func (controller *ExcelDataController) FileExport() {
// 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 = ParseOperateInfo(controller.BaseController)
// 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 = "导出共创用户"
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)
}
//GetExcelDataFields 获取导出excel数据的可选字段
func (controller *ExcelDataController) GetExcelDataFields() {
}
func (controller *ExcelDataController) GetFileWithExt() (io.Reader, string, error) {
excelFile, fileHeader, err := controller.GetFile("file")
if err != nil {
log.Logger.Error(err.Error())
return nil, "", fmt.Errorf("上传文件不存在")
}
ext := filepath.Ext(fileHeader.Filename)
if !(ext == ".xlsx" || ext == ".xls" || ext == ".csv") {
return nil, "", fmt.Errorf("仅支持上传文件格式 xls/xlsx/csv")
}
return excelFile, ext, nil
}
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)
}
... ...
... ... @@ -5,6 +5,7 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/product/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/product/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/product/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
type ProductController struct {
... ... @@ -69,3 +70,13 @@ func (controller *ProductController) SearchProduct() {
total, data, err := productService.SearchProduct(ParseOperateInfo(controller.BaseController), listProductQuery)
ResponseGrid(controller.BaseController, total, data, err)
}
func (controller *ProductController) BatchAddProduct() {
productService := service.NewProductService(nil)
cmd := &struct {
List []*domain.ImportProductItem `json:"list"`
}{}
controller.Unmarshal(cmd)
data, err := productService.BatchAddProduct(ParseOperateInfo(controller.BaseController), cmd.List)
controller.Response(data, err)
}
... ...
... ... @@ -66,3 +66,11 @@ func (controller *WorkshopController) SearchWorkshop() {
data, err := workshopService.SearchWorkshop(ParseOperateInfo(controller.BaseController), listWorkshopQuery)
controller.Response(data, err)
}
func (controller *WorkshopController) SelectorWorkshop() {
workshopService := service.NewWorkshopService(nil)
listWorkshopQuery := &query.SearchWorkshopQuery{}
controller.Unmarshal(listWorkshopQuery)
data, err := workshopService.SearchWorkshop(ParseOperateInfo(controller.BaseController), listWorkshopQuery)
controller.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego/controllers"
)
func init() {
web.Router("/file-import", &controllers.ExcelDataController{}, "Post:FileImport")
web.Router("/file-export", &controllers.ExcelDataController{}, "Post:FileExport")
web.Router("/file-import-template/:code", &controllers.ExcelDataController{}, "Get:FileImportTemplate")
}
... ...
... ... @@ -12,4 +12,5 @@ func init() {
web.Router("/products/:productId", &controllers.ProductController{}, "Delete:RemoveProduct")
web.Router("/products/", &controllers.ProductController{}, "Get:ListProduct")
web.Router("/products/search", &controllers.ProductController{}, "Post:SearchProduct")
web.Router("/products/batch-add", &controllers.ProductController{}, "Post:BatchAddProduct")
}
... ...
... ... @@ -12,4 +12,5 @@ func init() {
web.Router("/workshops/:workshopId", &controllers.WorkshopController{}, "Delete:RemoveWorkshop")
web.Router("/workshops/", &controllers.WorkshopController{}, "Get:ListWorkshop")
web.Router("/workshops/search", &controllers.WorkshopController{}, "Post:SearchWorkshop")
web.Router("/workshops/selector", &controllers.WorkshopController{}, "Post:SelectorWorkshop")
}
... ...