作者 Administrator

合并分支 'test' 到 'master'

Test



查看合并请求 !27
正在显示 89 个修改的文件 包含 4436 行增加172 行删除
FROM 192.168.0.243:5000/mmm/allied-creation-gateway:libfontconfig
ENV APP_DIR $GOPATH/src/project-20211222
ENV APP_DIR $GOPATH/src/project-20220324
RUN mkdir -p $APP_DIR
WORKDIR $APP_DIR/
COPY ./pkg pkg
... ...
... ... @@ -111,10 +111,14 @@ spec:
value: "http://allied-creation-user-dev.fjmaimaimai.com"
- name: ALLIED_CREATION_COOPERATION_HOST
value: "http://allied-creation-cooperation-dev.fjmaimaimai.com"
- name: ALLIED_CREATION_MANUFACTURE_HOST
value: "http://106.75.231.90:9999"
- name: ALLIED_CREATION_BASIC_HOST
value: "http://allied-creation-basic-dev.fjmaimaimai.com"
- name: SMS_SERVE_HOST
value: "https://sms.fjmaimaimai.com:9897"
- name: COST_STRUCTURED
value: "http://cost-structured-dev.fjmaimaimai.com"
- name: SUPLUS_SALE_APP
value: "http://suplus-sale-app-gateway-test.fjmaimaimai.com"
# - name: REDIS_HOST
... ...
... ... @@ -115,10 +115,14 @@ spec:
value: "https://allied-creation-user-prd.fjmaimaimai.com"
- name: ALLIED_CREATION_COOPERATION_HOST
value: "https://allied-creation-cooperation-prd.fjmaimaimai.com"
- name: ALLIED_CREATION_MANUFACTURE_HOST
value: "https://allied-creation-manufacture-prd.fjmaimaimai.com"
- name: ALLIED_CREATION_BASIC_HOST
value: "https://allied-creation-basic-prd.fjmaimaimai.com"
- name: SMS_SERVE_HOST
value: "https://sms.fjmaimaimai.com:9897"
- name: COST_STRUCTURED
value: "http://cost-structured-prd.fjmaimaimai.com"
# - name: REDIS_HOST
# valueFrom:
# configMapKeyRef:
... ...
... ... @@ -119,10 +119,18 @@ spec:
value: "https://allied-creation-cooperation-test.fjmaimaimai.com"
- name: ALLIED_CREATION_BASIC_HOST
value: "https://allied-creation-basic-test.fjmaimaimai.com"
- name: ALLIED_CREATION_MANUFACTURE_HOST
value: "http://allied-creation-manufacture-test.fjmaimaimai.com"
- name: SMS_SERVE_HOST
value: "https://sms.fjmaimaimai.com:9897"
- name: COST_STRUCTURED
value: "http://cost-structured-test.fjmaimaimai.com"
- name: SUPLUS_SALE_APP
value: "http://suplus-sale-app-gateway-test.fjmaimaimai.com"
- name: MANUFACTURE_WEIGH_DEFAULT_COMPANYID
value: "23"
- name: MANUFACTURE_WEIGH_DEFAULT_ORGID
value: "487"
# - name: REDIS_HOST
# valueFrom:
# configMapKeyRef:
... ...
... ... @@ -4,16 +4,21 @@ go 1.16
require (
github.com/GeeTeam/gt3-golang-sdk v0.0.0-20200116043922-446ca8a507d2
github.com/aliyun/aliyun-oss-go-sdk v2.2.1+incompatible
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
github.com/beego/beego/v2 v2.0.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/disintegration/imaging v1.6.2
github.com/emirpasic/gods v1.12.0
github.com/forgoer/openssl v0.0.0-20210828150411-6c5378b5b719
github.com/go-pg/pg/v10 v10.10.1
github.com/go-redis/redis v6.15.7+incompatible
github.com/google/uuid v1.1.1
github.com/linmadan/egglib-go v0.0.0-20210827085852-177fa745932d
github.com/pdfcpu/pdfcpu v0.3.13
github.com/satori/go.uuid v1.2.0 // indirect
github.com/stretchr/testify v1.7.0
github.com/tal-tech/go-queue v1.0.5
github.com/xuri/excelize/v2 v2.4.1
golang.org/x/text v0.3.6
)
... ...
... ... @@ -16,7 +16,11 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk=
github.com/aliyun/aliyun-oss-go-sdk v2.2.1+incompatible h1:uuJIwCFhbZy+zdvLy5zrcIToPEQP0s5CFOZ0Zj03O/w=
github.com/aliyun/aliyun-oss-go-sdk v2.2.1+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q=
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f h1:ZNv7On9kyUzm7fvRZumSyy/IUiSC7AzL0I1jKKtwooA=
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc=
github.com/beanstalkd/go-beanstalk v0.1.0/go.mod h1:/G8YTyChOtpOArwLTQPY1CHB+i212+av35bkPXXj56Y=
github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE=
github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI=
... ... @@ -73,6 +77,8 @@ github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox
github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk=
github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4=
github.com/emicklei/proto v1.9.0/go.mod h1:rn1FgRS/FANiZdD2djyH7TMA9jdRDcYQ9IEN9yvjX0A=
github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg=
github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
... ... @@ -299,6 +305,8 @@ github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6So
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=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/segmentio/kafka-go v0.4.2 h1:QXZ6q9Bu1JkAJQ/CQBb2Av8pFRG8LQ0kWCrLXgQyL8c=
github.com/segmentio/kafka-go v0.4.2/go.mod h1:Inh7PqOsxmfgasV8InZYKVXWsdjcCq2d9tFV75GLbuM=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
... ... @@ -481,6 +489,7 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
... ...
... ... @@ -2,6 +2,7 @@ package command
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"reflect"
"strings"
... ... @@ -23,6 +24,15 @@ type CompanySignUpCommand struct {
Password string `cname:"密码" json:"password" valid:"Required"`
// 短信验证码
SmsCode string `cname:"短信验证码" json:"smsCode" valid:"Required"`
// 法人
LegalPerson string `cname:"法人" json:"legalPerson" valid:"Required"`
// 社会信用代码
SocialCreditCode string `cname:"社会信用代码" json:"socialCreditCode" valid:"Required"`
// 营业执照所在地
BusinessLicenseAddress domain.BusinessLicenseAddress `cname:"营业执照所在地" json:"businessLicenseAddress" valid:"Required"`
// 营业执照-附件
BusinessLicenseAttachments []domain.Attachment `cname:"营业执照-附件" json:"businessLicenseAttachments" valid:"Required"`
}
func (companySignUpCommand *CompanySignUpCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -7,12 +7,13 @@ import (
)
type LoginCommand struct {
Phone string `json:"phone" valid:"Required"`
GrantType string `json:"grantType" valid:"Required"` //登录方式(signInPassword 密码登录、signInCaptcha 验证码登录)
Password string `json:"password"`
Captcha string `json:"captcha"`
SessionMode int `json:"sessionMode"`
DeviceType string `json:"-"`
Phone string `json:"phone" valid:"Required"`
GrantType string `json:"grantType" valid:"Required"` //登录方式(signInPassword 密码登录、signInCaptcha 验证码登录)
Password string `json:"password"`
Captcha string `json:"captcha"`
SessionMode int `json:"sessionMode"`
DeviceType string `json:"-"`
LoginPlatform string `json:"-"` //登录平台
}
func (orgAddCommand *LoginCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -40,6 +40,9 @@ func (svr AuthService) AuthLogin(loginCommand *command.LoginCommand) (interface{
if loginCommand.DeviceType == domain.DeviceTypeWeb {
loginPlatform = domain.LoginPlatformWeb
}
if len(loginCommand.LoginPlatform) != 0 {
loginPlatform = loginCommand.LoginPlatform
}
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
_, err = creationUserGateway.AuthRefreshIM(allied_creation_user.ReqAuthRefreshIM{
Phone: loginCommand.Phone,
... ... @@ -406,6 +409,11 @@ func (svr AuthService) CompanySignUp(companySignUpCommand *command.CompanySignUp
Contacts: companySignUpCommand.Contacts,
IndustryCategory: companySignUpCommand.IndustryCategory,
Scale: companySignUpCommand.Scale,
LegalPerson: companySignUpCommand.LegalPerson,
SocialCreditCode: companySignUpCommand.SocialCreditCode,
BusinessLicenseAttachments: companySignUpCommand.BusinessLicenseAttachments,
BusinessLicenseAddress: companySignUpCommand.BusinessLicenseAddress,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
... ... @@ -548,7 +556,7 @@ func (svr AuthService) getUserInfo(operator domain.Operator) (interface{}, error
func (svr AuthService) getToken(loginToken domain.LoginToken) (map[string]interface{}, error) {
// 1.匹配账号对应的用户
currentUser, err := svr.matchUser(&loginToken)
currentUser, err := svr.matchUserV2(&loginToken)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
... ... @@ -629,7 +637,7 @@ func (svr AuthService) matchUser(loginToken *domain.LoginToken) (*allied_creatio
loopUser1:
for _, v := range userSearchResult.Users {
for _, vv := range v.UserOrg {
if vv.OrgID == int(loginToken.OrgId) {
if vv.OrgID == int(loginToken.OrgId) && v.Company.Status == domain.CompanyAuthenticated {
currentOrgIsOK = true
currentUser = v
break loopUser1
... ... @@ -688,6 +696,99 @@ loopUser1:
return &currentUser, nil
}
func (svr AuthService) matchUserV2(loginToken *domain.LoginToken) (*allied_creation_user.UserDetail, error) {
var users []allied_creation_user.UserDetail
var currentUser *allied_creation_user.UserDetail
var defaultUser *allied_creation_user.UserDetail
var ok bool
var mapOrgUser = make(map[int]*allied_creation_user.UserDetail)
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
switch loginToken.Platform {
case domain.LoginPlatformWeb:
userSearchResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Phone: loginToken.Account,
UserType: domain.UserTypeEmployee,
EnableStatus: domain.UserStatusEnable,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "用户信息获取失败,"+err.Error())
}
users = userSearchResult.Users
case domain.LoginPlatformApp:
userSearchResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Phone: loginToken.Account,
UserType: domain.UserTypeEmployee | domain.UserTypeCooperation | domain.UserTypeVisitor,
EnableStatus: domain.UserStatusEnable,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "用户信息获取失败,"+err.Error())
}
users = userSearchResult.Users
case domain.LoginPlatformOperatorWeb:
userSearchResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Phone: loginToken.Account,
UserType: domain.UserTypeOperationAdmin,
EnableStatus: domain.UserStatusEnable,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "用户信息获取失败,"+err.Error())
}
users = userSearchResult.Users
}
if len(users) == 0 {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "账号不存在")
}
for index, user := range users {
if user.Company != nil && user.Company.Status != domain.CompanyAuthenticated {
continue
}
for _, userOrg := range user.UserOrg {
mapOrgUser[userOrg.OrgID] = &users[index]
if defaultUser == nil {
defaultUser = &users[index]
}
}
}
if defaultUser == nil {
defaultUser = &users[0]
}
//切换组织
if loginToken.OrgId != 0 {
if currentUser, ok = mapOrgUser[int(loginToken.OrgId)]; !ok { //&& loginToken.Platform == domain.LoginPlatformWeb
return nil, application.ThrowError(application.TRANSACTION_ERROR, "登录的公司组织不可用")
}
}
// 使用默认账号
if currentUser == nil {
currentUser = defaultUser
}
SetLoginToken(loginToken, currentUser)
return currentUser, nil
}
func SetLoginToken(loginToken *domain.LoginToken, currentUser *allied_creation_user.UserDetail) {
// 当前登录的公司用户信息
loginToken.UserId = int64(currentUser.UserId)
loginToken.UserBaseId = int64(currentUser.UserBaseId)
if currentUser.Company != nil {
loginToken.CompanyId = int64(currentUser.Company.CompanyId)
}
// 关联的组织
var orgIds []int64
for i := range currentUser.UserOrg {
orgIds = append(orgIds, int64(currentUser.UserOrg[i].OrgID))
// 默认组织
if loginToken.OrgId == 0 {
loginToken.OrgId = int64(currentUser.UserOrg[i].OrgID)
}
}
loginToken.OrgIds = orgIds
}
//GetCompanyOrgsByUser 获取登录用户的公司组织列表
func (svr AuthService) GetCompanyOrgsByUser(queryParam *query.GetCompanyOrgsByUserQuery) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(queryParam.Operator)
... ... @@ -713,6 +814,9 @@ func (svr AuthService) GetCompanyOrgsByUser(queryParam *query.GetCompanyOrgsByUs
CompanyId: user.Company.CompanyId,
CompanyName: user.Company.CompanyName,
})
if user.Company.Status != domain.CompanyAuthenticated {
continue
}
}
for j := range user.UserOrg {
org := user.UserOrg[j]
... ... @@ -792,3 +896,53 @@ func (svr *AuthService) CaptchaInit(request *query.CaptchaInitRequest) (interfac
rsp = rspData
return rsp, err
}
/*******************运营登录**********************/
//AuthLogin 用户登录
func (svr AuthService) AuthAdminLogin(loginCommand *command.LoginPwdCommand) (interface{}, error) {
login := &command.LoginCommand{
GrantType: "signInPassword",
Phone: loginCommand.Username,
Password: loginCommand.Password,
SessionMode: loginCommand.SessionMode,
DeviceType: loginCommand.DeviceType,
LoginPlatform: domain.LoginPlatformOperatorWeb,
}
return svr.AuthLogin(login)
}
//AuthLogin 用户登录
//func (svr AuthService) AuthAdminLoginBak(loginCommand *command.LoginPwdCommand) (interface{}, error) {
// if err := loginCommand.ValidateCommand(); err != nil {
// return nil, application.ThrowError(application.ARG_ERROR, err.Error())
// }
// if len(loginCommand.Username) == 0 {
// return nil, application.ThrowError(application.BUSINESS_ERROR, "账号不存在")
// }
// creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
// users, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
// UserType: domain.UserTypeOperationAdmin,
// Phone: loginCommand.Username,
// })
// if err != nil {
// return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
// }
// if len(users.Users) == 0 {
// return nil, application.ThrowError(application.BUSINESS_ERROR, "账号不存在")
// }
// login := &command.LoginCommand{
// GrantType: "signInPassword",
// Phone: loginCommand.Username,
// Password: loginCommand.Password,
// SessionMode: loginCommand.SessionMode,
// DeviceType: loginCommand.DeviceType,
// }
// if len(loginCommand.CaptchaChallenge) > 0 {
// geetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
// validateResult := geetest.SuccessValidate(loginCommand.CaptchaChallenge, loginCommand.CaptchaValidate, loginCommand.CaptchaSeccode, "", "")
// if !validateResult {
// log.Logger.Error("validate captcha fail")
// }
// }
// return svr.AuthLogin(login)
//}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type AuditCompanyCommand struct {
// 企业id
CompanyId int64 `cname:"企业id" json:"companyId" valid:"Required"`
// 手机号
Phone string `cname:"手机号" json:"phone" valid:"Required"`
// 审核状态
Status int `cname:"审核状态" json:"status" valid:"Required"`
// 备注
Remark string `cname:"备注" json:"remark" valid:"Required"`
}
func (updateCompanyCommand *AuditCompanyCommand) Valid(validation *validation.Validation) {
if !(updateCompanyCommand.Status == 1 || updateCompanyCommand.Status == 2) {
validation.Error("状态有误")
return
}
if updateCompanyCommand.Status == 1 {
updateCompanyCommand.Status = 2
return
}
if updateCompanyCommand.Status == 2 {
updateCompanyCommand.Status = 3
return
}
}
func (updateCompanyCommand *AuditCompanyCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateCompanyCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateCompanyCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
// type CreateCompanyCommand struct {
// // 企业名称
// CompanyName string `cname:"企业名称" json:"companyName" valid:"Required"`
// // 规模
// Scale string `cname:"规模" json:"scale" valid:"Required"`
// // 公司Logo地址
// Logo string `cname:"公司Logo地址" json:"logo" valid:"Required"`
// // 公司地址
// Address string `cname:"公司地址" json:"address" valid:"Required"`
// // 所属行业
// IndustryCategory string `cname:"所属行业" json:"industryCategory" valid:"Required"`
// // 联系人
// Contacts string `cname:"联系人" json:"contacts" valid:"Required"`
// // 注册时间
// RegisteredTime time.Time `cname:"注册时间" json:"registeredTime,omitempty"`
// // 注册状态 1:已注册 2:待认证 3:已认证
// Status int `cname:"注册状态 1:已注册 2:待认证 3:已认证" json:"status,omitempty"`
// }
// func (createCompanyCommand *CreateCompanyCommand) Valid(validation *validation.Validation) {
// }
// func (createCompanyCommand *CreateCompanyCommand) ValidateCommand() error {
// valid := validation.Validation{}
// b, err := valid.Valid(createCompanyCommand)
// if err != nil {
// return err
// }
// if !b {
// elem := reflect.TypeOf(createCompanyCommand).Elem()
// for _, validErr := range valid.Errors {
// field, isExist := elem.FieldByName(validErr.Field)
// if isExist {
// return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
// } else {
// return fmt.Errorf(validErr.Message)
// }
// }
// }
// return nil
// }
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type EnableCompanyCommand struct {
// 企业id
CompanyId int64 `cname:"企业id" json:"companyId" valid:"Required"`
// 审核状态
Status int `cname:"审核状态" json:"status" valid:"Required"`
}
func (updateCompanyCommand *EnableCompanyCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
if !(updateCompanyCommand.Status == 1 || updateCompanyCommand.Status == 2) {
validation.Error("状态有误")
return
}
if updateCompanyCommand.Status == 1 {
updateCompanyCommand.Status = 2
return
}
if updateCompanyCommand.Status == 2 {
updateCompanyCommand.Status = 4
return
}
}
func (updateCompanyCommand *EnableCompanyCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateCompanyCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateCompanyCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
// type ListCompanyCustomizeMenusCommand struct {
// // 企业id
// CompanyId int64 `cname:"企业id" json:"companyId,string" valid:"Required"`
// // 菜单类别 web app
// MenuCategory string `cname:"菜单类别" json:"menuCategory,omitempty" valid:"Required"`
// }
// func (listCompanyCustomizeMenusCommand *ListCompanyCustomizeMenusCommand) Valid(validation *validation.Validation) {
// }
// func (listCompanyCustomizeMenusCommand *ListCompanyCustomizeMenusCommand) ValidateCommand() error {
// valid := validation.Validation{}
// b, err := valid.Valid(listCompanyCustomizeMenusCommand)
// if err != nil {
// return err
// }
// if !b {
// elem := reflect.TypeOf(listCompanyCustomizeMenusCommand).Elem()
// for _, validErr := range valid.Errors {
// field, isExist := elem.FieldByName(validErr.Field)
// if isExist {
// return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
// } else {
// return fmt.Errorf(validErr.Message)
// }
// }
// }
// return nil
// }
... ...
package command
// type RemoveCompanyCommand struct {
// // 企业id
// CompanyId int64 `cname:"企业id" json:"companyId,string" valid:"Required"`
// }
// func (removeCompanyCommand *RemoveCompanyCommand) Valid(validation *validation.Validation) {
// validation.SetError("CustomValid", "未实现的自定义认证")
// }
// func (removeCompanyCommand *RemoveCompanyCommand) ValidateCommand() error {
// valid := validation.Validation{}
// b, err := valid.Valid(removeCompanyCommand)
// if err != nil {
// return err
// }
// if !b {
// elem := reflect.TypeOf(removeCompanyCommand).Elem()
// for _, validErr := range valid.Errors {
// field, isExist := elem.FieldByName(validErr.Field)
// if isExist {
// return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
// } else {
// return fmt.Errorf(validErr.Message)
// }
// }
// }
// return nil
// }
... ...
package command
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type UpdateCompanyCommand struct {
//操作人
Operator domain.Operator `json:"-"`
// 企业名称
CompanyName string `cname:"企业名称" json:"companyName" valid:"Required"`
// 公司地址
Address string `cname:"公司地址" json:"address" valid:"Required"`
// 系统名称
SystemName string `cname:"系统名称" json:"systemName" valid:"Required"`
// 公司Logo地址
Logo string `cname:"公司Logo地址" json:"logo" valid:"Required"`
}
func (updateCompanyCommand *UpdateCompanyCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (updateCompanyCommand *UpdateCompanyCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateCompanyCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateCompanyCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
// type UpdateCompanyCustomizeMenusCommand struct {
// // 企业id
// CompanyId int64 `cname:"企业id" json:"companyId" valid:"Required"`
// // 菜单编号
// MenuId int64 `cname:"菜单编号" json:"menuId" valid:"Required"`
// // 菜单名称
// //MenuName string `cname:"菜单名称" json:"menuName" valid:"Required"`
// // 菜单别名
// MenuAlias string `cname:"菜单别名" json:"menuAlias" valid:"Required"`
// // 排序
// Sort int `cname:"排序" json:"sort" valid:"Required"`
// }
// func (updateCompanyCustomizeMenusCommand *UpdateCompanyCustomizeMenusCommand) Valid(validation *validation.Validation) {
// //validation.SetError("CustomValid", "未实现的自定义认证")
// }
// func (updateCompanyCustomizeMenusCommand *UpdateCompanyCustomizeMenusCommand) ValidateCommand() error {
// valid := validation.Validation{}
// b, err := valid.Valid(updateCompanyCustomizeMenusCommand)
// if err != nil {
// return err
// }
// if !b {
// elem := reflect.TypeOf(updateCompanyCustomizeMenusCommand).Elem()
// for _, validErr := range valid.Errors {
// field, isExist := elem.FieldByName(validErr.Field)
// if isExist {
// return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
// } else {
// return fmt.Errorf(validErr.Message)
// }
// }
// }
// return nil
// }
... ...
package dto
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
)
type CompanyGetItemDto struct {
CompanyListItemDto
Remark string `json:"remark"`
// 法律相关
// 法人
LegalPerson string `json:"legalPerson"`
// 社会信用代码
SocialCreditCode string `json:"socialCreditCode"`
// 营业执照所在地
BusinessLicenseAddress interface{} `json:"businessLicenseAddress"`
// 营业执照-附件
BusinessLicenseAttachments []domain.Attachment `json:"businessLicenseAttachments"`
}
func (dto *CompanyGetItemDto) LoadDto(c allied_creation_user.CompanyItem, u allied_creation_user.UserDetail) {
companyListItemDto := &CompanyListItemDto{}
companyListItemDto.LoadDto(c, u)
dto.CompanyListItemDto = *companyListItemDto
dto.Remark = c.CompanyInfo.Remark
dto.LegalPerson = c.CompanyInfo.Legal.LegalPerson
dto.SocialCreditCode = c.CompanyInfo.Legal.SocialCreditCode
dto.BusinessLicenseAddress = c.CompanyInfo.Legal.BusinessLicenseAddress
dto.BusinessLicenseAttachments = c.CompanyInfo.Legal.BusinessLicenseAttachments
}
... ...
package dto
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
type CompanyListItemDto struct {
// 企业id
CompanyId int `json:"companyId"`
// 公司名称
CompanyName string `json:"companyName"`
// 规模
Scale string `json:"scale,omitempty"`
// 所属行业
IndustryCategory string `json:"industryCategory,omitempty"`
// 联系人
Contacts string `cname:"联系人" json:"contacts"`
// 手机号码
Phone string `cname:"手机号码" json:"phone"`
// 注册时间
RegisteredTime string `json:"registeredTime,omitempty"`
// 公司状态 1:已注册(待审核) 2:已通过 3:已拒绝
Status int `json:"status"`
}
func (dto *CompanyListItemDto) LoadDto(c allied_creation_user.CompanyItem, u allied_creation_user.UserDetail) *CompanyListItemDto {
dto.CompanyId = c.CompanyId
dto.CompanyName = c.CompanyInfo.CompanyName
dto.Scale = c.CompanyInfo.Scale
dto.IndustryCategory = c.CompanyInfo.IndustryCategory
dto.Contacts = u.UserInfo.UserName
dto.Phone = u.UserInfo.Phone
dto.RegisteredTime = c.CompanyInfo.RegisteredTime.Format("2006-01-02")
dto.Status = c.Status
return dto
}
type CompanyListItemsDto []*CompanyListItemDto
func (dto *CompanyListItemsDto) LoadDto(items []allied_creation_user.CompanyItem, users []allied_creation_user.UserDetail) {
var mapItems = make(map[int]allied_creation_user.CompanyItem)
for i := range items {
mapItems[items[i].CompanyId] = items[i]
}
for i := range users {
if v, ok := mapItems[users[i].Company.CompanyId]; ok {
company := &CompanyListItemDto{}
*dto = append(*dto, company.LoadDto(v, users[i]))
}
}
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GetCompanyQuery struct {
// 企业id
CompanyId int `cname:"企业id" json:"companyId" valid:"Required"`
}
func (getCompanyQuery *GetCompanyQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getCompanyQuery *GetCompanyQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getCompanyQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(getCompanyQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
"reflect"
"strings"
)
type ListCompanyQuery struct {
// 查询偏离量
PageNumber int `json:"pageNumber"`
// 查询限制
PageSize int `json:"pageSize" valid:"Required"`
// 状态
Status int `cname:"状态" json:"status,omitempty"`
// 企业名称
CompanyName string `cname:"企业名称" json:"companyName,omitempty"`
}
func (listCompanyQuery *ListCompanyQuery) Valid(validation *validation.Validation) {
}
func (listCompanyQuery *ListCompanyQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listCompanyQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listCompanyQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"github.com/emirpasic/gods/sets/hashset"
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/company/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/company/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/company/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"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/sms_serve"
)
// 企业
type CompanyService struct {
}
// 创建企业
// func (companyService *CompanyService) CreateCompany(createCompanyCommand *command.CreateCompanyCommand) (interface{}, error) {
// return nil, nil
// }
// 返回企业
func (companyService *CompanyService) GetCompany(getCompanyQuery *query.GetCompanyQuery) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
result, err := creationUserGateway.CompanyGet(allied_creation_user.ReqCompanyGet{
CompanyId: getCompanyQuery.CompanyId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
userResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
InCompanyIds: []interface{}{result.CompanyId},
UserType: domain.UserTypeCompanyAdmin,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var user allied_creation_user.UserDetail
if len(userResult.Users) > 0 {
user = userResult.Users[0]
}
companyDto := &dto.CompanyGetItemDto{}
companyDto.LoadDto(allied_creation_user.CompanyItem(*result), user)
return companyDto, nil
}
func (companyService *CompanyService) AuditCompany(cmd *command.AuditCompanyCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
_, err := creationUserGateway.AuditCompany(allied_creation_user.ReqCompanyAudit{
CompanyId: int(cmd.CompanyId),
Status: cmd.Status,
Remark: cmd.Remark,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
smsServe := sms_serve.NewHttplibHttplibSmsServe()
if cmd.Status == domain.CompanyAuthenticated {
var tmpPhone []rune = []rune(cmd.Phone)
for i := 0; i < 4; i++ {
tmpPhone[i+3] = rune('*')
}
err = smsServe.SendNoticeSms(cmd.Phone, 5007040, map[string]interface{}{"phone": string(tmpPhone)})
} else if cmd.Status == domain.CompanyUnauthenticated {
err = smsServe.SendNoticeSms(cmd.Phone, 5006964, map[string]interface{}{"reason": cmd.Remark})
}
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return struct{}{}, nil
}
func (companyService *CompanyService) EnableCompany(cmd *command.EnableCompanyCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
_, err := creationUserGateway.EnableCompany(allied_creation_user.ReqCompanyEnable{
CompanyId: int(cmd.CompanyId),
Status: cmd.Status,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return struct{}{}, nil
}
// 返回企业列表
func (companyService *CompanyService) ListCompany(listCompanyQuery *query.ListCompanyQuery) (int64, interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
result, err := creationUserGateway.CompanySearch(allied_creation_user.ReqCompanySearch{
Offset: (listCompanyQuery.PageNumber - 1) * listCompanyQuery.PageSize,
Limit: listCompanyQuery.PageSize,
Status: listCompanyQuery.Status,
CompanyName: listCompanyQuery.CompanyName,
})
if err != nil {
return 0, nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
companySet := hashset.New()
for i := range result.Companys {
companySet.Add(result.Companys[i].CompanyId)
}
var users = make([]allied_creation_user.UserDetail, 0)
if companySet.Size() > 0 {
userResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
InCompanyIds: companySet.Values(),
UserType: domain.UserTypeCompanyAdmin,
})
if err != nil {
return 0, nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
users = userResult.Users
}
companyListItemsDto := dto.CompanyListItemsDto{}
companyListItemsDto.LoadDto(result.Companys, users)
return int64(result.Count), companyListItemsDto, nil
}
// 返回自定义菜单列表(匹配有设置的菜单)
// func (companyService *CompanyService) ListCompanyCustomizeMenus(listCompanyCustomizeMenusCommand *command.ListCompanyCustomizeMenusCommand) (interface{}, error) {
// return nil, nil
// }
// 移除企业
// func (companyService *CompanyService) RemoveCompany(removeCompanyCommand *command.RemoveCompanyCommand) (interface{}, error) {
// return nil, nil
// }
// 更新企业
func (companyService *CompanyService) UpdateCompany(updateCompanyCommand *command.UpdateCompanyCommand) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(updateCompanyCommand.Operator)
_, err := creationUserGateway.CompanyUpdate(allied_creation_user.ReqCompanyUpdate{
CompanyId: updateCompanyCommand.Operator.CompanyId,
CompanyName: updateCompanyCommand.CompanyName,
Address: updateCompanyCommand.Address,
SystemName: updateCompanyCommand.SystemName,
Logo: updateCompanyCommand.Logo,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return updateCompanyCommand, nil
}
func NewCompanyService(options map[string]interface{}) *CompanyService {
newCompanyService := &CompanyService{}
return newCompanyService
}
... ...
package command
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
)
type AdminUserAddCommand struct {
//操作人
Operator domain.Operator `json:"-"`
// 用户编号
UsersCode string `json:"userCode" valid:"Required"`
// 用户姓名
UsersName string `json:"userName" valid:"Required"`
// 部门id
DepartmentName string `json:"departmentName" valid:"Required"`
// 手机号码
Phone string `json:"phone" valid:"Required"`
}
//func (companyUserAddCommand *CompanyUserAddCommand) Valid(validation *validation.Validation) {
//
//}
//
//func (companyUserAddCommand *CompanyUserAddCommand) ValidateCommand() error {
// valid := validation.Validation{}
// b, err := valid.Valid(companyUserAddCommand)
// if err != nil {
// return err
// }
// if !b {
// for _, validErr := range valid.Errors {
// return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
// }
// }
// return nil
//}
... ...
package command
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
)
type AdminUserEditCommand struct {
//操作人
Operator domain.Operator `json:"-"`
UserId int64 `json:"userId"`
// 用户编号
UsersCode string `json:"userCode" valid:"Required"`
// 用户姓名
UsersName string `json:"userName" valid:"Required"`
// 部门id
DepartmentName string `json:"departmentName" valid:"Required"`
// 手机号码
Phone string `json:"phone" valid:"Required"`
}
//func (companyUserAddCommand *CompanyUserAddCommand) Valid(validation *validation.Validation) {
//
//}
//
//func (companyUserAddCommand *CompanyUserAddCommand) ValidateCommand() error {
// valid := validation.Validation{}
// b, err := valid.Valid(companyUserAddCommand)
// if err != nil {
// return err
// }
// if !b {
// for _, validErr := range valid.Errors {
// return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
// }
// }
// return nil
//}
... ...
package command
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type EnableAdminUserCommand struct {
Operator domain.Operator `json:"-"`
UserId int64 `cname:"用户id列表" json:"userId" valid:"Required"`
// 启用状态(启用:1 禁用:2 )
EnableStatus int `cname:"启用状态(启用:1 禁用:2 )" json:"enableStatus" valid:"Required"`
}
func (batchEnableCommand *EnableAdminUserCommand) Valid(validation *validation.Validation) {
}
func (batchEnableCommand *EnableAdminUserCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(batchEnableCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(batchEnableCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type EnableUserCommand struct {
Operator domain.Operator `json:"-"`
UserBaseId int64 `cname:"用户id列表" json:"userBaseId" valid:"Required"`
// 启用状态(启用:1 禁用:2 注销:3)
EnableStatus int `cname:"启用状态(启用:1 禁用:2 注销:3)" json:"enableStatus" valid:"Required"`
}
func (batchEnableCommand *EnableUserCommand) Valid(validation *validation.Validation) {
}
func (batchEnableCommand *EnableUserCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(batchEnableCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(batchEnableCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
type ResetPasswordCommand struct {
Operator domain.Operator `json:"-"`
Account string `json:"account"`
}
... ...
package dto
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
"time"
)
type AdminUserDto struct {
// 用户基础数据id
UserId int `json:"userId,omitempty"`
// 用工编号
UserCode string `json:"userCode"`
//姓名
UserName string `json:"userName"`
// 账号
Phone string `json:"phone"`
// 用户关联的组织
DepartmentName string `json:"departmentName"`
// 账号状态 1:正常 2.禁用 3:注销
EnableStatus int `json:"enableStatus,omitempty"`
// 推荐人
Referer string `json:"referer"`
// 创建时间
RegistrationDate string `json:"registrationDate,omitempty"`
// 最后登录时间
LastLogIn string `json:"lastLogIn"`
}
func NewAdminUserDto(v allied_creation_user.UserDetail) AdminUserDto {
item := AdminUserDto{
UserCode: v.UserCode,
UserId: v.UserId,
Phone: v.UserInfo.Phone,
DepartmentName: v.Department.DepartmentName,
EnableStatus: v.EnableStatus,
UserName: v.UserInfo.UserName,
RegistrationDate: v.CreatedAt.Format("2006-01-02"),
LastLogIn: "",
}
if v.Favorite.LastLogInAt > 0 {
item.LastLogIn = time.Unix(v.Favorite.LastLogInAt, 0).Format("2006-01-02 15:04:05")
}
return item
}
... ...
package dto
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
"strings"
)
type UserBaseDto struct {
// 用户基础数据id
UserBaseId int `json:"userBaseId,omitempty"`
//姓名
UserName string `json:"userName"`
// 账号
Account string `json:"account"`
// 用户关联的组织
Organizations string `json:"organizations"`
// 账号状态 1:正常 2.禁用 3:注销
Status int `json:"status,omitempty"`
// 推荐人
Referer string `json:"referer"`
// 创建时间
RegistrationDate string `json:"registrationDate,omitempty"`
// 最后登录时间
LastLogIn string `json:"lastLogIn"`
}
func (dto *UserBaseDto) LoadDto(detail allied_creation_user.UserBaseDetail) {
dto.UserBaseId = detail.UserBaseId
dto.UserName = detail.UserInfo.UserName
dto.Account = detail.UserInfo.Phone
dto.Status = detail.Status
dto.Referer = detail.Referer
dto.RegistrationDate = detail.RegistrationDate
dto.LastLogIn = detail.LastLogIn
var organizations []string
for i := range detail.UserOrg {
if len(detail.UserOrg[i].OrgName) == 0 {
continue
}
organizations = append(organizations, detail.UserOrg[i].OrgName)
}
dto.Organizations = strings.Join(organizations, ",")
}
... ...
package query
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListAdminUserQuery struct {
Operator domain.Operator `json:"-"`
// 查询偏离量
PageNumber int `cname:"查询偏离量" json:"pageNumber"`
// 查询限制
PageSize int `cname:"查询限制" json:"pageSize"`
// 用户姓名
UserName string `cname:"用户姓名" json:"userName,omitempty"`
// 所属组织
DepartmentName string `cname:"所属部门" json:"departmentName,omitempty"`
}
func (listUserQuery *ListAdminUserQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listUserQuery *ListAdminUserQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listUserQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listUserQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListUserQuery struct {
Operator domain.Operator `json:"-"`
// 查询偏离量
PageNumber int `cname:"查询偏离量" json:"pageNumber"`
// 查询限制
PageSize int `cname:"查询限制" json:"pageSize"`
// 用户姓名
UserName string `cname:"用户姓名" json:"userName,omitempty"`
// 在用户列表内
//InUserBaseIds []int64 `cname:"用户姓名" json:"inUserBaseIds,omitempty"`
// 所属组织
OrgName string `cname:"所属组织" json:"orgName,omitempty"`
// 关闭查询限制
//DisableLimit bool `cname:"关闭查询限制" json:"disableLimit,omitempty"`
// 获取组织
//FetchOrgBelong bool `cname:"获取组织" json:"fetchOrgBelong,omitempty"`
}
func (listUserQuery *ListUserQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listUserQuery *ListUserQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listUserQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listUserQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
"strconv"
)
// 返回公司用户信息列表
func (usersService *UserService) AdminUserList(companyUserListQuery *query.ListAdminUserQuery) (int64, interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Offset: (companyUserListQuery.PageNumber - 1) * companyUserListQuery.PageSize,
Limit: companyUserListQuery.PageSize,
OrganizationId: 0,
DepartmentId: 0,
UserName: companyUserListQuery.UserName,
DepName: companyUserListQuery.DepartmentName,
Phone: "",
UserType: domain.UserTypeOperationAdmin,
PullRealTime: true,
})
if err != nil {
return 0, nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
//数据转换
cnt := int64(result.Count)
var (
listData = make([]dto.AdminUserDto, 0)
item dto.AdminUserDto
)
for _, v := range result.Users {
item = dto.NewAdminUserDto(v)
listData = append(listData, item)
}
return cnt, listData, nil
}
// 启用禁用用户
func (usersService *UserService) EnableAdminUser(companyUserEnableCommand *command.EnableAdminUserCommand) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
companyUserEnableCommand.Operator)
var userIds []int64 = []int64{companyUserEnableCommand.UserId}
_, err := creationUserGateway.UserBatchEnable(allied_creation_user.ReqBatchEnableUser{
UserIds: userIds,
EnableStatus: companyUserEnableCommand.EnableStatus,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return companyUserEnableCommand, err
}
func (usersService *UserService) GetAdminUser(userId int) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
domain.Operator{})
result, err := creationUserGateway.UserGet(allied_creation_user.ReqGetUser{
UserId: userId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
userInfo := dto.NewAdminUserDto(result.UserDetail)
return userInfo, nil
}
func (usersService *UserService) CreateAdminUser(cmd *command.AdminUserAddCommand) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
cmd.Operator)
userOrg := []int64{}
userRole := []int64{}
initPassword := domain.DefaultPassword
result, err := creationUserGateway.AdminUserCreate(allied_creation_user.ReqCreateUser{
CompanyId: cmd.Operator.CompanyId,
// 用户类型 1:企业内部用户(内部添加) 2:共创用户 1024:企业注册用户(注册添加)
UserType: domain.UserTypeOperationAdmin,
UserCode: cmd.UsersCode,
UserOrg: userOrg,
UserRole: userRole,
// 启用状态(启用:1 禁用:2)
EnableStatus: 1,
UserName: cmd.UsersName,
Phone: cmd.Phone,
Password: initPassword,
DepartmentName: cmd.DepartmentName,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
data := struct {
UserId string `json:"userId"`
command.AdminUserAddCommand
}{
UserId: strconv.Itoa(result.UserId),
AdminUserAddCommand: *cmd,
}
return data, err
}
func (usersService *UserService) UpdateAdminUser(cmd *command.AdminUserEditCommand) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
cmd.Operator)
user, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
Account: cmd.Phone,
})
_, err = creationUserGateway.AdminUserUpdate(allied_creation_user.ReqUpdateUser{
UserId: cmd.UserId,
//CooperationCompany: cmd.CooperationCompany,
//CooperationDeadline: time.Unix(cmd.CooperationDeadline/1000, 0),
Email: user.UserInfo.Email,
//EnableStatus: user.,
UserCode: cmd.UsersCode,
UserName: cmd.UsersName,
Avatar: user.UserInfo.Avatar,
//OrgId: cmd.Operator.OrgId,
Phone: cmd.Phone,
DepartmentName: cmd.DepartmentName,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return cmd, err
}
func (svr *UserService) GetAdminUserInfo(operator domain.Operator) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
operator)
resultUser, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
Account: operator.Phone,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
users, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
UserBaseId: int64(resultUser.UserBaseID),
UserType: domain.UserTypeOperationAdmin,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if len(users.Users) == 0 {
return nil, application.ThrowError(application.BUSINESS_ERROR, "用户不存在")
}
var user = map[string]interface{}{
"userId": users.Users[0].UserId,
"userInfo": map[string]interface{}{
"userName": resultUser.UserInfo.UserName,
"userPhone": resultUser.UserInfo.Phone,
"userAvatar": resultUser.UserInfo.Avatar,
"email": resultUser.UserInfo.Email,
},
"department": struct{}{},
"company": map[string]interface{}{},
//"im": resultUser.Im,
"org": struct{}{},
}
return user, nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
)
type UserService struct {
}
// 创建菜单服务
func (userService *UserService) SearchUser(cmd *query.ListUserQuery) (int64, interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(cmd.Operator)
result, err := creationUserGateway.UserBaseSearch(allied_creation_user.ReqUserBaseSearch{
Offset: (cmd.PageNumber - 1) * cmd.PageSize,
Limit: cmd.PageSize,
UserName: cmd.UserName,
OrgName: cmd.OrgName,
FetchOrgBelong: true,
})
if err != nil {
return 0, nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var users = make([]dto.UserBaseDto, 0)
for i := range result.Users {
item := &dto.UserBaseDto{}
item.LoadDto(result.Users[i])
users = append(users, *item)
}
return result.Count, users, nil
}
func (userService *UserService) EnableUser(cmd *command.EnableUserCommand) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(cmd.Operator)
_, err := creationUserGateway.EnableUserBase(allied_creation_user.ReqEnableUserBase{
UserBaseIds: []int64{cmd.UserBaseId},
EnableStatus: cmd.EnableStatus,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return struct{}{}, nil
}
func (userService *UserService) ResetPassword(cmd *command.ResetPasswordCommand) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(cmd.Operator)
_, err := creationUserGateway.AuthResetPassword(allied_creation_user.ReqAuthResetPassword{
Phone: cmd.Account,
Password: domain.DefaultPassword, //TL123456!
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return struct{}{}, nil
}
func NewUserService(options map[string]interface{}) *UserService {
newUserService := &UserService{}
return newUserService
}
... ...
... ... @@ -26,7 +26,7 @@ func (menuService *MenuService) MenuFavorite(menuFavoriteCommand *command.MenuFa
}
// 返回菜单列表
func (menuService *MenuService) MenuList(menuListQuery *query.MenuListQuery) (interface{}, error) {
func (menuService *MenuService) CustomizeMenus(menuListQuery *query.MenuListQuery) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
menuListQuery.Operator,
)
... ... @@ -59,6 +59,21 @@ func (menuService *MenuService) MenuUpdate(menuUpdateCommand *command.MenuUpdate
return menuUpdateCommand, nil
}
func (menuService *MenuService) MenuSearch(menuListQuery *query.MenuListQuery) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
menuListQuery.Operator,
)
result, err := creationUserGateway.MenusSearch(allied_creation_user.ReqMenusSearch{
MenuCategory: menuListQuery.MenuCategory,
})
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"menus": result.Menus,
}, nil
}
func NewMenuService(options map[string]interface{}) *MenuService {
newMenuService := &MenuService{}
return newMenuService
... ...
package command
type ImportCostDataCommand struct {
Types int `json:"types"`
}
... ...
... ... @@ -14,6 +14,10 @@ type ImportDataCommand struct {
FileExt string `json:"-"`
// 业务编码
Code string `form:"code"`
// 条件 - 成本结构会增加条件
Where string `form:"where"`
// 文件名
FileName string `json:"fileName"`
}
func (importDataCommand *ImportDataCommand) Valid(validation *validation.Validation) {
... ...
package query
type ExcelDataFieldsQuery struct {
//操作人
// 业务编码
Code string `form:"code"`
}
... ...
package query
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
type ManufactureEmployeeProductiveQuery struct {
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 姓名
UserName string `cname:"姓名" json:"userName"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType string `cname:"员工类型 1:固定 2:派遣 3.临时" json:"employeeType"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
//操作人
Operator domain.Operator `json:"-"`
SelectedField []string `json:"selectedField"`
}
... ...
package query
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_manufacture"
)
type ManufactureExportEmployeeAttendanceStaticsQuery struct {
*allied_creation_manufacture.SearchEmployeeAttendanceStaticsRequest
//操作人
Operator domain.Operator `json:"-"`
SelectedField []string `json:"selectedField"`
}
... ...
package query
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_manufacture"
)
type ManufactureExportWorkshopAttendanceStaticsQuery struct {
*allied_creation_manufacture.SearchWorkshopWorkTimeStaticsRequest
//操作人
Operator domain.Operator `json:"-"`
SelectedField []string `json:"selectedField"`
}
... ...
package query
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_manufacture"
)
type ManufactureSecondLevelRecordQuery struct {
*allied_creation_manufacture.SearchSecondLevelRecordRequest
//操作人
Operator domain.Operator `json:"-"`
SelectedField []string `json:"selectedField"`
}
... ...
package query
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
type ManufactureWorkshopProductiveQuery struct {
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 品名
PlanProductName string `cname:"品名" json:"planProductName,omitempty"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
//操作人
Operator domain.Operator `json:"-"`
SelectedField []string `json:"selectedField"`
}
... ...
package query
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
type SearchProductQuery struct {
// 产品名称
ProductName string `json:"productName,omitempty"`
// 产品类别
ProductCategory string `cname:"产品类别" json:"productCategory"`
//操作人
Operator domain.Operator `json:"-"`
SelectedField []string `json:"selectedField"`
}
... ...
... ... @@ -2,6 +2,7 @@ package service
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_manufacture"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/web/excelData/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
... ... @@ -51,3 +52,88 @@ func (srv ExcelDataService) ExportCooperationUser(companyUserListQuery *query.Co
}
return ExportCooperationUserData{SourceData: result.Users, SelectedField: companyUserListQuery.SelectedField}, nil
}
// ExportCooperationUser 导出共创用户信息列表
func (srv ExcelDataService) ExportProducts(cmd *query.SearchProductQuery) (ExportProductsData, error) {
creationUserGateway := allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(cmd.Operator)
result, err := creationUserGateway.SearchProduct(allied_creation_manufacture.SearchProductRequest{
ProductName: cmd.ProductName,
ProductCategory: cmd.ProductCategory,
})
if err != nil {
return ExportProductsData{}, fmt.Errorf("获取企业用户数据失败:%w", err)
}
return ExportProductsData{SourceData: result.Grid.List, SelectedField: cmd.SelectedField}, nil
}
// ExportEmployeeProductive 导出员工产能
func (srv ExcelDataService) ExportEmployeeProductive(cmd *query.ManufactureEmployeeProductiveQuery) (ExportEmployeeProductiveData, error) {
creationUserGateway := allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(cmd.Operator)
result, err := creationUserGateway.SearchEmployeeProductive(allied_creation_manufacture.SearchEmployeeProductiveRequest{
WorkshopName: cmd.WorkshopName,
LineName: cmd.LineName,
SectionName: cmd.SectionName,
UserName: cmd.UserName,
EmployeeType: cmd.EmployeeType,
BeginTime: cmd.BeginTime,
EndTime: cmd.EndTime,
})
if err != nil {
return ExportEmployeeProductiveData{}, fmt.Errorf("获取员工产能数据失败:%w", err)
}
return ExportEmployeeProductiveData{SourceData: result.Grid.List, SelectedField: cmd.SelectedField}, nil
}
// ExportEmployeeProductive 导出车间产能
func (srv ExcelDataService) ExportWorkshopProductive(cmd *query.ManufactureWorkshopProductiveQuery) (ExportWorkshopProductiveData, error) {
creationUserGateway := allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(cmd.Operator)
result, err := creationUserGateway.SearchWorkshopProductive(allied_creation_manufacture.SearchWorkshopProductiveRequest{
SectionName: cmd.SectionName,
PlanProductName: cmd.PlanProductName,
BeginTime: cmd.BeginTime,
EndTime: cmd.EndTime,
})
if err != nil {
return ExportWorkshopProductiveData{}, fmt.Errorf("获取员工产能数据失败:%w", err)
}
return ExportWorkshopProductiveData{SourceData: result.Grid.List, SelectedField: cmd.SelectedField}, nil
}
// ExportSecondLevelRecord 二级废品
func (srv ExcelDataService) ExportSecondLevelRecord(cmd *query.ManufactureSecondLevelRecordQuery) (ExportSecondLevelData, error) {
creationUserGateway := allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(cmd.Operator)
result, err := creationUserGateway.SearchSecondLevelRecord(allied_creation_manufacture.SearchSecondLevelRecordRequest{
WorkshopName: cmd.WorkshopName,
BatchNumber: cmd.BatchNumber,
UserName: cmd.UserName,
LineName: cmd.LineName,
SectionName: cmd.SectionName,
EmployeeType: cmd.EmployeeType,
BeginTime: cmd.BeginTime,
EndTime: cmd.EndTime,
})
if err != nil {
return ExportSecondLevelData{}, fmt.Errorf("获取二级废品数据失败:%w", err)
}
return ExportSecondLevelData{SourceData: result.Grid.List, SelectedField: cmd.SelectedField}, nil
}
// ExportEmployeeAttendanceStatics 导出员工工时
func (srv ExcelDataService) ExportEmployeeAttendanceStatics(cmd *query.ManufactureExportEmployeeAttendanceStaticsQuery) (ExportEmployeeAttendanceStaticsData, error) {
creationUserGateway := allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(cmd.Operator)
result, err := creationUserGateway.SearchEmployeeAttendanceStatics(*cmd.SearchEmployeeAttendanceStaticsRequest)
if err != nil {
return ExportEmployeeAttendanceStaticsData{}, fmt.Errorf("获取员工工时数据失败:%w", err)
}
return ExportEmployeeAttendanceStaticsData{SourceData: result.Grid.List, SelectedField: cmd.SelectedField}, nil
}
// ExportWorkshopAttendanceStatics 导出车间工时
func (srv ExcelDataService) ExportWorkshopAttendanceStatics(cmd *query.ManufactureExportWorkshopAttendanceStaticsQuery) (ExportWorkshopAttendanceStaticsData, error) {
creationUserGateway := allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(cmd.Operator)
result, err := creationUserGateway.SearchWorkshopWorkTimeStatics(*cmd.SearchWorkshopWorkTimeStaticsRequest)
if err != nil {
return ExportWorkshopAttendanceStaticsData{}, fmt.Errorf("获取车间工时数据失败:%w", err)
}
return ExportWorkshopAttendanceStaticsData{SourceData: result.Grid.List, SelectedField: cmd.SelectedField}, nil
}
... ...
package service
import (
"bytes"
"encoding/json"
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/util/converter"
"strings"
"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"
"strings"
)
type ExcelDataService struct {
... ... @@ -90,6 +97,8 @@ func (srv ExcelDataService) ImportCompanyUser(importDataCommand *command.ImportD
{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)
... ... @@ -111,6 +120,8 @@ func (srv ExcelDataService) ImportCompanyUser(importDataCommand *command.ImportD
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)
}
... ... @@ -161,6 +172,247 @@ func (srv ExcelDataService) ImportOrganization(importDataCommand *command.Import
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: "image1", CnName: "图片1"},
{EnName: "image2", CnName: "图片2"},
{EnName: "image3", CnName: "图片3"},
{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 {
//图片1
_, mBytes1, err := f.GetPicture(f.GetSheetName(index), "E"+fmt.Sprintf("%v", excelImport.RowBegin+key+1))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "读取图片失败")
}
var ossFile []string
if mBytes1 != nil {
ossFile1, err := oss.UploadOss(mBytes1)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传图片失败")
}
ossFile = append(ossFile,ossFile1)
}
//图片2
_,mBytes2,err := f.GetPicture(f.GetSheetName(index), "F"+fmt.Sprintf("%v", excelImport.RowBegin+key+1))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "读取图片失败")
}
if mBytes2 != nil {
ossFile2, err := oss.UploadOss(mBytes2)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传图片失败")
}
ossFile = append(ossFile,ossFile2)
}
//图片3
_,mBytes3,err := f.GetPicture(f.GetSheetName(index), "G"+fmt.Sprintf("%v", excelImport.RowBegin+key+1))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "读取图片失败")
}
if mBytes3 != nil {
ossFile3, err := oss.UploadOss(mBytes3)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "上传图片失败")
}
ossFile = append(ossFile,ossFile3)
}
//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 := domain.GetTargetPeriod(v["targetPeriod"])
item := &domain.CostManagemant{
ProjectCode: strings.TrimSpace(v["projectCode"]),
ProjectName: importDataCommand.FileName,
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 len(ossFile) >0 {
item.Urls = 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())
}
if result.Code != 0 {
return map[string]interface{}{
"successCount": 0,
"fail": map[string]interface{}{
"header": map[string]string{
"failReason": "错误详情",
"projectCode": "项目编码",
"itemName": "细项名称",
},
"body": []map[string]interface{}{
{"failReason":result.Msg,"projectCode":"","itemName":""},
},
},
"successData":nil,
}, nil
} else {
return result.Data, nil
}
}
// 导入结果
func (srv ExcelDataService) importResultWithHeader(headers []excel.DataField, failRows []interface{}, totalRow int) interface{} {
var result = map[string]interface{}{
... ... @@ -199,11 +451,14 @@ func (srv ExcelDataService) fieldValueAllEmpty(param map[string]string) bool {
// 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.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/test/20220318/object/1647587204_B5azRmr2TB73jRKWsnFyDe4yxXJWnrDT.xlsx",
}
var url string
var ok bool
... ... @@ -215,9 +470,9 @@ func (srv ExcelDataService) FileImportTemplate(importDataCommand *command.Import
}, nil
}
func (srv ExcelDataService) GetExcelDataFields(code string) (interface{}, error) {
func (srv ExcelDataService) GetExcelDataFields(param *query.ExcelDataFieldsQuery) (interface{}, error) {
dataFileds := []DataFieldOptions{}
switch code {
switch param.Code {
case domain.ExportCompanyUser:
dataFileds = (ExportCompanyUserData{}).AllFields()
case domain.ExportCooperationUser:
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/utils/excel"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"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"
)
... ... @@ -175,3 +178,461 @@ func (data ExportCooperationUserData) DataListLen() int {
func (data ExportCooperationUserData) TableTitle() []string {
return nil
}
//ExportProductsData 导出产品数据
type ExportProductsData struct {
SourceData []allied_creation_manufacture.SearchProductItem
SelectedField []string
}
var _ excel.ExcelMaker = (*ExportProductsData)(nil)
func (data ExportProductsData) AllFields() []DataFieldOptions {
return []DataFieldOptions{
{EnName: "productCode", CnName: "产品编号"},
{EnName: "productName", CnName: "*品名"},
{EnName: "unit", CnName: "*规格"},
{EnName: "productCategory", CnName: "*类别"},
{EnName: "unitWeight", CnName: "投入单份重量"},
}
}
func (data ExportProductsData) 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 ExportProductsData) CellValue(index int, enName string) (value interface{}) {
if index > data.DataListLen() {
return ""
}
switch enName {
case "productCode":
return data.SourceData[index].ProductCode
case "productName":
return data.SourceData[index].ProductName
case "unit":
return data.SourceData[index].Unit
case "productCategory":
return data.SourceData[index].ProductCategory
case "unitWeight":
return fmt.Sprintf("%v", data.SourceData[index].UnitWeight)
}
return nil
}
func (data ExportProductsData) DataListLen() int {
return len(data.SourceData)
}
func (data ExportProductsData) TableTitle() []string {
return nil
}
//ExportEmployeeProductiveData 导出员工产能数据
type ExportEmployeeProductiveData struct {
SourceData []allied_creation_manufacture.EmployeeProductiveItem
SelectedField []string
}
var _ excel.ExcelMaker = (*ExportEmployeeProductiveData)(nil)
func (data ExportEmployeeProductiveData) AllFields() []DataFieldOptions {
return []DataFieldOptions{
{EnName: "createdAt", CnName: "日期"},
{EnName: "workshopName", CnName: "车间名称"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "workOn", CnName: "班别"},
{EnName: "userName", CnName: "姓名"},
{EnName: "employeeType", CnName: "员工类型"},
{EnName: "participateType", CnName: "类别"},
{EnName: "planProductName", CnName: "品名"},
{EnName: "productWeigh", CnName: "产能"},
{EnName: "secondLevelWeigh", CnName: "二级品"},
{EnName: "qualificationRate", CnName: "合格率"},
{EnName: "orgName", CnName: "组织机构"},
}
}
func (data ExportEmployeeProductiveData) 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 ExportEmployeeProductiveData) CellValue(index int, enName string) (value interface{}) {
if index > data.DataListLen() {
return ""
}
switch enName {
case "createdAt":
return data.SourceData[index].CreatedAt
case "workshopName":
return data.SourceData[index].WorkshopName
case "lineName":
return data.SourceData[index].LineName
case "sectionName":
return data.SourceData[index].SectionName
case "workOn":
return data.SourceData[index].WorkOn
case "userName":
return data.SourceData[index].ProductWorker.UserName
case "employeeType":
return domain.EmployeeTypeDescription(data.SourceData[index].ProductWorker.EmployeeType)
case "participateType":
return domain.ParticipateTypeDescription(data.SourceData[index].ParticipateType)
case "planProductName":
return data.SourceData[index].PlanProductName
case "productWeigh":
return fmt.Sprintf("%vKg", data.SourceData[index].ProductWeigh)
case "secondLevelWeigh":
return fmt.Sprintf("%vKg", data.SourceData[index].SecondLevelWeigh)
case "qualificationRate":
return fmt.Sprintf("%v%%", data.SourceData[index].QualificationRate)
case "orgName":
return data.SourceData[index].OrgName
}
return nil
}
func (data ExportEmployeeProductiveData) DataListLen() int {
return len(data.SourceData)
}
func (data ExportEmployeeProductiveData) TableTitle() []string {
return nil
}
//ExportWorkshopProductiveData 导出员工产能数据
type ExportWorkshopProductiveData struct {
SourceData []allied_creation_manufacture.WorkshopProductiveItem
SelectedField []string
}
var _ excel.ExcelMaker = (*ExportWorkshopProductiveData)(nil)
func (data ExportWorkshopProductiveData) AllFields() []DataFieldOptions {
return []DataFieldOptions{
{EnName: "createdAt", CnName: "日期"},
{EnName: "batchNumber", CnName: "批次号"},
{EnName: "workshopName", CnName: "车间名称"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "planProductName", CnName: "品名"},
{EnName: "devotedProductWeigh", CnName: "投入量"},
{EnName: "productWeigh", CnName: "产出量"},
{EnName: "secondLevelWeigh", CnName: "二级品"},
{EnName: "qualificationRate", CnName: "出品率"},
{EnName: "orgName", CnName: "组织机构"},
}
}
func (data ExportWorkshopProductiveData) 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 ExportWorkshopProductiveData) CellValue(index int, enName string) (value interface{}) {
if index > data.DataListLen() {
return ""
}
switch enName {
case "createdAt":
return data.SourceData[index].CreatedAt
case "batchNumber":
return data.SourceData[index].BatchNumber
case "workshopName":
return data.SourceData[index].WorkshopName
case "lineName":
return data.SourceData[index].LineName
case "sectionName":
return data.SourceData[index].SectionName
case "userName":
return data.SourceData[index].ProductWorker.UserName
case "planProductName":
return data.SourceData[index].PlanProductName
case "devotedProductWeigh":
return fmt.Sprintf("%vKg", data.SourceData[index].DevotedProductWeigh)
case "productWeigh":
return fmt.Sprintf("%vKg", data.SourceData[index].ProductWeigh)
case "secondLevelWeigh":
return fmt.Sprintf("%vKg", data.SourceData[index].SecondLevelWeigh)
case "qualificationRate":
return fmt.Sprintf("%v%%", data.SourceData[index].QualificationRate)
case "orgName":
return data.SourceData[index].OrgName
}
return nil
}
func (data ExportWorkshopProductiveData) DataListLen() int {
return len(data.SourceData)
}
func (data ExportWorkshopProductiveData) TableTitle() []string {
return nil
}
//ExportEmployeeAttendanceStaticsData 导出员工产能数据
type ExportEmployeeAttendanceStaticsData struct {
SourceData []allied_creation_manufacture.SearchEmployeeAttendanceStaticsItem
SelectedField []string
}
var _ excel.ExcelMaker = (*ExportEmployeeAttendanceStaticsData)(nil)
func (data ExportEmployeeAttendanceStaticsData) AllFields() []DataFieldOptions {
return []DataFieldOptions{
{EnName: "signDate", CnName: "日期"},
{EnName: "workshopName", CnName: "车间名称"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "userName", CnName: "姓名"},
{EnName: "employeeTypeDescription", CnName: "员工类型"},
{EnName: "attendanceTypeDescription", CnName: "类别"},
{EnName: "workTime", CnName: "工时"},
{EnName: "attendanceStatusDescription", CnName: "状态"},
{EnName: "orgName", CnName: "组织机构"},
}
}
func (data ExportEmployeeAttendanceStaticsData) 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 ExportEmployeeAttendanceStaticsData) CellValue(index int, enName string) (value interface{}) {
if index > data.DataListLen() {
return ""
}
switch enName {
case "signDate":
return data.SourceData[index].SignDate
case "workshopName":
return data.SourceData[index].WorkshopName
case "lineName":
return data.SourceData[index].LineName
case "sectionName":
return data.SourceData[index].SectionName
case "userName":
return data.SourceData[index].ProductWorker.UserName
case "employeeTypeDescription":
return data.SourceData[index].EmployeeTypeDescription
case "attendanceTypeDescription":
return data.SourceData[index].AttendanceTypeDescription
case "workTime":
return fmt.Sprintf("%vh", data.SourceData[index].WorkTime)
case "attendanceStatusDescription":
return data.SourceData[index].AttendanceStatusDescription
case "orgName":
return data.SourceData[index].OrgName
}
return nil
}
func (data ExportEmployeeAttendanceStaticsData) DataListLen() int {
return len(data.SourceData)
}
func (data ExportEmployeeAttendanceStaticsData) TableTitle() []string {
return nil
}
//ExportWorkshopAttendanceStaticsData 导出车间工时统计
type ExportWorkshopAttendanceStaticsData struct {
SourceData []allied_creation_manufacture.SearchWorkshopWorkTimeStaticsItem
SelectedField []string
}
var _ excel.ExcelMaker = (*ExportWorkshopAttendanceStaticsData)(nil)
func (data ExportWorkshopAttendanceStaticsData) AllFields() []DataFieldOptions {
return []DataFieldOptions{
{EnName: "recordDate", CnName: "日期"},
{EnName: "workshopName", CnName: "车间名称"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "eftWorkTime", CnName: "固定工时"},
{EnName: "edWorkTime", CnName: "临时工时"},
{EnName: "epWorkTime", CnName: "派遣工时"},
{EnName: "orgName", CnName: "组织机构"},
}
}
func (data ExportWorkshopAttendanceStaticsData) 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 ExportWorkshopAttendanceStaticsData) CellValue(index int, enName string) (value interface{}) {
if index > data.DataListLen() {
return ""
}
switch enName {
case "recordDate":
return data.SourceData[index].RecordDate
case "workshopName":
return data.SourceData[index].WorkshopName
case "lineName":
return data.SourceData[index].LineName
case "sectionName":
return data.SourceData[index].SectionName
case "eftWorkTime":
return data.SourceData[index].EftWorkTime
case "edWorkTime":
return data.SourceData[index].EdWorkTime
case "epWorkTime":
return data.SourceData[index].EptWorkTime
case "orgName":
return data.SourceData[index].OrgName
}
return nil
}
func (data ExportWorkshopAttendanceStaticsData) DataListLen() int {
return len(data.SourceData)
}
func (data ExportWorkshopAttendanceStaticsData) TableTitle() []string {
return nil
}
//ExportWorkshopProductiveData 导出员工产能数据
type ExportSecondLevelData struct {
SourceData []allied_creation_manufacture.SecondLevelRecordItem
SelectedField []string
}
var _ excel.ExcelMaker = (*ExportSecondLevelData)(nil)
func (data ExportSecondLevelData) AllFields() []DataFieldOptions {
return []DataFieldOptions{
{EnName: "workshopName", CnName: "车间名称"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "workOn", CnName: "班别"},
{EnName: "userName", CnName: "姓名"},
{EnName: "employeeType", CnName: "员工类型"},
{EnName: "batchNumber", CnName: "批次号"},
{EnName: "planProductName", CnName: "生产品名"},
{EnName: "weightBefore", CnName: "二级品"},
{EnName: "createdAt", CnName: "提报时间"},
{EnName: "orgName", CnName: "组织机构"},
}
}
func (data ExportSecondLevelData) 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 ExportSecondLevelData) CellValue(index int, enName string) (value interface{}) {
if index > data.DataListLen() {
return ""
}
switch enName {
case "workshopName":
return data.SourceData[index].WorkshopName
case "lineName":
return data.SourceData[index].LineName
case "sectionName":
return data.SourceData[index].SectionName
case "userName":
return data.SourceData[index].ProductWorker.UserName
case "workOn":
return domain.WorkOnDescription(data.SourceData[index].WorkOn)
case "employeeType":
return domain.EmployeeTypeDescription(data.SourceData[index].ProductWorker.EmployeeType)
case "batchNumber":
return data.SourceData[index].BatchNumber
case "planProductName":
return data.SourceData[index].PlanProductName
case "weightBefore":
return fmt.Sprintf("%vKg", data.SourceData[index].WeightBefore)
case "createdAt":
return data.SourceData[index].CreatedAt
case "orgName":
return data.SourceData[index].OrgName
}
return nil
}
func (data ExportSecondLevelData) DataListLen() int {
return len(data.SourceData)
}
func (data ExportSecondLevelData) TableTitle() []string {
return nil
}
... ...
... ... @@ -30,6 +30,10 @@ type CompanyUserAddCommand struct {
UserRole []Role `json:"userRole,omitempty"`
// 头像
Avatar string `json:"avatar" valid:"Required"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType int `cname:"员工类型" json:"employeeType" valid:"Required"`
// IC卡号
IcCardNumber string `cname:"IC卡号" json:"icCardNumber,omitempty"`
}
func (companyUserAddCommand *CompanyUserAddCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -25,6 +25,10 @@ type CompanyUserUpdateCommand struct {
Phone string `json:"phone,omitempty"`
// 邮箱
Email string `json:"email,omitempty"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType int `cname:"员工类型" json:"employeeType" valid:"Required"`
// IC卡号
IcCardNumber string `cname:"IC卡号" json:"icCardNumber,omitempty"`
// 关联的组织机构
UserOrg []Org `json:"userOrg,omitempty"`
// 关联的组织结构
... ...
... ... @@ -9,24 +9,32 @@ type CompanyUserItem struct {
UserId string `json:"userId"`
UserName string `json:"userName"`
UserType int `json:"userType"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType int `json:"employeeType"`
// IC卡号
IcCardNumber string `json:"icCardNumber"`
AuthFlag bool `json:"authFlag"` // 1:可操作(编辑,修改等)
}
//CompanyUserInfo 用户数据详情
type CompanyUserInfo struct {
Email string `json:"email"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
EnableStatus int `json:"enableStatus"`
UsersCode string `json:"userCode"`
UsersID string `json:"userId"`
UsersName string `json:"userName"`
OrgID string `json:"orgId"`
OrgName string `json:"orgName"`
DepartmentID string `json:"departmentId"`
DepartmentName string `json:"departmentName"`
UsersOrg []UserOrg `json:"userOrg"`
UsersRole []UserRole `json:"userRole"`
Email string `json:"email"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
EnableStatus int `json:"enableStatus"`
UsersCode string `json:"userCode"`
UsersID string `json:"userId"`
UsersName string `json:"userName"`
OrgID string `json:"orgId"`
OrgName string `json:"orgName"`
DepartmentID string `json:"departmentId"`
DepartmentName string `json:"departmentName"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType int `json:"employeeType"`
// IC卡号
IcCardNumber string `json:"icCardNumber"`
UsersOrg []UserOrg `json:"userOrg"`
UsersRole []UserRole `json:"userRole"`
}
type UserOrg struct {
... ...
... ... @@ -93,6 +93,8 @@ func (usersService *UsersService) CompanyUserGet(companyUserGetQuery *query.Comp
DepartmentName: resultUser.Department.DepartmentName,
UsersOrg: usersOrg,
UsersRole: userRole,
EmployeeType: resultUser.UserInfo.EmployeeType,
IcCardNumber: resultUser.UserInfo.IcCardNumber,
}
datas := map[string]interface{}{
... ... @@ -141,6 +143,8 @@ func (usersService *UsersService) CompanyUserAdd(companyUserAddCommand *command.
Phone: companyUserAddCommand.Phone,
Avatar: companyUserAddCommand.Avatar,
Email: companyUserAddCommand.Email,
IcCardNumber: companyUserAddCommand.IcCardNumber,
EmployeeType: companyUserAddCommand.EmployeeType,
Password: initPassword,
})
if err != nil {
... ... @@ -181,7 +185,7 @@ func (usersService *UsersService) CompanyUserEnable(companyUserEnableCommand *co
func (usersService *UsersService) CompanyUserList(companyUserListQuery *query.CompanyUserListQuery) (int64, interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Offset: (companyUserListQuery.PageNumber - 1) * companyUserListQuery.PageSize,
Offset: (companyUserListQuery.PageNumber - 1) * companyUserListQuery.PageSize,
Limit: companyUserListQuery.PageSize,
CompanyId: companyUserListQuery.Operator.CompanyId,
OrganizationId: 0,
... ... @@ -214,6 +218,8 @@ func (usersService *UsersService) CompanyUserList(companyUserListQuery *query.Co
UserId: strconv.Itoa(v.UserId),
UserName: v.UserInfo.UserName,
UserType: v.UserType,
EmployeeType: v.UserInfo.EmployeeType,
IcCardNumber: v.UserInfo.IcCardNumber,
}
if v.Org.OrgId == int(companyUserListQuery.Operator.OrgId) {
item.AuthFlag = true
... ... @@ -280,6 +286,8 @@ func (usersService *UsersService) CompanyUserUpdate(companyUserUpdateCommand *co
Phone: companyUserUpdateCommand.Phone,
Avatar: companyUserUpdateCommand.Avatar,
Email: companyUserUpdateCommand.Email,
EmployeeType: companyUserUpdateCommand.EmployeeType,
IcCardNumber: companyUserUpdateCommand.IcCardNumber,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
... ...
... ... @@ -27,6 +27,9 @@ var ALLIED_CREATION_USER_HOST = "http://localhost:8081" //"http://allied-creatio
//天联共创业务模块
var ALLIED_CREATION_COOPERATION_HOST = "http://localhost:8082" // "http://allied-creation-cooperation-dev.fjmaimaimai.com"
// 天联共创 生产制造模块
var ALLIED_CREATION_MANUFACTURE_HOST = "http://localhost:8083"
// 版本更新模块
var SUPLUS_ADMIN_BASE_HOST = "http://suplus-admin-base-dev.fjmaimaimai.com"
... ... @@ -41,6 +44,10 @@ var SMSCODE_ALL_POWER = "999512"
var EnableBlockChain = true
// 天联共创 成本结构化
var COST_STRUCTURED = "http://cost-structured-dev.fjmaimaimai.com"
//var COST_STRUCTURED = "http://localhost:8085"
func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
... ... @@ -63,6 +70,9 @@ func init() {
if os.Getenv("ALLIED_CREATION_COOPERATION_HOST") != "" {
ALLIED_CREATION_COOPERATION_HOST = os.Getenv("ALLIED_CREATION_COOPERATION_HOST")
}
if os.Getenv("ALLIED_CREATION_MANUFACTURE_HOST") != "" {
ALLIED_CREATION_MANUFACTURE_HOST = os.Getenv("ALLIED_CREATION_MANUFACTURE_HOST")
}
if os.Getenv("SMS_SERVE_HOST") != "" {
SMS_SERVE_HOST = os.Getenv("SMS_SERVE_HOST")
}
... ... @@ -75,4 +85,7 @@ func init() {
if os.Getenv("SUPLUS_SALE_APP") != "" {
SUPLUS_SALE_APP = os.Getenv("SUPLUS_SALE_APP")
}
if os.Getenv("COST_STRUCTURED") != "" {
COST_STRUCTURED = os.Getenv("COST_STRUCTURED")
}
}
... ...
package constant
import (
"os"
"strconv"
)
var (
// 生产制造 - 称重系统 - 默认公司
MANUFACTURE_WEIGH_DEFAULT_COMPANYID = 1
// 生产制造 - 称重系统 - 默认组织
MANUFACTURE_WEIGH_DEFAULT_ORGID = 1
)
func init() {
if os.Getenv("MANUFACTURE_WEIGH_DEFAULT_COMPANYID") != "" {
MANUFACTURE_WEIGH_DEFAULT_COMPANYID, _ = strconv.Atoi(os.Getenv("MANUFACTURE_WEIGH_DEFAULT_COMPANYID"))
}
if os.Getenv("MANUFACTURE_WEIGH_DEFAULT_ORGID") != "" {
MANUFACTURE_WEIGH_DEFAULT_ORGID, _ = strconv.Atoi(os.Getenv("MANUFACTURE_WEIGH_DEFAULT_ORGID"))
}
}
... ...
package constant
const OssAccessKey = "LTAI4Fz1LUBW2fXp6QWaJHRS"
const OssSecret = "aLZXwK8pgrs10Ws03qcN7NsrSXFVsg"
var OssBucket = "timeless-world"
const OssDomain = "http://timeless-world.oss-cn-shenzhen.aliyuncs.com"
\ No newline at end of file
... ...
... ... @@ -2,11 +2,18 @@ package constant
import "os"
var POSTGRESQL_DB_NAME = "terms"
//var POSTGRESQL_DB_NAME = "terms"
//var POSTGRESQL_USER = "postgres"
//var POSTGRESQL_PASSWORD = "123456"
//var POSTGRESQL_HOST = "127.0.0.1"
//var POSTGRESQL_PORT = "5432"
//var DISABLE_CREATE_TABLE = false
//var DISABLE_SQL_GENERATE_PRINT = false
var POSTGRESQL_DB_NAME = "allied_creation_dev"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "123456"
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "5432"
var POSTGRESQL_HOST = "114.55.200.59"
var POSTGRESQL_PORT = "31543"
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
... ...
package domain
// 公司状态状态 1:已注册 2:已通过 3:已拒绝
const (
CompanyRegistered = iota + 1
CompanyAuthenticated
CompanyUnauthenticated
)
//公司
type CompanyData struct {
CompanyID int `json:"companyId"`
... ... @@ -12,3 +19,10 @@ type Company struct {
Logo string `json:"logo"`
CompanyName string `json:"companyName"`
}
// 营业执照所在地
type BusinessLicenseAddress struct {
Province string `json:"province"`
City string `json:"city"`
Address string `json:"address"`
}
... ...
package domain
import "strings"
type BatchCreateCostManagemant struct {
UserId int64 `cname:"操作人id" json:"UserId" valid:"Required"`
// 公司id
CompanyId int64 `cname:"公司id" json:"companyId" valid:"Required"`
// 项目id
ProjectId int64 `cname:"项目id" json:"projectId,string"`
// 项目名称
ProjectName string `cname:"项目名称" json:"projectName" valid:"Required"`
// 项目分类: 1风险 2成本 3品质 4交期 5服务 6客户关系 7品牌
Types int `cname:"项目分类: 1风险 2成本 3品质 4交期 5服务 6客户关系 7品牌" json:"types" valid:"Required"`
//成本數組
CostManagemants []*CostManagemant `cname:"成本数组" json:"costManagemants" valid:"Required"`
}
// 成本管理
type CostManagemant struct {
// 项目编码
ProjectCode string `json:"projectCode"`
// 成本管理Id
CostManagemantId int64 `json:"costManagemantId,string"`
// 公式id
CompanyId int64 `json:"companyId,string"`
// 标杆值,字符串,如果纯数字的时候参与计算
Benchmark string `json:"benchmark"`
// 负责人数组
ChargePersons []string `json:"chargePersons"`
// 历史最高值,字符串,如果纯数字的时候参与计算
Highest string `json:"highest"`
// 细项名称
ItemName string `json:"itemName"`
// 级别
Level int `json:"level"`
// 父id
ParentId int64 `json:"parentId,string"`
// 现状值,字符串,如果纯数字的时候参与计算
Present string `json:"present"`
// 当前选择的节点类型 1、combination 组合框 2、staff 员工选取 3、text 文本框 4、BOM BOM表
// 5、number数值框 6、calculate计算框
ChoiceId int `cname:"当前选择的节点类型 1、combination 组合框 2、staff 员工选取 3、text 文本框 4、BOM BOM表 5、number数值框 6、calculate计算框" json:"choiceId"`
// 文本内容
Text string `cname:"文本内容" json:"text"`
// 图片
Urls []string `cname:"图片" json:"urls"`
// calculate 计算框:计算框公式
Formula string `cname:"calculate 计算框:计算框公式" json:"formula" `
// 项目id
//ProjectId int64 `json:"projectId,string"`
// 项目名称
ProjectName string `json:"projectName"`
// 进度计划比,字符串,如果纯数字的时候参与计算
SchedulePlanPercent string `json:"schedulePlanPercent"`
// 结构类型
//StructureType int `json:"structureType"`
// 目标值 字符串 为数字时 参与计算
Target string `json:"target"`
// 目标值期限 1 第一季度 2第二季度 3第三季度 4第四季度 5 年度
TargetPeriod int `json:"targetPeriod"`
// 顶级成本管理id
TopCostManagemantId int64 `json:"topCostManagemantId,string"`
// 项目分类: 1风险 2成本 3品质 4交期 5服务 6客户关系 7品牌
Types int `json:"types"`
// 昨日实际值
YesterdayActual string `json:"yesterdayActual"`
}
type NodeType struct {
TypeId int
TypeName string
}
var NodeTypeGroup = []NodeType{
{TypeId: 1, TypeName: "组合框"},
{TypeId: 2, TypeName: "员工类型"},
{TypeId: 3, TypeName: "文本类型"},
{TypeId: 4, TypeName: "BOM表类型"},
{TypeId: 5, TypeName: "数值类型"},
{TypeId: 6, TypeName: "计算类型"},
{TypeId: 7, TypeName: "图片类型"},
}
func (NodeType) GetIdByName(name string) int {
group := NodeTypeGroup
for _, item := range group {
if item.TypeName == name {
return item.TypeId
}
}
return 0
}
func GetTargetPeriod(targetPeriod string) int {
targetPeriod = strings.TrimSpace(targetPeriod)
switch targetPeriod {
case "年度":
return 5
case "第一季度":
return 1
case "第二季度":
return 2
case "第三季度":
return 3
case "第四季度":
return 4
case "":
return 0
}
return -1
}
\ No newline at end of file
... ...
... ... @@ -3,10 +3,11 @@ package domain
/***** 1.用户模块 *****/
// 用户类型
const (
UserTypeEmployee = 1
UserTypeCooperation = 2
UserTypeVisitor = 4
UserTypeCompanyAdmin = 1024
UserTypeEmployee = 1
UserTypeCooperation = 2
UserTypeVisitor = 4
UserTypeOperationAdmin = 8
UserTypeCompanyAdmin = 1024
)
// 用户状态
... ... @@ -62,6 +63,13 @@ const (
ImportDividendsOrders = "BUSINESS_ALLIED-CREATION_BONUS_ORDER"
// 导入退货订单
ImportDividendsReturnOrders = "BUSINESS_ALLIED-CREATION_BONUS_RETURN"
// 导入产品
ImportProducts = "BUSINESS_ALLIED-MANUFACTURING_BASIC_PRODUCT"
// 导入设备
ImportDevices = "BUSINESS_ALLIED-MANUFACTURING_BASIC_DEVICE"
//导入成本结构
ImportCosts = "BUSINESS_ALLIED-COST"
)
const (
... ... @@ -69,6 +77,20 @@ const (
ExportCompanyUser = "ExportCompanyUser"
// 导入共创用户
ExportCooperationUser = "ExportCooperationUser"
// 导入产品
ExportProducts = "ExportProducts"
// 导出员工产能统计
ExportManufactureEmployeeProductive = "ExportManufactureEmployeeProductive"
// 导出车间产能统计
ExportManufactureWorkshopProductive = "ExportManufactureWorkshopProductive"
// 报废记录
ExportSecondLevelRecord = "ExportSecondLevelRecord"
// 员工工时
ExportManufactureEmployeeAttendanceStatics = "ExportManufactureEmployeeAttendanceStatics"
// 车间工时
ExportManufactureWorkshopAttendanceStatics = "ExportManufactureWorkshopAttendanceStatics"
)
const (
... ... @@ -80,3 +102,54 @@ const (
BlockChainSourceCooperationProject = "allied-creation.cooperation.project"
BlockChainSourceCooperationDividendsEstimate = "allied-creation.cooperation.dividends-estimate"
)
const (
DefaultPassword = "4a693460c4cf078ea5b6b5a9e2cf382064a6f810" // TL123456!
)
func EmployeeTypeDescription(employeeType int) string {
if employeeType == 1 {
return "固定"
}
if employeeType == 2 {
return "派遣"
}
if employeeType == 3 {
return "临时"
}
return "固定"
}
func ParticipateTypeDescription(participateType int) string {
if participateType == 1 {
return "正常"
}
if participateType == 2 {
return "支援"
}
return "正常"
}
// 班次
const (
WorkOnFullDay = 1 //全天
WorkOnDay = 2 //白班
WorkOnMidDay = 4 //中班
WorkOnNight = 8 //夜班
)
func WorkOnDescription(workOn int) string {
if workOn&WorkOnFullDay > 0 {
return "全天"
}
if workOn&WorkOnDay > 0 {
return "白班"
}
if workOn&WorkOnMidDay > 0 {
return "中班"
}
if workOn&WorkOnNight > 0 {
return "夜班"
}
return ""
}
... ...
package domain
// 导入数据体
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"`
}
// 导入设备数据体
type ImportDeviceItem struct {
// 设备编号
DeviceCode string `json:"deviceCode,omitempty"`
// 设备名称
DeviceName string `json:"deviceName,omitempty"`
// 设备型号
DeviceModel string `json:"deviceModel,omitempty"`
// 设备类型
DeviceType string `json:"deviceType,omitempty"`
// 品牌
Brand string `json:"brand,omitempty"`
// 设备状态 1:正常 2:封存 3:报废
Status string `json:"status,omitempty"`
// 风险等级 1:高 2:中 3:低
Level string `json:"level,omitempty"`
// 失败理由
FailReason string `json:"failReason"`
}
... ...
... ... @@ -7,8 +7,9 @@ import (
//登录的平台
const (
LoginPlatformApp string = "app"
LoginPlatformWeb string = "web"
LoginPlatformApp string = "app" //天联共创app
LoginPlatformWeb string = "web" //天联共创web
LoginPlatformOperatorWeb string = "operator-web" //天联共创运营-web
)
const (
... ...
... ... @@ -5,6 +5,7 @@ import (
"github.com/linmadan/egglib-go/utils/json"
"github.com/tal-tech/go-queue/kq"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"
"strings"
)
... ... @@ -32,7 +33,13 @@ func Push(topic string, o interface{}) error {
if pusher, ok = defaultClientMap[topic]; !ok {
return fmt.Errorf("pusher client [%v] not found ", topic)
}
return pusher.Push(json.MarshalToString(o))
if err := pusher.Push(json.MarshalToString(o)); err != nil {
log.Logger.Debug(fmt.Sprintf("Topic:%v error:%v", topic, err.Error()), map[string]interface{}{"value": o})
return err
} else {
log.Logger.Debug(fmt.Sprintf("Topic:%v 发送成功", topic), map[string]interface{}{"value": o})
}
return nil
}
// 新建一个推送对象
... ...
package allied_creation_manufacture
import (
"fmt"
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway"
)
//HttpLibAlliedCreationManufacture 生产制造模块
type HttpLibAlliedCreationManufacture struct {
service_gateway.BaseServiceGateway
baseUrL string
}
func NewHttpLibAlliedCreationManufacture(operator domain.Operator) *HttpLibAlliedCreationManufacture {
return &HttpLibAlliedCreationManufacture{
BaseServiceGateway: service_gateway.BaseServiceGateway{
ConnectTimeout: 100 * time.Second,
ReadWriteTimeout: 100 * time.Second,
CompanyId: operator.CompanyId,
OrgId: operator.OrgId,
InOrgIds: operator.OrgIds,
UserId: operator.UserId,
UserBaseId: operator.UserBaseId,
},
baseUrL: constant.ALLIED_CREATION_MANUFACTURE_HOST,
}
}
func (gateway HttpLibAlliedCreationManufacture) BaseUrl() string {
return gateway.baseUrL
}
//BatchAddProduct 批量添加产品
func (gateway HttpLibAlliedCreationManufacture) BatchAddProduct(param BatchAddProductRequest) (*BatchAddProductResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/products/batch-add")
method := "post"
var data BatchAddProductResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type BatchAddProductRequest struct {
List []*domain.ImportProductItem `json:"list"`
}
type BatchAddProductResponse []interface{}
//SearchProduct 搜索产品
func (gateway HttpLibAlliedCreationManufacture) SearchProduct(param SearchProductRequest) (*SearchProductResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/products/search")
method := "post"
var data SearchProductResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchProductRequest struct {
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 产品名称
ProductName string `json:"productName,omitempty"`
// 产品类别
ProductCategory string `cname:"产品类别" json:"productCategory"`
}
SearchProductResponse struct {
Grid struct {
List []SearchProductItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
SearchProductItem struct {
ProductID int `json:"productId"`
ProductCode string `json:"productCode"`
ProductName string `json:"productName"`
ProductCategory string `json:"productCategory"`
Unit string `json:"unit"`
UnitWeight float64 `json:"unitWeight"`
}
)
/*设备*/
//BatchAddProduct 批量添加产品
func (gateway HttpLibAlliedCreationManufacture) BatchAddDevice(param BatchAddDeviceRequest) (*BatchAddProductResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/devices/batch-add")
method := "post"
var data BatchAddProductResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type BatchAddDeviceRequest struct {
List []*domain.ImportDeviceItem `json:"list"`
}
type BatchAddDeviceResponse []interface{}
/**生产记录**/
//SearchProduct 搜索员工产能统计
func (gateway HttpLibAlliedCreationManufacture) SearchEmployeeProductive(param SearchEmployeeProductiveRequest) (*SearchEmployeeProductiveResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/product-records/employee-productive/search")
method := "post"
var data SearchEmployeeProductiveResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchEmployeeProductiveRequest struct {
// 页码
//PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
//PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 姓名
UserName string `cname:"姓名" json:"userName"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType string `cname:"员工类型 1:固定 2:派遣 3.临时" json:"employeeType"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchEmployeeProductiveResponse struct {
Grid struct {
List []EmployeeProductiveItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
EmployeeProductiveItem struct {
EmployeeProductRecordID int `json:"employeeProductRecordId"`
ProductWorker struct {
UserID int `json:"userId"`
UserName string `json:"userName"`
Avatar string `json:"avatar"`
Phone string `json:"phone"`
EmployeeType int `json:"employeeType"`
} `json:"productWorker"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
WorkOn string `json:"workOn"`
PlanProductName string `json:"planProductName"`
BatchNumber string `json:"batchNumber"`
ParticipateType int `json:"participateType"`
ProductWeigh float64 `json:"productWeigh"`
SecondLevelWeigh float64 `json:"secondLevelWeigh"`
CreatedAt string `json:"createdAt"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
QualificationRate int `json:"qualificationRate"`
}
)
//SearchProduct 搜索员工产能统计
func (gateway HttpLibAlliedCreationManufacture) SearchWorkshopProductive(param SearchWorkshopProductiveRequest) (*SearchWorkshopProductiveResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/product-records/workshop-productive/search")
method := "post"
var data SearchWorkshopProductiveResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchWorkshopProductiveRequest struct {
// 品名
PlanProductName string `cname:"品名" json:"planProductName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchWorkshopProductiveResponse struct {
Grid struct {
List []WorkshopProductiveItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
WorkshopProductiveItem struct {
EmployeeProductRecordID int `json:"employeeProductRecordId"`
ProductWorker struct {
UserID int `json:"userId"`
UserName string `json:"userName"`
Avatar string `json:"avatar"`
Phone string `json:"phone"`
EmployeeType int `json:"employeeType"`
} `json:"productWorker"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
WorkOn string `json:"workOn"`
PlanProductName string `json:"planProductName"`
BatchNumber string `json:"batchNumber"`
//ParticipateType int `json:"participateType"`
// 投入量
DevotedProductWeigh float64 `json:"devotedProductWeigh"`
// 产能
ProductWeigh float64 `json:"productWeigh"`
// 二级品产能
SecondLevelWeigh float64 `json:"secondLevelWeigh"`
CreatedAt string `json:"createdAt"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
QualificationRate int `json:"qualificationRate"`
}
)
//SearchProduct 搜索员工产能统计
func (gateway HttpLibAlliedCreationManufacture) SearchSecondLevelRecord(param SearchSecondLevelRecordRequest) (*SearchSecondLevelRecordResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/product-records/second-level-record/search")
method := "post"
var data SearchSecondLevelRecordResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchSecondLevelRecordRequest struct {
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName"`
// 批号
BatchNumber string `cname:"批号" json:"batchNumber"`
// 姓名
UserName string `cname:"姓名" json:"userName"`
// 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重
//ProductRecordType int `cname:"生产记录类型:1:领料 2:退料 4:称重 8:二级品称重"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType int `cname:"员工类型 1:固定 2:派遣 3.临时" json:"employeeType"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchSecondLevelRecordResponse struct {
Grid struct {
List []SecondLevelRecordItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
SecondLevelRecordItem struct {
ProductRecordID int `json:"productRecordId"`
ProductWorker struct {
UserID int `json:"userId"`
UserName string `json:"userName"`
EmployeeType int `json:"employeeType"`
Phone string `json:"phone"`
} `json:"productWorker"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
WorkOn int `json:"workOn"`
WeightBefore int `json:"weightBefore"`
WeightAfter int `json:"weightAfter"`
ApproveStatus int `json:"approveStatus"`
ApproveUser struct {
UserID int `json:"userId"`
UserName string `json:"userName"`
} `json:"approveUser"`
ApproveAt string `json:"approveAt"`
PlanProductName string `json:"planProductName"`
BatchNumber string `json:"batchNumber"`
CreatedDate string `json:"createdDate"`
CreatedAt string `json:"createdAt"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
}
)
/*** 考勤记录 ***/
//SearchEmployeeAttendanceStatics 搜索员工工时统计
func (gateway HttpLibAlliedCreationManufacture) SearchEmployeeAttendanceStatics(param SearchEmployeeAttendanceStaticsRequest) (*SearchEmployeeAttendanceStaticsResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/attendances/employee-attendance-statics/search")
method := "post"
var data SearchEmployeeAttendanceStaticsResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchEmployeeAttendanceStaticsRequest struct {
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 姓名
UserName string `cname:"姓名" json:"userName,omitempty"`
// 考勤状态 1.未审核 2:已审核 4.自动审核
AttendanceStatus int `cname:"考勤状态 1.未审核 2:已审核 4.自动审核" json:"attendanceStatus,omitempty"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchEmployeeAttendanceStaticsResponse struct {
Grid struct {
List []SearchEmployeeAttendanceStaticsItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
SearchEmployeeAttendanceStaticsItem struct {
ProductAttendanceID int `json:"productAttendanceId"`
SignDate string `json:"signDate"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
ProductWorker struct {
UserID int `json:"userId"`
UserName string `json:"userName"`
EmployeeType int `json:"employeeType"`
Avatar string `json:"avatar"`
Phone string `json:"phone"`
} `json:"productWorker"`
AttendanceType int `json:"attendanceType"`
AttendanceStatus int `json:"attendanceStatus"`
AttendanceTypeDescription string `json:"attendanceTypeDescription"`
EmployeeTypeDescription string `json:"employeeTypeDescription"`
AttendanceStatusDescription string `json:"attendanceStatusDescription"`
WorkTime float64 `json:"workTime"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
}
)
//SearchEmployeeAttendanceStatics 搜索员工工时统计
func (gateway HttpLibAlliedCreationManufacture) SearchWorkshopWorkTimeStatics(param SearchWorkshopWorkTimeStaticsRequest) (*SearchWorkshopWorkTimeStaticsResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/attendances/workshop-attendance-statics/search")
method := "post"
var data SearchWorkshopWorkTimeStaticsResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchWorkshopWorkTimeStaticsRequest struct {
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchWorkshopWorkTimeStaticsResponse struct {
Grid struct {
List []SearchWorkshopWorkTimeStaticsItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
SearchWorkshopWorkTimeStaticsItem struct {
WorkshopWorkTimeRecordID int `json:"workshopWorkTimeRecordId"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
EftWorkTime float64 `json:"eftWorkTime"`
EdWorkTime int `json:"edWorkTime"`
EptWorkTime int `json:"eptWorkTime"`
RecordDate string `json:"recordDate"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
}
)
... ...
... ... @@ -28,3 +28,7 @@ func NewHttplibAlliedCreationUser(operator domain.Operator) *HttplibAlliedCreati
}
}
func (gateway HttplibAlliedCreationUser) BaseUrl() string {
return gateway.baseUrL
}
... ...
... ... @@ -135,7 +135,7 @@ func (gateway HttplibAlliedCreationUser) CompanyRemove(param ReqCompanyRemove) (
// CompanyGet 返回企业
func (gateway HttplibAlliedCreationUser) CompanyGet(param ReqCompanyGet) (*DataCompanyGet, error) {
url := gateway.baseUrL + "/company/{companyId}"
url := gateway.baseUrL + "/company/" + strconv.Itoa(param.CompanyId)
method := "GET"
req := gateway.CreateRequest(url, method)
log.Logger.Debug("向用户模块请求数据:返回企业。", map[string]interface{}{
... ... @@ -164,6 +164,66 @@ func (gateway HttplibAlliedCreationUser) CompanyGet(param ReqCompanyGet) (*DataC
return &data, err
}
func (gateway HttplibAlliedCreationUser) AuditCompany(param ReqCompanyAudit) (DataCompanyAudit, error) {
url := gateway.baseUrL + fmt.Sprintf("/company/%d/audit", param.CompanyId)
method := "post"
req := gateway.CreateRequest(url, method)
moduleDesc := "审核公司"
//TODO traceID
log.Logger.Debug("向用户模块请求数据:"+moduleDesc, map[string]interface{}{
"api": method + ":" + url,
"param": param,
})
req, err := req.JSONBody(param)
if err != nil {
return nil, fmt.Errorf("%v失败:%w", moduleDesc, err)
}
byteResult, err := req.Bytes()
if err != nil {
return nil, fmt.Errorf("%v失败:%w", moduleDesc, err)
}
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return nil, fmt.Errorf("解析错误:%w", err)
}
var data DataCompanyAudit
err = gateway.GetResponseData(result, &data)
return data, err
}
func (gateway HttplibAlliedCreationUser) EnableCompany(param ReqCompanyEnable) (DataCompanyEnable, error) {
url := gateway.baseUrL + fmt.Sprintf("/company/%d/enable", param.CompanyId)
method := "post"
req := gateway.CreateRequest(url, method)
moduleDesc := "启用公司"
//TODO traceID
log.Logger.Debug("向用户模块请求数据:"+moduleDesc, map[string]interface{}{
"api": method + ":" + url,
"param": param,
})
req, err := req.JSONBody(param)
if err != nil {
return nil, fmt.Errorf("%v失败:%w", moduleDesc, err)
}
byteResult, err := req.Bytes()
if err != nil {
return nil, fmt.Errorf("%v失败:%w", moduleDesc, err)
}
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return nil, fmt.Errorf("解析错误:%w", err)
}
var data DataCompanyEnable
err = gateway.GetResponseData(result, &data)
return data, err
}
// CompanySearch 返回企业列表
func (gateway HttplibAlliedCreationUser) CompanySearch(param ReqCompanySearch) (*DataCompanySearch, error) {
url := gateway.baseUrL + "/company/search"
... ...
... ... @@ -430,3 +430,131 @@ func (gateway HttplibAlliedCreationUser) UserAccessMenus(param ReqUserAccessMenu
err = gateway.GetResponseData(result, &data)
return &data, err
}
//UserSearch 搜索用户列表
func (gateway HttplibAlliedCreationUser) UserBaseSearch(param ReqUserBaseSearch) (*DataUserBaseSearch, error) {
url := gateway.baseUrL + "/user-base/search"
method := "post"
req := gateway.CreateRequest(url, method)
//TODO traceID
log.Logger.Debug("向用户模块请求数据:搜索用户列表。", map[string]interface{}{
"api": method + ":" + url,
"param": param,
})
req, err := req.JSONBody(param)
if err != nil {
return nil, fmt.Errorf("搜索用户列表失败:%w", err)
}
byteResult, err := req.Bytes()
if err != nil {
return nil, fmt.Errorf("获取搜索用户列表失败:%w", err)
}
if param.Limit > 50 {
//太多就不打印了
log.Logger.Debug("获取用户模块请求数据:搜索用户列表。", map[string]interface{}{
"result": string(byteResult),
})
}
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return nil, fmt.Errorf("解析搜索用户列表:%w", err)
}
var data DataUserBaseSearch
err = gateway.GetResponseData(result, &data)
return &data, err
}
func (gateway HttplibAlliedCreationUser) EnableUserBase(param ReqEnableUserBase) (interface{}, error) {
url := gateway.baseUrL + "/user-base/batch-enable"
method := "post"
req := gateway.CreateRequest(url, method)
//TODO traceID
log.Logger.Debug("向用户模块请求数据:搜索用户列表。", map[string]interface{}{
"api": method + ":" + url,
"param": param,
})
req, err := req.JSONBody(param)
if err != nil {
return nil, fmt.Errorf("搜索用户列表失败:%w", err)
}
byteResult, err := req.Bytes()
if err != nil {
return nil, fmt.Errorf("获取搜索用户列表失败:%w", err)
}
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return nil, fmt.Errorf("解析搜索用户列表:%w", err)
}
//var data DataCompanyEnable
//err = gateway.GetResponseData(result, &data)
return nil, err
}
func (gateway HttplibAlliedCreationUser) AdminUserCreate(param ReqCreateUser) (*DataCreateUser, error) {
url := gateway.baseUrL + "/admin-user"
method := "post"
req := gateway.CreateRequest(url, method)
//TODO traceID
log.Logger.Debug("向用户模块请求数据:创建用户。", map[string]interface{}{
"api": method + ":" + url,
"param": param,
})
req, err := req.JSONBody(param)
if err != nil {
return nil, fmt.Errorf("创建用户失败:%w", err)
}
byteResult, err := req.Bytes()
if err != nil {
return nil, fmt.Errorf("获取创建用户失败:%w", err)
}
log.Logger.Debug("获取用户模块请求数据:创建用户。", map[string]interface{}{
"result": string(byteResult),
})
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return nil, fmt.Errorf("解析创建用户:%w", err)
}
var data DataCreateUser
err = gateway.GetResponseData(result, &data)
return &data, err
}
//UserUpdate 更新用户
func (gateway HttplibAlliedCreationUser) AdminUserUpdate(param ReqUpdateUser) (*DataUpdateUser, error) {
url := gateway.baseUrL + "/admin-user/" + strconv.Itoa(int(param.UserId))
method := "put"
req := gateway.CreateRequest(url, method)
//TODO traceID
log.Logger.Debug("向用户模块请求数据:更新用户。", map[string]interface{}{
"api": method + ":" + url,
"param": param,
})
req, err := req.JSONBody(param)
if err != nil {
return nil, fmt.Errorf("请求更新用户失败:%w", err)
}
byteResult, err := req.Bytes()
if err != nil {
return nil, fmt.Errorf("获取更新用户失败:%w", err)
}
log.Logger.Debug("获取用户模块请求数据:更新用户。", map[string]interface{}{
"result": string(byteResult),
})
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return nil, fmt.Errorf("解析更新用户:%w", err)
}
var data DataUpdateUser
err = gateway.GetResponseData(result, &data)
return &data, err
}
... ...
package allied_creation_user
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
//企业注册
type (
ReqAuthCompanySignUp struct {
... ... @@ -9,6 +11,15 @@ type (
Password string `json:"password"`
Phone string `json:"phone"`
Scale string `json:"scale"`
// 法人
LegalPerson string `cname:"法人" json:"legalPerson" valid:"Required"`
// 社会信用代码
SocialCreditCode string `cname:"社会信用代码" json:"socialCreditCode" valid:"Required"`
// 营业执照所在地
BusinessLicenseAddress domain.BusinessLicenseAddress `cname:"营业执照所在地" json:"businessLicenseAddress" valid:"Required"`
// 营业执照-附件
BusinessLicenseAttachments []domain.Attachment `cname:"营业执照-附件" json:"businessLicenseAttachments" valid:"Required"`
}
DataAuthCompanySignUp struct {
... ...
package allied_creation_user
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"time"
)
//创建企业
type (
ReqCompanyCreate struct {
... ... @@ -49,18 +54,78 @@ type (
//返回企业
type (
ReqCompanyGet struct {
CompanyId int `json:"companyId"`
}
DataCompanyGet struct {
DataCompanyGet CompanyItem
)
type (
ReqCompanyAudit struct {
CompanyId int `json:"-"`
// 审核状态
Status int `cname:"审核状态" json:"status" valid:"Required"`
// 备注
Remark string `cname:"备注" json:"remark" valid:"Required"`
}
DataCompanyAudit map[string]interface{}
)
type (
ReqCompanyEnable struct {
CompanyId int `json:"-"`
// 审核状态
Status int `cname:"审核状态" json:"status" valid:"Required"`
}
DataCompanyEnable map[string]interface{}
)
//返回企业列表
type (
ReqCompanySearch struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset,omitempty"`
// 查询限制
Limit int `cname:"查询限制" json:"limit,omitempty"`
// 状态
Status int `cname:"状态" json:"status,omitempty"`
// 企业名称
CompanyName string `cname:"企业名称" json:"companyName,omitempty"`
}
DataCompanySearch struct {
Companys []CompanyItem `json:"companys"`
Count int `json:"count"`
}
CompanyItem struct {
CompanyId int `json:"companyId"`
CompanyConfig struct {
SystemName string `json:"systemName"`
Theme string `json:"theme"`
} `json:"companyConfig"`
CompanyInfo struct {
CompanyName string `json:"companyName"`
Scale string `json:"scale"`
IndustryCategory string `json:"industryCategory"`
RegisteredTime time.Time `json:"registeredTime"`
Legal struct {
LegalPerson string `json:"legalPerson"`
SocialCreditCode string `json:"socialCreditCode"`
BusinessLicenseAddress struct {
Province string `json:"province"`
City string `json:"city"`
Address string `json:"address"`
} `json:"businessLicenseAddress"`
BusinessLicenseAttachments []domain.Attachment `json:"businessLicenseAttachments"`
} `json:"legal"`
Remark string `json:"备注"`
} `json:"companyInfo"`
Status int `json:"status"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
)
... ...
... ... @@ -23,6 +23,10 @@ type UserDetail struct {
Email string `json:"email"`
UserName string `json:"userName"`
Avatar string `json:"avatar"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType int `json:"employeeType,omitempty"`
// IC卡号
IcCardNumber string `json:"icCardNumber,omitempty"`
} `json:"userInfo,omitempty"`
Company *struct {
CompanyId int `json:"companyId"`
... ... @@ -69,6 +73,11 @@ type UserDetail struct {
} `json:"im"`
// 收藏的菜单(工作台)(菜单编码列表)
FavoriteMenus []string `json:"favoriteMenus"`
Favorite struct {
OrgItems []int64 `json:"orgItems"`
Referer string `json:"referer"`
LastLogInAt int64 `json:"lastLogInAt"`
} `json:"favorite"`
// 创建时间
CreatedAt time.Time `json:"createdAt,omitempty"`
}
... ... @@ -106,6 +115,8 @@ type (
EnableStatus int `cname:"状态(1:启用 2:禁用 3:注销)" json:"enableStatus,omitempty"`
// 状态(1:启用 2:禁用 3:注销)
InEnableStatus []int `cname:"状态(1:启用 2:禁用 3:注销)" json:"inEnableStatus,omitempty"`
// 匹配多个公司
InCompanyIds []interface{} `json:"inCompanyIds,omitempty"`
// 自定义高级查询
AdvancedQuery string `json:"advancedQuery"`
... ... @@ -151,6 +162,13 @@ type (
Avatar string `json:"avatar"`
// 邮箱
Email string `json:"email"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType int `cname:"员工类型" json:"employeeType" valid:"Required"`
// IC卡号
IcCardNumber string `cname:"IC卡号" json:"icCardNumber,omitempty"`
// 部门
DepartmentName string `cname:"部门" json:"departmentName"`
}
DataCreateUser struct {
UserId int `json:"userId"`
... ... @@ -187,6 +205,13 @@ type (
Avatar string `json:"avatar"`
// 邮箱
Email string `json:"email"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType int `cname:"员工类型" json:"employeeType" valid:"Required"`
// IC卡号
IcCardNumber string `cname:"IC卡号" json:"icCardNumber,omitempty"`
// 运营管理扩展
// 部门
DepartmentName string `cname:"部门" json:"departmentName"`
}
DataUpdateUser struct {
... ... @@ -405,7 +430,65 @@ type (
CooperationCompany string `json:"cooperationCompany"`
// 共创到期时间 (yyyy-MM-dd) cooperationDeadline
CooperationDeadline string `json:"cooperationDeadline"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType string `json:"employeeType,omitempty"`
// IC卡号
IcCardNumber string `json:"icCardNumber,omitempty"`
// 失败理由
FailReason string `json:"failReason"`
}
)
//搜索用户列表
type (
ReqUserBaseSearch struct {
// 查询偏离量
Offset int `json:"offset"`
// 查询限制
Limit int `json:"limit"`
// 用户姓名
UserName string `cname:"用户姓名" json:"userName,omitempty"`
// 在用户列表内
InUserBaseIds []int64 `cname:"用户姓名" json:"inUserBaseIds,omitempty"`
// 所属组织
OrgName string `cname:"所属组织" json:"orgName,omitempty"`
// 关闭查询限制
DisableLimit bool `cname:"关闭查询限制" json:"disableLimit,omitempty"`
// 获取组织
FetchOrgBelong bool `cname:"获取组织" json:"fetchOrgBelong,omitempty"`
}
//DataUserSearch 搜索用户列表
DataUserBaseSearch struct {
Count int64 `json:"count"`
Users []UserBaseDetail `json:"users"`
}
UserBaseDetail struct {
UserBaseId int `json:"userBaseId"`
LastLogIn string `json:"lastLogIn"`
UserInfo struct {
UserName string `json:"userName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
} `json:"userInfo"`
Status int `json:"status"`
Referer string `json:"referer"`
UserOrg []struct {
OrgId int `json:"orgId"`
OrgName string `json:"orgName"`
} `json:"userOrg"`
RegistrationDate string `json:"registrationDate"`
}
)
type (
ReqEnableUserBase struct {
UserBaseIds []int64 `cname:"用户id列表" json:"userBaseIds" valid:"Required"`
// 启用状态(启用:1 禁用:2 注销:3)
EnableStatus int `cname:"启用状态(启用:1 禁用:2 注销:3)" json:"enableStatus" valid:"Required"`
}
//DataUserSearch 搜索用户列表
DataEnableUserBase = interface{}
)
... ...
package cost_structured
import (
"encoding/json"
"fmt"
"strings"
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway"
)
//HttpLibCostStructured 成本结构化
type HttpLibCostStructured struct {
service_gateway.BaseServiceGateway
baseUrL string
}
func NewHttpLibCostStructured(operator domain.Operator) *HttpLibCostStructured {
return &HttpLibCostStructured{
BaseServiceGateway: service_gateway.BaseServiceGateway{
ConnectTimeout: 100 * time.Second,
ReadWriteTimeout: 100 * time.Second,
CompanyId: operator.CompanyId,
OrgId: operator.OrgId,
InOrgIds: operator.OrgIds,
UserId: operator.UserId,
UserBaseId: operator.UserBaseId,
},
baseUrL: constant.COST_STRUCTURED,
}
}
func (gateway HttpLibCostStructured) BaseUrl() string {
return gateway.baseUrL
}
//批量添加成本管理
func (gateway HttpLibCostStructured) BatchCreateCostManagemant(param BatchAddCostManagemantRequest) (*service_gateway.GatewayResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/cost-managemants/batch-create-cost-managemants")
method := "post"
//var data BatchAddCostManagemantResponse
//err := gateway.FastDoRequest(url, method, param, &data)
r := gateway.CreateRequest(url, method)
if len(gateway.InOrgIds) > 0 {
r.Header("orgIds", strings.Join(service_gateway.ToArrayString(gateway.InOrgIds), ","))
}
req, err := r.JSONBody(param)
if err != nil {
return nil,err
}
byteResult, err:= req.Bytes()
if err != nil {
return nil,err
}
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return nil,err
}
return &result, nil
}
type BatchAddCostManagemantRequest struct {
*domain.BatchCreateCostManagemant
}
type BatchAddCostManagemantResponse []interface{}
func (gateway HttpLibCostStructured) ListCostManagemant(param ListCostManagemantRequest) (*ListCostManagemantResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/cost-managemants/")
method := "post"
var data ListCostManagemantResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
ListCostManagemantRequest struct {
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 查询项目(结构)类型
Types int `cname:"查询项目(结构)类型" json:"types" valid:"Required"`
// 查询项目id
ProjectId int64 `cname:"查询项目id" json:"projectId"`
}
ListCostManagemantResponse struct {
Grid struct {
List []SearchProductItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
SearchProductItem struct {
ProductID int `json:"productId"`
ProductCode string `json:"productCode"`
ProductName string `json:"productName"`
ProductCategory string `json:"productCategory"`
Unit string `json:"unit"`
UnitWeight float64 `json:"unitWeight"`
}
)
/*设备*/
type BatchAddDeviceRequest struct {
List []*domain.ImportDeviceItem `json:"list"`
}
type BatchAddDeviceResponse []interface{}
/**生产记录**/
//SearchProduct 搜索员工产能统计
func (gateway HttpLibCostStructured) SearchEmployeeProductive(param SearchEmployeeProductiveRequest) (*SearchEmployeeProductiveResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/product-records/employee-productive/search")
method := "post"
var data SearchEmployeeProductiveResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchEmployeeProductiveRequest struct {
// 页码
//PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
//PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 姓名
UserName string `cname:"姓名" json:"userName"`
// 员工类型 1:固定 2:派遣 3.临时
EmployeeType string `cname:"员工类型 1:固定 2:派遣 3.临时" json:"employeeType"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchEmployeeProductiveResponse struct {
Grid struct {
List []EmployeeProductiveItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
EmployeeProductiveItem struct {
EmployeeProductRecordID int `json:"employeeProductRecordId"`
ProductWorker struct {
UserID int `json:"userId"`
UserName string `json:"userName"`
Avatar string `json:"avatar"`
Phone string `json:"phone"`
EmployeeType int `json:"employeeType"`
} `json:"productWorker"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
WorkOn string `json:"workOn"`
PlanProductName string `json:"planProductName"`
BatchNumber string `json:"batchNumber"`
ParticipateType int `json:"participateType"`
ProductWeigh float64 `json:"productWeigh"`
SecondLevelWeigh float64 `json:"secondLevelWeigh"`
CreatedAt string `json:"createdAt"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
QualificationRate int `json:"qualificationRate"`
}
)
//SearchProduct 搜索员工产能统计
func (gateway HttpLibCostStructured) SearchWorkshopProductive(param SearchWorkshopProductiveRequest) (*SearchWorkshopProductiveResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/product-records/workshop-productive/search")
method := "post"
var data SearchWorkshopProductiveResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchWorkshopProductiveRequest struct {
// 品名
PlanProductName string `cname:"品名" json:"planProductName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchWorkshopProductiveResponse struct {
Grid struct {
List []WorkshopProductiveItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
WorkshopProductiveItem struct {
EmployeeProductRecordID int `json:"employeeProductRecordId"`
ProductWorker struct {
UserID int `json:"userId"`
UserName string `json:"userName"`
Avatar string `json:"avatar"`
Phone string `json:"phone"`
EmployeeType int `json:"employeeType"`
} `json:"productWorker"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
WorkOn string `json:"workOn"`
PlanProductName string `json:"planProductName"`
BatchNumber string `json:"batchNumber"`
//ParticipateType int `json:"participateType"`
// 投入量
DevotedProductWeigh float64 `json:"devotedProductWeigh"`
// 产能
ProductWeigh float64 `json:"productWeigh"`
// 二级品产能
SecondLevelWeigh float64 `json:"secondLevelWeigh"`
CreatedAt string `json:"createdAt"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
QualificationRate int `json:"qualificationRate"`
}
)
/*** 考勤记录 ***/
//SearchEmployeeAttendanceStatics 搜索员工工时统计
func (gateway HttpLibCostStructured) SearchEmployeeAttendanceStatics(param SearchEmployeeAttendanceStaticsRequest) (*SearchEmployeeAttendanceStaticsResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/attendances/employee-attendance-statics/search")
method := "post"
var data SearchEmployeeAttendanceStaticsResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchEmployeeAttendanceStaticsRequest struct {
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 姓名
UserName string `cname:"姓名" json:"userName,omitempty"`
// 考勤状态 1.未审核 2:已审核 4.自动审核
AttendanceStatus int `cname:"考勤状态 1.未审核 2:已审核 4.自动审核" json:"attendanceStatus,omitempty"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchEmployeeAttendanceStaticsResponse struct {
Grid struct {
List []SearchEmployeeAttendanceStaticsItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
SearchEmployeeAttendanceStaticsItem struct {
ProductAttendanceID int `json:"productAttendanceId"`
SignDate string `json:"signDate"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
ProductWorker struct {
UserID int `json:"userId"`
UserName string `json:"userName"`
EmployeeType int `json:"employeeType"`
Avatar string `json:"avatar"`
Phone string `json:"phone"`
} `json:"productWorker"`
AttendanceType int `json:"attendanceType"`
AttendanceStatus int `json:"attendanceStatus"`
AttendanceTypeDescription string `json:"attendanceTypeDescription"`
EmployeeTypeDescription string `json:"employeeTypeDescription"`
AttendanceStatusDescription string `json:"attendanceStatusDescription"`
WorkTime float64 `json:"workTime"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
}
)
//SearchEmployeeAttendanceStatics 搜索员工工时统计
func (gateway HttpLibCostStructured) SearchWorkshopWorkTimeStatics(param SearchWorkshopWorkTimeStaticsRequest) (*SearchWorkshopWorkTimeStaticsResponse, error) {
url := fmt.Sprintf("%s%s", gateway.BaseUrl(), "/attendances/workshop-attendance-statics/search")
method := "post"
var data SearchWorkshopWorkTimeStaticsResponse
err := gateway.FastDoRequest(url, method, param, &data)
return &data, err
}
type (
SearchWorkshopWorkTimeStaticsRequest struct {
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 开始时间
BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
EndTime string `cname:"结束时间" json:"endTime"`
}
SearchWorkshopWorkTimeStaticsResponse struct {
Grid struct {
List []SearchWorkshopWorkTimeStaticsItem `json:"list"`
Total int `json:"total"`
} `json:"grid"`
}
SearchWorkshopWorkTimeStaticsItem struct {
WorkshopWorkTimeRecordID int `json:"workshopWorkTimeRecordId"`
WorkStationID string `json:"workStationId"`
WorkshopID int `json:"workshopId"`
WorkshopName string `json:"workshopName"`
LineID int `json:"lineId"`
LineName string `json:"lineName"`
SectionID int `json:"sectionId"`
SectionName string `json:"sectionName"`
EftWorkTime float64 `json:"eftWorkTime"`
EdWorkTime int `json:"edWorkTime"`
EptWorkTime int `json:"eptWorkTime"`
RecordDate string `json:"recordDate"`
OrgName string `json:"orgName"`
AuthFlag bool `json:"authFlag"`
}
)
... ...
... ... @@ -5,6 +5,7 @@ import (
"fmt"
"github.com/linmadan/egglib-go/utils/json"
"strconv"
"strings"
"time"
"github.com/beego/beego/v2/client/httplib"
... ... @@ -27,6 +28,7 @@ type BaseServiceGateway struct {
ReadWriteTimeout time.Duration
CompanyId int64
OrgId int64
InOrgIds []int64
UserId int64
UserBaseId int64
}
... ... @@ -66,3 +68,57 @@ func (gateway BaseServiceGateway) GetResponseData(result GatewayResponse, data i
}
return nil
}
func (gateway BaseServiceGateway) FastDoRequest(url, method string, param interface{}, data interface{}) error {
err := gateway.DoRequest(Request{
Url: url,
Method: method,
Param: param,
}, &data)
log.Logger.Info("接口请求:----", map[string]interface{}{
"url": url,
"method": method,
"param": param,
"data": data,
})
if err != nil {
return err
}
return nil
}
func (gateway BaseServiceGateway) DoRequest(requestParam Request, val interface{}) error {
r := gateway.CreateRequest(requestParam.Url, requestParam.Method)
if len(gateway.InOrgIds) > 0 {
r.Header("orgIds", strings.Join(ToArrayString(gateway.InOrgIds), ","))
}
req, err := r.JSONBody(requestParam.Param)
if err != nil {
return err
}
byteResult, err := req.Bytes()
if err != nil {
return err
}
var result GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return err
}
err = gateway.GetResponseData(result, val)
return nil
}
type Request struct {
Url string
Method string
Param interface{}
}
func ToArrayString(inputs []int64) []string {
result := make([]string, 0)
for i := range inputs {
result = append(result, strconv.Itoa(int(inputs[i])))
}
return result
}
... ...
... ... @@ -63,6 +63,43 @@ func (smsServe HttplibSmsServe) SendSms(phone string) error {
return nil
}
//SendSms 公共短信验证码服务 发送验证码
func (smsServe HttplibSmsServe) SendNoticeSms(phone string, tplId int, tplValues map[string]interface{}) error {
url := smsServe.baseUrL + "/service/sendNoticeSms"
method := "post"
req := smsServe.CreateRequest(url, method)
param := map[string]interface{}{
"phone": phone,
"tplId": tplId,
"tplValues": tplValues,
}
log.Logger.Debug("向公共短信验证码服务请求数据:短信验证码接口。", map[string]interface{}{
"api": method + ":" + url,
"param": param,
})
req, err := req.JSONBody(param)
if err != nil {
return fmt.Errorf("请求公共短信验证码服务失败:%w", err)
}
byteResult, err := req.Bytes()
if err != nil {
return fmt.Errorf("获取公共短信验证码服务失败:%w", err)
}
log.Logger.Debug("获取公共短信验证码服务请求数据", map[string]interface{}{
"result": string(byteResult),
})
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return fmt.Errorf("解析更新组织:%w", err)
}
if result.Code != 0 {
return fmt.Errorf(result.Msg)
}
return nil
}
//CheckSmsCode 公共短信验证码服务 校验验证码
func (smsServe HttplibSmsServe) CheckSmsCode(phone string, code string) error {
if code == constant.SMSCODE_ALL_POWER {
... ...
package beego
import (
"encoding/json"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"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"
"net/http"
"os"
"strconv"
... ... @@ -48,25 +51,30 @@ func init() {
filters.SecureKeyMap["token"] = "x-mmm-accesstoken"
web.InsertFilter("/*", web.BeforeRouter, AllowCors())
web.InsertFilter("/*", web.BeforeRouter, filters.CreateRequstLogFilter(log.Logger))
web.InsertFilter("/v1/web/*", web.BeforeExec, middleware.CheckAccessToken2())
web.InsertFilter("/v1/app/*", web.BeforeExec, middleware.CheckAccessToken2())
web.InsertFilter("/v1/user/*", web.BeforeExec, middleware.CheckAccessToken2())
web.InsertFilter("/v1/background/*", web.BeforeExec, middleware.CheckAccessToken())
web.InsertFilter("/v1/web/*", web.BeforeExec, middleware.CheckAccessToken())
web.InsertFilter("/v1/app/*", web.BeforeExec, middleware.CheckAccessToken())
web.InsertFilter("/v1/user/*", web.BeforeExec, middleware.CheckAccessToken())
web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(log.Logger), web.WithReturnOnOutput(false))
web.InsertFilter("/v1/app11/*", web.BeforeExec, filters.SecureHandler(
filters.WithEnableCheckTimestamp(false),
filters.WithOnInvalidRequest(func(ctx *context.Context) {
headerData, _ := json.Marshal(ctx.Input.Context.Request.Header)
log.Logger.Info("签名验证失败:" + string(headerData))
}),
))
//web.InsertFilterChain("/v1/*", middleware.CheckAccessToken)
//web.InsertFilter("/v1/app11/*", web.BeforeExec, filters.SecureHandler(
// filters.WithEnableCheckTimestamp(false),
// filters.WithOnInvalidRequest(func(ctx *context.Context) {
// headerData, _ := json.Marshal(ctx.Input.Context.Request.Header)
// log.Logger.Info("签名验证失败:" + string(headerData))
// }),
//))
web.InsertFilter("/v1/common/user/area/*", web.BeforeRouter, middleware.RedirectInternalService("/v1/common/user", allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})))
web.InsertFilter("/v1/manufacture/*", web.BeforeRouter, middleware.CheckAccessToken())
web.InsertFilter("/v1/manufacture/*", web.BeforeRouter, middleware.RedirectInternalService("/v1/manufacture", allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(domain.Operator{})))
web.InsertFilter("/v1/cost/*", web.BeforeRouter, middleware.CheckAccessToken())
web.InsertFilter("/v1/cost/*", web.BeforeRouter, middleware.RedirectInternalService("/v1/cost", cost_structured.NewHttpLibCostStructured(domain.Operator{})))
}
func AllowCors() func(ctx *context.Context) {
return func(ctx *context.Context) {
ctx.Output.Header("Access-Control-Allow-Methods", "OPTIONS,DELETE,POST,GET,PUT,PATCH")
//ctx.Output.Header("Access-Control-Max-Age", "3600")
//ctx.Output.Header("Access-Control-Allow-Headers", "*,x-mmm-version")
ctx.Output.Header("Access-Control-Allow-Headers", "Content-Type,X-Mmm-Accesstoken,X-Mmm-Devicetype,X-Mmm-Sign,X-Mmm-Timestamp,X-Mmm-Uuid,X-Mmm-Version,x-mmm-appname,*")
ctx.Output.Header("Access-Control-Allow-Credentials", "true")
ctx.Output.Header("Access-Control-Allow-Origin", "*") //origin
... ...
package backgroud_client
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/auth/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/auth/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers"
)
type AuthController struct {
controllers.BaseController
}
func (controller *AuthController) LoginPwd() {
authService := service.AuthService{}
loginCmd := &command.LoginPwdCommand{}
//Must()
controller.Unmarshal(loginCmd)
data, err := authService.AuthAdminLogin(loginCmd)
controller.Response(data, err)
}
... ...
package backgroud_client
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/company/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/company/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/company/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers"
)
type CompanyController struct {
controllers.BaseController
}
// func (controller *CompanyController) CreateCompany() {
// companyService := service.NewCompanyService(nil)
// createCompanyCommand := &command.CreateCompanyCommand{}
// controller.Unmarshal(createCompanyCommand)
// data, err := companyService.CreateCompany(createCompanyCommand)
// controller.Response(data, err)
// }
func (controller *CompanyController) UpdateCompany() {
companyService := service.NewCompanyService(nil)
updateCompanyCommand := &command.UpdateCompanyCommand{}
controller.Unmarshal(updateCompanyCommand)
updateCompanyCommand.Operator = controller.GetOperator()
data, err := companyService.UpdateCompany(updateCompanyCommand)
controller.Response(data, err)
}
func (controller *CompanyController) GetCompany() {
companyService := service.NewCompanyService(nil)
getCompanyQuery := &query.GetCompanyQuery{}
companyId, _ := controller.GetInt(":companyId")
getCompanyQuery.CompanyId = companyId
data, err := companyService.GetCompany(getCompanyQuery)
controller.Response(data, err)
}
// func (controller *CompanyController) RemoveCompany() {
// companyService := service.NewCompanyService(nil)
// removeCompanyCommand := &command.RemoveCompanyCommand{}
// controller.Unmarshal(removeCompanyCommand)
// companyId, _ := controller.GetInt64(":companyId")
// removeCompanyCommand.CompanyId = companyId
// data, err := companyService.RemoveCompany(removeCompanyCommand)
// controller.Response(data, err)
// }
func (controller *CompanyController) SearchCompany() {
companyService := service.NewCompanyService(nil)
listCompanyQuery := &query.ListCompanyQuery{}
controller.Unmarshal(listCompanyQuery)
cnt, data, err := companyService.ListCompany(listCompanyQuery)
controller.ReturnPageListData(cnt, data, err, listCompanyQuery.PageNumber)
}
func (controller *CompanyController) AuditCompany() {
companyService := service.NewCompanyService(nil)
cmd := &command.AuditCompanyCommand{}
controller.Unmarshal(cmd)
companyId, _ := controller.GetInt64(":companyId")
cmd.CompanyId = companyId
data, err := companyService.AuditCompany(cmd)
controller.Response(data, err)
}
func (controller *CompanyController) EnableCompany() {
companyService := service.NewCompanyService(nil)
cmd := &command.EnableCompanyCommand{}
controller.Unmarshal(cmd)
companyId, _ := controller.GetInt64(":companyId")
cmd.CompanyId = companyId
data, err := companyService.EnableCompany(cmd)
controller.Response(data, err)
}
... ...
package backgroud_client
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers"
)
type UserController struct {
controllers.BaseController
}
func (controller *UserController) SearchUser() {
companyService := service.NewUserService(nil)
listCompanyQuery := &query.ListUserQuery{}
controller.Unmarshal(listCompanyQuery)
cnt, data, err := companyService.SearchUser(listCompanyQuery)
controller.ReturnPageListData(cnt, data, err, listCompanyQuery.PageNumber)
}
func (controller *UserController) EnableUser() {
companyService := service.NewUserService(nil)
cmd := &command.EnableUserCommand{}
controller.Unmarshal(cmd)
data, err := companyService.EnableUser(cmd)
controller.Response(data, err)
}
func (controller *UserController) ResetPassword() {
companyService := service.NewUserService(nil)
cmd := &command.ResetPasswordCommand{}
controller.Unmarshal(cmd)
data, err := companyService.ResetPassword(cmd)
controller.Response(data, err)
}
func (controller *UserController) SearchAdminUser() {
companyService := service.NewUserService(nil)
q := &query.ListAdminUserQuery{}
controller.Unmarshal(q)
cnt, data, err := companyService.AdminUserList(q)
controller.ReturnPageListData(cnt, data, err, q.PageNumber)
}
func (controller *UserController) EnableAdminUser() {
companyService := service.NewUserService(nil)
cmd := &command.EnableAdminUserCommand{}
controller.Unmarshal(cmd)
data, err := companyService.EnableAdminUser(cmd)
controller.Response(data, err)
}
func (controller *UserController) GetAdminUser() {
companyService := service.NewUserService(nil)
userId, _ := controller.GetInt(":userId")
data, err := companyService.GetAdminUser(userId)
controller.Response(data, err)
}
func (controller *UserController) UpdateAdminUser() {
companyService := service.NewUserService(nil)
cmd := &command.AdminUserEditCommand{}
controller.Unmarshal(cmd)
userId, _ := controller.GetInt(":userId")
cmd.UserId = int64(userId)
data, err := companyService.UpdateAdminUser(cmd)
controller.Response(data, err)
}
func (controller *UserController) CreateAdminUser() {
companyService := service.NewUserService(nil)
cmd := &command.AdminUserAddCommand{}
controller.Unmarshal(cmd)
data, err := companyService.CreateAdminUser(cmd)
controller.Response(data, err)
}
func (controller *UserController) GetAdminUserInfo() {
companyService := service.NewUserService(nil)
operator := controller.GetOperator()
data, err := companyService.GetAdminUserInfo(operator)
controller.Response(data, err)
}
... ...
... ... @@ -11,6 +11,7 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/middleware"
"io"
"path/filepath"
"strings"
)
type BaseController struct {
... ... @@ -97,7 +98,7 @@ func (controller *BaseController) GetOperator() domain.Operator {
}
// 打印测试日志
// log.Logger.Debug("operator " + json.MarshalToString(op))
log.Logger.Debug("operator " + json.MarshalToString(op))
return op
}
... ... @@ -124,17 +125,19 @@ func (controller *BaseController) GetExcelFile() (io.Reader, error) {
return excelFile, nil
}
func (controller *BaseController) GetFileWithExt() (io.Reader, string, error) {
func (controller *BaseController) GetFileWithExt() (io.Reader, string,string, error) {
excelFile, fileHeader, err := controller.GetFile("file")
if err != nil {
log.Logger.Error(err.Error())
return nil, "", fmt.Errorf("上传文件不存在")
return nil, "","", fmt.Errorf("上传文件不存在")
}
ext := filepath.Ext(fileHeader.Filename)
if !(ext == ".xlsx" || ext == ".xls" || ext == ".csv") {
return nil, "", fmt.Errorf("仅支持上传文件格式 xls/xlsx/csv")
return nil, "","", fmt.Errorf("仅支持上传文件格式 xls/xlsx/csv")
}
return excelFile, ext, nil
fileName := filepath.Base(fileHeader.Filename)
fileName = strings.TrimRight(fileName,ext)
return excelFile, ext,fileName, nil
}
func Must(err error) {
... ...
... ... @@ -2,6 +2,7 @@ package web_client
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers"
"io"
"strings"
... ... @@ -190,9 +191,10 @@ func defaultImport(controller *ExcelDataController) {
err error
r io.Reader
ext string
fileName string
)
excelService := service.NewExcelDataService(nil)
r, ext, err = controller.GetFileWithExt()
r, ext,fileName, err = controller.GetFileWithExt()
if err != nil {
controller.Response(nil, err)
return
... ... @@ -202,6 +204,7 @@ func defaultImport(controller *ExcelDataController) {
cmd.Operator = controller.GetOperator()
cmd.Reader = r
cmd.FileExt = ext
cmd.FileName = fileName
switch cmd.Code {
case domain.ImportCompanyUser:
data, err = excelService.ImportCompanyUser(cmd)
... ... @@ -209,6 +212,12 @@ func defaultImport(controller *ExcelDataController) {
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)
}
... ... @@ -261,6 +270,36 @@ func fileExport(controller *ExcelDataController, code string) {
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 = "导出车间工时汇总"
default:
err = fmt.Errorf("export type :%v not exists", exportDataCommand.Code)
}
... ... @@ -291,7 +330,35 @@ 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)
}
//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)
}
... ...
... ... @@ -19,7 +19,7 @@ func (controller *MenuController) MenuList() {
log.Logger.Debug("json err:" + err.Error())
}
menuListQuery.Operator = controller.GetOperator()
data, err := menuService.MenuList(menuListQuery)
data, err := menuService.CustomizeMenus(menuListQuery)
controller.Response(data, err)
}
... ... @@ -46,3 +46,15 @@ func (controller *MenuController) MenuFavorite() {
data, err := menuService.MenuFavorite(menuFavoriteCommand)
controller.Response(data, err)
}
func (controller *MenuController) MenuSearch() {
menuService := service.NewMenuService(nil)
menuListQuery := &query.MenuListQuery{}
err := controller.Unmarshal(menuListQuery)
if err != nil {
log.Logger.Debug("json err:" + err.Error())
}
menuListQuery.Operator = controller.GetOperator()
data, err := menuService.MenuSearch(menuListQuery)
controller.Response(data, err)
}
... ...
... ... @@ -2,99 +2,26 @@ package middleware
import (
"fmt"
log1 "log"
"net/http"
"net/url"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/cache"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"
)
type CtxKeyLoginToken struct{}
func JWTAuth(ctx *context.Context) {
}
func CheckAccessToken(next web.FilterFunc) web.FilterFunc {
return func(ctx *context.Context) {
tokenStr := ctx.Input.Header("x-mmm-accesstoken")
filterMap := map[string]string{
"/v1/auth/login/pwd": "",
"/v1/auth/login/sms": "",
"/v1/auth/login/qrcode": "",
"/v1/auth/org-switch": "",
"/v1/user/company-orgs": "",
"/v1/auth/captcha-init": "",
"/v1/auth/qrcode-init": "",
"/v1/auth/sms-code": "",
"/v1/auth/check-sms-code": "",
"/v1/auth/company-sign-up": "",
"/v1/auth/reset-password": "",
"/v1/auth/refresh-token": "",
"/v1/app/cooperation-projects/person/search": "",
}
var err error
if filterUrl, err := url.Parse(ctx.Request.RequestURI); err == nil {
// 不需要验证的接口
if _, ok := filterMap[filterUrl.Path]; ok {
next(ctx)
return
}
} else {
log.Logger.Error("parse url error:" + err.Error())
}
defer func() {
if err != nil {
ctx.Output.SetStatus(http.StatusOK)
ctx.Output.JSON(map[string]interface{}{
"msg": domain.ParseCodeMsg(domain.InvalidAccessToken),
"code": domain.InvalidAccessToken,
"data": struct{}{},
}, false, false)
}
}()
tk := &domain.LoginToken{}
err = tk.ParseToken(tokenStr)
if err != nil {
log.Logger.Error(err.Error())
return
}
platform := domain.ParsePlatform(ctx.Input.Header("x-mmm-devicetype"))
// redis缓存
tokenCache := cache.LoginTokenCache{}
token, err := tokenCache.GetAccessToken(tk.Account, platform)
if err != nil {
log.Logger.Error(err.Error())
return
}
if token != tokenStr {
log1.Println("token not equal \n" + tk.Account + "\n" + tokenStr + "\n" + token)
err = fmt.Errorf("access token not exists")
return
}
ctx.Input.SetData(CtxKeyLoginToken{}, tk)
next(ctx)
}
}
func NewCtxLoginToken(ctx *context.Context, tk domain.LoginToken) {
ctx.Input.SetData(CtxKeyLoginToken{}, domain.LoginToken{})
}
func FormCtxLoginToken(ctx *context.Context) (domain.LoginToken, bool) {
val := ctx.Input.GetData(CtxKeyLoginToken{})
if v, ok := val.(domain.LoginToken); ok {
return v, true
if v, ok := val.(*domain.LoginToken); ok {
return *v, true
}
return domain.LoginToken{}, false
}
func CheckAccessToken2() web.FilterFunc {
func CheckAccessToken() web.FilterFunc {
return func(ctx *context.Context) {
tokenStr := ctx.Input.Header("x-mmm-accesstoken")
filterMap := map[string]string{
... ... @@ -116,6 +43,8 @@ func CheckAccessToken2() web.FilterFunc {
"/v1/user/cooperation-org": "",
"/v1/app/cooperation-projects/person/shared-info": "", //共创项目详情 - 未登录可以查看
"/v1/app/cooperation-projects/person/shared-info/attachment": "",
"/v1/background/auth/login/pwd": "",
}
var err error
if filterUrl, err := url.Parse(ctx.Request.RequestURI); err == nil {
... ... @@ -136,10 +65,11 @@ func CheckAccessToken2() web.FilterFunc {
}, false, false)
}
}()
//log.Logger.Debug(tokenStr)
tk := &domain.LoginToken{}
err = tk.ParseToken(tokenStr)
if err != nil {
fmt.Println(fmt.Sprintf("token:%v|", tokenStr))
log.Logger.Error(err.Error())
return
}
... ...
package middleware
import (
"encoding/json"
"fmt"
"github.com/beego/beego/v2/client/httplib"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway"
"io/ioutil"
"net/http"
"strings"
)
type internalService interface {
GetResponseData(result service_gateway.GatewayResponse, data interface{}) error
CreateRequest(url string, method string) *httplib.BeegoHTTPRequest
BaseUrl() string
}
func RedirectInternalService(prefix string, svr internalService) web.FilterFunc {
return func(ctx *context.Context) {
if !strings.HasPrefix(ctx.Request.RequestURI, prefix) {
return
}
var err error
var byteResult []byte
var data = make(map[string]interface{})
defer func() {
if err != nil {
ctx.Output.SetStatus(http.StatusOK)
ctx.Output.JSON(map[string]interface{}{
"msg": err.Error(),
"code": 1,
"data": struct{}{},
}, false, false)
}
}()
method := strings.ToLower(ctx.Request.Method)
url := strings.Replace(ctx.Request.RequestURI, prefix, "", 1)
req := svr.CreateRequest(svr.BaseUrl()+url, method)
// 传递当前登录信息(可配置)
loginToken, ok := FormCtxLoginToken(ctx)
if ok && loginToken.CompanyId > 0 && loginToken.OrgId > 0 {
req.Header("companyId", fmt.Sprintf("%v", loginToken.CompanyId))
req.Header("orgId", fmt.Sprintf("%v", loginToken.OrgId))
req.Header("userId", fmt.Sprintf("%v", loginToken.UserId))
orgIdList := make([]string, 0)
for i := range loginToken.OrgIds {
orgIdList = append(orgIdList, fmt.Sprintf("%d", loginToken.OrgIds[i]))
}
req.Header("orgIds", fmt.Sprintf("%v", strings.Join(orgIdList, ",")))
}
req.Body(ctx.Input.RequestBody)
response, err := req.Response()
if err != nil {
return
}
if response.StatusCode != http.StatusOK {
err = fmt.Errorf("%v", response.Status)
return
}
byteResult, err = ioutil.ReadAll(response.Body)
if err != nil {
return
}
defer response.Body.Close()
// 透传非json数据
contentType := response.Header.Get("Content-Type")
if contentType != "application/json" {
copyResponse(ctx, response, byteResult)
return
}
var result service_gateway.GatewayResponse
err = json.Unmarshal(byteResult, &result)
if err != nil {
return
}
err = svr.GetResponseData(result, &data)
if err != nil {
return
}
ctx.Output.SetStatus(http.StatusOK)
ctx.Output.JSON(map[string]interface{}{
"msg": "成功",
"code": 0,
"data": data,
}, false, false)
}
}
func copyResponse(ctx *context.Context, response *http.Response, data []byte) {
for k, v := range response.Header {
if len(v) == 0 {
continue
}
ctx.Output.Header(k, strings.Join(v, ","))
}
ctx.Output.SetStatus(response.StatusCode)
ctx.Output.Body(data)
}
... ...
package middleware
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_manufacture"
)
func RedirectManufactureWeigh() web.FilterFunc {
return RedirectInternalService("/v1/manufacture-weigh", allied_creation_manufacture.NewHttpLibAlliedCreationManufacture(domain.Operator{
CompanyId: int64(constant.MANUFACTURE_WEIGH_DEFAULT_COMPANYID),
OrgId: int64(constant.MANUFACTURE_WEIGH_DEFAULT_ORGID),
}))
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers/backgroud_client"
)
func init() {
web.Router("/v1/background/menus/", &backgroud_client.MenuController{}, "Post:CreateMenu")
web.Router("/v1/background/menus/:menuId", &backgroud_client.MenuController{}, "Put:UpdateMenu")
web.Router("/v1/background/menus/:menuId", &backgroud_client.MenuController{}, "Get:GetMenu")
//web.Router("/v1/background/menus/:menuId", &backgroud_client.MenuController{}, "Delete:RemoveMenu")
//web.Router("/v1/background/menus/search", &backgroud_client.MenuController{}, "Get:ListMenu")
web.Router("/v1/background/menus/search", &backgroud_client.MenuController{}, "Post:SearchMenu")
web.Router("/v1/background/menus/batch-delete", &backgroud_client.MenuController{}, "Post:BatchDeleteMenu")
web.Router("/v1/background/menus/batch-enable", &backgroud_client.MenuController{}, "Post:BatchEnableMenu")
}
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers/backgroud_client"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers/web_client"
)
func init() {
// dictionary
web.Router("/v1/background/dictionary/", &backgroud_client.DictionaryController{}, "Post:CreateDictionary")
web.Router("/v1/background/dictionary/:dictionaryId", &backgroud_client.DictionaryController{}, "Put:UpdateDictionary")
web.Router("/v1/background/dictionary/:dictionaryId", &backgroud_client.DictionaryController{}, "Get:GetDictionary")
web.Router("/v1/background/dictionary/search", &backgroud_client.DictionaryController{}, "Post:ListDictionary")
web.Router("/v1/background/dictionary/remove", &backgroud_client.DictionaryController{}, "Post:RemoveDictionary")
// menu
web.Router("/v1/background/menus/", &backgroud_client.MenuController{}, "Post:CreateMenu")
web.Router("/v1/background/menus/:menuId", &backgroud_client.MenuController{}, "Put:UpdateMenu")
web.Router("/v1/background/menus/:menuId", &backgroud_client.MenuController{}, "Get:GetMenu")
web.Router("/v1/background/menus/search", &backgroud_client.MenuController{}, "Post:SearchMenu")
web.Router("/v1/background/menus/batch-delete", &backgroud_client.MenuController{}, "Post:BatchDeleteMenu")
web.Router("/v1/background/menus/batch-enable", &backgroud_client.MenuController{}, "Post:BatchEnableMenu")
// company
//web.Router("/v1/background/company/", &backgroud_client.CompanyController{}, "Post:CreateCompany")
web.Router("/v1/background/company/:companyId", &backgroud_client.CompanyController{}, "Put:UpdateCompany")
web.Router("/v1/background/company/:companyId", &backgroud_client.CompanyController{}, "Get:GetCompany")
web.Router("/v1/background/company/search", &backgroud_client.CompanyController{}, "Post:SearchCompany")
web.Router("/v1/background/company/:companyId/audit", &backgroud_client.CompanyController{}, "Post:AuditCompany")
web.Router("/v1/background/company/:companyId/enable", &backgroud_client.CompanyController{}, "Post:EnableCompany")
// user
web.Router("/v1/background/user/search", &backgroud_client.UserController{}, "Post:SearchUser")
web.Router("/v1/background/user/enable", &backgroud_client.UserController{}, "Post:EnableUser")
web.Router("/v1/background/user/reset-password", &backgroud_client.UserController{}, "Post:ResetPassword")
// admin
web.Router("/v1/background/user-admin/search", &backgroud_client.UserController{}, "Post:SearchAdminUser")
web.Router("/v1/background/user-admin/:userId", &backgroud_client.UserController{}, "Get:GetAdminUser")
web.Router("/v1/background/user-admin/:userId", &backgroud_client.UserController{}, "Put:UpdateAdminUser")
web.Router("/v1/background/user-admin/", &backgroud_client.UserController{}, "Post:CreateAdminUser")
web.Router("/v1/background/user-admin/enable", &backgroud_client.UserController{}, "Post:EnableAdminUser")
web.Router("/v1/background/user-admin/reset-password", &backgroud_client.UserController{}, "Post:ResetPassword")
web.Router("/v1/background/auth/login/pwd", &backgroud_client.AuthController{}, "Post:LoginPwd")
web.Router("/v1/background/auth/user-info", &backgroud_client.UserController{}, "Post:GetAdminUserInfo")
web.Router("/v1/background/auth/user-menu", &web_client.MenuController{}, "Post:MenuSearch")
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers/backgroud_client"
)
func init() {
web.Router("/v1/background/dictionary/", &backgroud_client.DictionaryController{}, "Post:CreateDictionary")
web.Router("/v1/background/dictionary/:dictionaryId", &backgroud_client.DictionaryController{}, "Put:UpdateDictionary")
web.Router("/v1/background/dictionary/:dictionaryId", &backgroud_client.DictionaryController{}, "Get:GetDictionary")
web.Router("/v1/background/dictionary/search", &backgroud_client.DictionaryController{}, "Post:ListDictionary")
web.Router("/v1/background/dictionary/remove", &backgroud_client.DictionaryController{}, "Post:RemoveDictionary")
}
... ... @@ -28,6 +28,7 @@ func init() {
web.Router("/v1/user/cooperation-org", &mobile_client.UserController{}, "Post:CooperationOrg")
// 特殊处理
web.Router("/v1/user/department-users", &mobile_client.UserController{}, "Post:DepartmentUsers") //公用的
web.Router("/v1/app/orgs/department-users", &mobile_client.UserController{}, "Post:DepartmentUsers")
web.Router("/v1/web/orgs/department-users", &web_client.OrgController{}, "Post:DepartmentUsers")
}
... ...
... ... @@ -8,6 +8,12 @@ import (
func init() {
web.Router("/v1/web/excel/export/company-user", &web_client.ExcelDataController{}, "Post:ExportCompanyUser")
web.Router("/v1/web/excel/export/cooperation-user", &web_client.ExcelDataController{}, "Post:ExportCooperationUser")
web.Router("/v1/web/excel/export/manufacture-products", &web_client.ExcelDataController{}, "Post:ExportProducts")
web.Router("/v1/web/excel/export/manufacture-employee-productive", &web_client.ExcelDataController{}, "Post:ExportManufactureEmployeeProductive")
web.Router("/v1/web/excel/export/manufacture-workshop-productive", &web_client.ExcelDataController{}, "Post:ExportManufactureWorkshopProductive")
web.Router("/v1/web/excel/export/manufacture-employee-attendance-statics", &web_client.ExcelDataController{}, "Post:ExportManufactureEmployeeAttendanceStatics")
web.Router("/v1/web/excel/export/manufacture-workshop-attendance-statics", &web_client.ExcelDataController{}, "Post:ExportManufactureWorkshopAttendanceStatics")
web.Router("/v1/web/excel/import/dividends-orders", &web_client.ExcelDataController{}, "Post:ImportDividendsOrder")
web.Router("/v1/web/excel/import/dividends-returned-orders", &web_client.ExcelDataController{}, "Post:ImportDividendsReturnedOrder")
... ... @@ -15,4 +21,7 @@ func init() {
web.Router("/v1/web/file-import", &web_client.ExcelDataController{}, "Post:FileImport")
web.Router("/v1/web/file-export", &web_client.ExcelDataController{}, "Post:FileExport")
web.Router("/v1/web/file-import-template/:code", &web_client.ExcelDataController{}, "Get:FileImportTemplate")
web.Router("/v1/web/file-export/fields/:code", &web_client.ExcelDataController{}, "Get:GetExcelDataFields")
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/middleware"
)
func init() {
// 车间列表
web.Post("/v1/manufacture-weigh/workshops/selector", middleware.RedirectManufactureWeigh())
// 车间员工
web.Post("/v1/manufacture-weigh/product-groups/employees", middleware.RedirectManufactureWeigh())
// 生产批次列表
web.Post("/v1/manufacture-weigh/product-plans/search", middleware.RedirectManufactureWeigh())
// 物料列表
web.Post("/v1/manufacture-weigh/unit-conversions/materials", middleware.RedirectManufactureWeigh())
// 领料
web.Post("/v1/manufacture-weigh/product-plans/receive-material", middleware.RedirectManufactureWeigh())
// 退料
web.Post("/v1/manufacture-weigh/product-plans/return-material", middleware.RedirectManufactureWeigh())
// 提交二级品
web.Post("/v1/manufacture-weigh/product-plans/submit-product-record", middleware.RedirectManufactureWeigh())
// 车间员工
web.Post("/v1/manufacture-weigh/product-groups/employee-signing", middleware.RedirectManufactureWeigh())
// 车间生产效率
web.Post("/v1/manufacture-weigh/statistics/workshop-production-efficiency-statistics", middleware.RedirectManufactureWeigh())
// 设备运行信息
web.Post("/v1/manufacture-weigh/statistics/device-running-info", middleware.RedirectManufactureWeigh())
// 设备生产效率
web.Post("/v1/manufacture-weigh/statistics/device-production-efficiency-statistics", middleware.RedirectManufactureWeigh())
web.Post("/v1/manufacture-weigh/statistics/internal/:actionType", middleware.RedirectManufactureWeigh())
}
... ...
package oss
import (
"bytes"
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
)
var snow, _ = snowflake.NewIdWorker(1)
func UploadOss(data []byte) (string, error) {
client, err := oss.New("oss-cn-shenzhen.aliyuncs.com", constant.OssAccessKey, constant.OssSecret)
if err != nil {
return "", err
}
bucket, err := client.Bucket(constant.OssBucket)
if err != nil {
return "", err
}
fileId, err := snow.NextId()
if err != nil {
return "", err
}
fileName := "costs/" + fmt.Sprintf("%v", fileId)
err = bucket.PutObject(fileName, bytes.NewBuffer(data))
return constant.OssDomain +"/"+ fileName, err
}
\ No newline at end of file
... ...
package oss
import (
"fmt"
"io/ioutil"
"testing"
)
func TestOss(t *testing.T){
mBytes,_:=ioutil.ReadFile("./test.png")
result,err := UploadOss(mBytes)
fmt.Println(result,err)
}
\ No newline at end of file
... ...