作者 yangfu

init

正在显示 128 个修改的文件 包含 6223 行增加0 行删除
# Compiled Object codefiles, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
.log
.idea
*.tmp
\ No newline at end of file
... ...
FROM golang:latest
MAINTAINER mmm-go-pp <>
ENV APP_DIR $GOPATH/src/partner01
RUN mkdir -p $APP_DIR
WORKDIR $APP_DIR/
COPY ./pkg pkg
COPY ./conf conf
COPY ./go.mod go.mod
COPY ./go.sum go.sum
COPY ./main.go main.go
RUN ["ln","-sf","/usr/share/zoneinfo/Asia/Shanghai","/etc/localtime"]
ENV GO111MODULE on
ENV GOPROXY https://goproxy.io
RUN ["go","mod","tidy"]
RUN ["ls"]
RUN ["go","build"]
ENTRYPOINT ["./partner01"]
\ No newline at end of file
... ...
#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n <replace-your-k8s-namespace> get pods | grep -q partner01
if [ "$?" == "1" ];then
kubectl create -f /tmp/dev/partner01/partner01.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q partner01
if [ "$?" == "0" ];then
echo "partner01 service install success!"
else
echo "partner01 service install fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q partner01
if [ "$?" == "0" ];then
echo "partner01 deployment install success!"
else
echo "partner01 deployment install fail!"
fi
else
kubectl delete -f /tmp/dev/partner01/partner01.yaml
kubectl -n <replace-your-k8s-namespace> get svc | grep -q partner01
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get svc | grep -q partner01
done
kubectl -n <replace-your-k8s-namespace> get pods | grep -q partner01
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get pods | grep -q partner01
done
kubectl create -f /tmp/dev/partner01/partner01.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q partner01
if [ "$?" == "0" ];then
echo "partner01 service update success!"
else
echo "partner01 service update fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q partner01
if [ "$?" == "0" ];then
echo "partner01 deployment update success!"
else
echo "partner01 deployment update fail!"
fi
fi
\ No newline at end of file
... ...
apiVersion: v1
kind: Service
metadata:
name: partner01
namespace: <replace-your-k8s-namespace>
labels:
k8s-app: partner01
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
selector:
k8s-app: partner01
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: partner01
namespace: <replace-your-k8s-namespace>
labels:
k8s-app: partner01
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: partner01
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference: {}
weight: 100
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- cn-hangzhou.i-bp1djh1xn7taumbue1ze
- cn-hangzhou.i-bp1djh1xn7taumbue1zd
- cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
- cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
containers:
- name: partner01
image: 192.168.0.243:5000/mmm/partner01:dev
imagePullPolicy: Always
ports:
- containerPort: 8082
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
env:
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
value: "1000"
volumes:
- name: accesslogs
emptyDir: {}
\ No newline at end of file
... ...
module gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway
go 1.16
require (
github.com/ajg/form v1.5.1 // indirect
github.com/beego/beego/v2 v2.0.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/gavv/httpexpect v2.0.0+incompatible
github.com/go-pg/pg/v10 v10.9.0
github.com/google/go-querystring v1.1.0 // indirect
github.com/imkira/go-interpol v1.1.0 // indirect
github.com/linmadan/egglib-go v0.0.0-20210313060205-8b5e456b11f7
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/moul/http2curl v1.0.0 // indirect
github.com/onsi/ginkgo v1.15.2
github.com/onsi/gomega v1.11.0
github.com/sergi/go-diff v1.2.0 // indirect
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/tiptok/gocomm v1.0.12
github.com/valyala/fasthttp v1.23.0 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
)
//replace github.com/tiptok/gocomm v1.0.11 => F:\go\src\learn_project\gocomm
... ...
此 diff 太大无法显示。
package main
import (
"github.com/beego/beego/v2/server/web"
"github.com/tiptok/gocomm/pkg/log"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/gateway"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego"
)
func main() {
log.Info("start...")
web.Run()
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type AccessTokenCommand struct {
// Attribute描述
AuthCode string `json:"authCode,omitempty"`
}
func (accessTokenCommand *AccessTokenCommand) Valid(validation *validation.Validation) {
}
func (accessTokenCommand *AccessTokenCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(accessTokenCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type ChangePasswordCommand struct {
// 旧密码
OldPwd string `json:"oldPwd,omitempty"`
// 新密码
NewPwd string `json:"newPwd,omitempty"`
// 确认密码
ConfirmPwd string `json:"confirmPwd,omitempty"`
// 手机号
Phone string `json:"phone,omitempty"`
}
func (changePasswordCommand *ChangePasswordCommand) Valid(validation *validation.Validation) {
}
func (changePasswordCommand *ChangePasswordCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(changePasswordCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type LoginByCompanyCommand struct {
// 1.高管 2.合伙人 4:游客
UserType int `json:"userType" valid:"Required"`
// 凭证
Credentials string `json:"credentials" valid:"Required"`
// 用户id
UserId int64 `json:"userId" valid:"Required"`
}
func (loginByCompanyCommand *LoginByCompanyCommand) Valid(validation *validation.Validation) {
}
func (loginByCompanyCommand *LoginByCompanyCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(loginByCompanyCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type RefreshTokenCommand struct {
// refreshToken
RefreshToken string `json:"refreshToken,omitempty"`
}
func (refreshTokenCommand *RefreshTokenCommand) Valid(validation *validation.Validation) {
}
func (refreshTokenCommand *RefreshTokenCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(refreshTokenCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type RevokeCommand struct {
}
func (revokeCommand *RevokeCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (revokeCommand *RevokeCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(revokeCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type SendSmsCodeCommand struct {
// 手机号
Phone string `json:"phone,omitempty"`
}
func (sendSmsCodeCommand *SendSmsCodeCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (sendSmsCodeCommand *SendSmsCodeCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(sendSmsCodeCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type LoginQuery struct {
// 手机号
Phone string `json:"phone,omitempty"`
// signInPassword(密码登录) 或 signInCaptcha(验证码登录)或signInCredentials(凭证登录)
GrantType string `json:"grantType,omitempty"`
// 密码(grantType = signInPassword)
Password string `json:"password,omitempty"`
// 验证码(grantType = signInCaptcha)
Captcha string `json:"captcha,omitempty"`
// 凭证(grantType = signInCredentials)
Credentials string `json:"credentials,omitempty"`
}
func (loginQuery *LoginQuery) Valid(validation *validation.Validation) {
}
func (loginQuery *LoginQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(loginQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/tiptok/gocomm/gs"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/auth/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/auth/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/gateway"
)
// 认证服务
type AuthService struct {
}
// 用户按公司登录
func (authService *AuthService) AccessToken(accessTokenCommand *command.AccessTokenCommand) (interface{}, error) {
if err := accessTokenCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.AuthsAccessToken, gs.WithJsonObject(accessTokenCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
// 修改手机号密码
func (authService *AuthService) ChangePassword(changePasswordCommand *command.ChangePasswordCommand) (interface{}, error) {
if err := changePasswordCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.AuthsChangePhonePassword, gs.WithJsonObject(changePasswordCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
// 用户登录 返回有权限的公司列表
func (authService *AuthService) Login(loginQuery *query.LoginQuery) (interface{}, error) {
if err := loginQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.AuthsLogin, gs.WithJsonObject(loginQuery))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
// 用户按公司登录
func (authService *AuthService) LoginByCompany(loginByCompanyCommand *command.LoginByCompanyCommand) (interface{}, error) {
if err := loginByCompanyCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.AuthsLoginByCompany, gs.WithJsonObject(loginByCompanyCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
// 更新授权令牌accessToken
func (authService *AuthService) RefreshToken(refreshTokenCommand *command.RefreshTokenCommand) (interface{}, error) {
if err := refreshTokenCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.AuthsRefreshToken, gs.WithJsonObject(refreshTokenCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
// 注销登录
func (authService *AuthService) Revoke(revokeCommand *command.RevokeCommand) (interface{}, error) {
if err := revokeCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.AuthsRevoke, gs.WithJsonObject(revokeCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
// 发送验证码
func (authService *AuthService) SendSmsCode(sendSmsCodeCommand *command.SendSmsCodeCommand) (interface{}, error) {
if err := sendSmsCodeCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.AuthsSendSmsCode, gs.WithJsonObject(sendSmsCodeCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
func NewAuthService(options map[string]interface{}) *AuthService {
newAuthService := &AuthService{}
return newAuthService
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type ConvertCompanyStatusCommand struct {
// 公司Id
CompanyId int64 `json:"companyId" valid:"Required"`
// 状态 1正常 2禁用
Status int64 `json:"status" valid:"Required"`
}
func (convertCompanyStatusCommand *ConvertCompanyStatusCommand) Valid(validation *validation.Validation) {
// _ = validation.SetError("CustomValid", "未实现的自定义认证")
}
func (convertCompanyStatusCommand *ConvertCompanyStatusCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(convertCompanyStatusCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type CreateCompanyCommand struct {
// 公司名称
Name string `json:"name" valid:"Required"`
// 公司简称
Abbreviation string `json:"abbreviation" valid:"Required"`
// 状态 1正常 2禁用
Status int64 `json:"status" valid:"Required"`
// 备注
Remarks string `json:"remarks,omitempty"`
// 公司主管理员账号
UserAccount string `json:"userAccount" valid:"Required"`
// 公司主管理员姓名
UserName string `json:"userName" valid:"Required"`
}
func (createCompanyCommand *CreateCompanyCommand) Valid(validation *validation.Validation) {
// _ = validation.SetError("CustomValid", "未实现的自定义认证")
}
func (createCompanyCommand *CreateCompanyCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createCompanyCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type RemoveCompanyCommand struct {
// 公司Id
CompanyId int64 `json:"companyId" 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 {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type SetCompanyAdminCommand struct {
// 公司Id
CompanyId int64 `json:"companyId" valid:"Required"`
// 公司主管理员账号
UserAccount string `json:"userAccount" valid:"Required"`
// 公司主管理员姓名
UserName string `json:"userName" valid:"Required"`
}
func (setCompanyAdminCommand *SetCompanyAdminCommand) Valid(validation *validation.Validation) {
// _ = validation.SetError("CustomValid", "未实现的自定义认证")
}
func (setCompanyAdminCommand *SetCompanyAdminCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(setCompanyAdminCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type UpdateCompanyCommand struct {
// 公司Id
CompanyId int64 `json:"companyId" valid:"Required"`
// 公司名称
Name string `json:"name,omitempty"`
// 公司简称
Abbreviation string `json:"abbreviation,omitempty"`
// 状态 1正常 2禁用
Status int64 `json:"status,omitempty"`
// 备注
Remarks string `json:"remarks,omitempty"`
// 公司主管理员账号
UserAccount string `json:"userAccount,omitempty"`
// 公司主管理员姓名
UserName string `json:"userName,omitempty"`
}
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 {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type GetCompanyQuery struct {
// 公司Id
CompanyId int64 `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 {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type ListCompanyQuery struct {
// 查询偏离量
Offset int `json:"offset" valid:"Required"`
// 查询限制
Limit int `json:"limit" valid:"Required"`
}
func (listCompanyQuery *ListCompanyQuery) Valid(validation *validation.Validation) {
// _ = validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listCompanyQuery *ListCompanyQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listCompanyQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"github.com/tiptok/gocomm/common"
"github.com/tiptok/gocomm/gs"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/company/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/company/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/gateway"
)
// 公司服务
type CompanyService struct {
}
// 公司状态转换 禁用、启用
func (companyService *CompanyService) ConvertCompanyStatus(convertCompanyStatusCommand *command.ConvertCompanyStatusCommand) (interface{}, error) {
if err := convertCompanyStatusCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var companyRepository domain.CompanyRepository
if value, err := factory.CreateCompanyRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
companyRepository = value
}
company, err := companyRepository.FindOne(map[string]interface{}{"companyId": convertCompanyStatusCommand.CompanyId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if company == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(convertCompanyStatusCommand.CompanyId)))
}
if err := company.Update(tool_funs.SimpleStructToMap(convertCompanyStatusCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if company, err := companyRepository.Save(company); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return company, nil
}
}
// 创建
func (companyService *CompanyService) CreateCompany(createCompanyCommand *command.CreateCompanyCommand) (interface{}, error) {
if err := createCompanyCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
return gateway.Partner01Service.CompanyCreate(createCompanyCommand)
}
// 返回
func (companyService *CompanyService) GetCompany(getCompanyQuery *query.GetCompanyQuery) (interface{}, error) {
if err := getCompanyQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
return gateway.Partner01Service.CompanyGet(common.LoadCustomFieldToMap(getCompanyQuery, "CompanyId"))
}
// 返回列表
func (companyService *CompanyService) ListCompany(listCompanyQuery *query.ListCompanyQuery) (interface{}, error) {
if err := listCompanyQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.CompanyList, gs.WithPathQuery(common.ObjectToMap(listCompanyQuery)))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
// 移除
func (companyService *CompanyService) RemoveCompany(removeCompanyCommand *command.RemoveCompanyCommand) (interface{}, error) {
if err := removeCompanyCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.CompanyRemove, gs.WithPathParam(common.ObjectToMap(removeCompanyCommand)))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
// 设置公司管理员
func (companyService *CompanyService) SetCompanyAdmin(setCompanyAdminCommand *command.SetCompanyAdminCommand) (interface{}, error) {
if err := setCompanyAdminCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var companyRepository domain.CompanyRepository
if value, err := factory.CreateCompanyRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
companyRepository = value
}
company, err := companyRepository.FindOne(map[string]interface{}{"companyId": setCompanyAdminCommand.CompanyId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if company == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(setCompanyAdminCommand.CompanyId)))
}
newCompanyAdmin := &domain.CompanyAdmin{
UserAccount: setCompanyAdminCommand.UserAccount, // 用户手机号
UserName: setCompanyAdminCommand.UserName, // 用户名称
}
// 更改公司管理员信息
if err := company.SetCompanyAdmin(newCompanyAdmin); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if company, err := companyRepository.Save(company); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
// todo 更改公司管理员
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return company, nil
}
}
// 更新
func (companyService *CompanyService) UpdateCompany(updateCompanyCommand *command.UpdateCompanyCommand) (interface{}, error) {
if err := updateCompanyCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
data, err := gateway.Partner01Service.Invoke(gateway.CompanyGet, gs.WithPathParam(common.ObjectToMap(updateCompanyCommand)))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
func NewCompanyService(options map[string]interface{}) *CompanyService {
newCompanyService := &CompanyService{}
return newCompanyService
}
... ...
package factory
import (
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain/service"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/domainService"
)
func CreateShippingService(options map[string]interface{}) (service.ShippingGoodsService, error) {
var transactionContext *pgTransaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pgTransaction.TransactionContext)
}
return domainService.NewShippingGoodsService(transactionContext)
}
func CreateReceivingService(options map[string]interface{}) (service.ReceivingGoodsService, error) {
var transactionContext *pgTransaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pgTransaction.TransactionContext)
}
return domainService.NewReceivingGoodsService(transactionContext)
}
func CreateCancelOrderService(options map[string]interface{}) (service.CancelOrderService, error) {
var transactionContext *pgTransaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pgTransaction.TransactionContext)
}
return domainService.NewCancelOrderService(transactionContext)
}
func CreateReturnGoodsService(options map[string]interface{}) (service.ReturnGoodsService, error) {
var transactionContext *pgTransaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pgTransaction.TransactionContext)
}
return domainService.NewReturnGoodsService(transactionContext)
}
... ...
package factory
import (
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/repository"
)
func CreatePartnerCategoryRepository(options map[string]interface{}) (domain.PartnerCategoryRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewPartnerCategoryRepository(transactionContext)
}
func CreatePermissionRepository(options map[string]interface{}) (domain.PermissionRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewPermissionRepository(transactionContext)
}
func CreateUserAuthRepository(options map[string]interface{}) (domain.UserAuthRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewUserAuthRepository(transactionContext)
}
func CreateOrderRepository(options map[string]interface{}) (domain.OrderRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewOrderRepository(transactionContext)
}
func CreateGoodsRepository(options map[string]interface{}) (domain.GoodsRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewGoodsRepository(transactionContext)
}
func CreateUserRepository(options map[string]interface{}) (domain.UserRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewUserRepository(transactionContext)
}
func CreateCompanyRepository(options map[string]interface{}) (domain.CompanyRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewCompanyRepository(transactionContext)
}
... ...
package factory
import (
"github.com/linmadan/egglib-go/core/application"
pG "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
func CreateTransactionContext(options map[string]interface{}) (application.TransactionContext, error) {
return pG.NewPGTransactionContext(pg.DB), nil
}
... ...
package command
import (
"fmt"
"time"
"github.com/beego/beego/v2/core/validation"
)
type CancelOrderCommand struct {
// 订单ID
OrderId int64 `json:"orderId" valid:"Required"`
// 订单编号
OrderNo string `json:"orderNo" valid:"Required"`
// 公司id
CompanyId int64 `json:"companyId" valid:"Required"`
// 是否是公司负责人
IsPrincipal bool `json:"isPrincipal" valid:"Required"`
// 统一用户id
Uid int64 `json:"uid" valid:"Required"`
// 用户账号
UserAccount string `json:"userAccount" valid:"Required"`
// 用户头像URL
UserAvatarUrl string `json:"userAvatarUrl" valid:"Required"`
// 用户名称
UserName string `json:"userName" valid:"Required"`
// 邮件地址
Email string `json:"email" valid:"Required"`
// 性别
Gender int `json:"gender" valid:"Required"`
// 入职时间
EntryTime time.Time `json:"entryTime" valid:"Required"`
// 分机
Extension string `json:"extension" valid:"Required"`
// 工作地
Workplace string `json:"workplace" valid:"Required"`
// 私人电话
PrivateNumber string `json:"privateNumber" valid:"Required"`
// 工号
JobNumber string `json:"jobNumber" valid:"Required"`
}
func (cancelOrderCommand *CancelOrderCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (cancelOrderCommand *CancelOrderCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(cancelOrderCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type CreateOrderCommand struct {
// 订单编号
OrderNo string `json:"orderNo" valid:"Required"`
// 公司Id
CompanyId int64 `json:"companyId" valid:"Required"`
// 买家名称
BuyerName string `json:"buyerName,omitempty"`
// 联系信息
ContactInfo string `json:"contactInfo,omitempty"`
// 发货地址
ShippingAddress string `json:"shippingAddress,omitempty"`
// 订单商品总数
OrderNum int64 `json:"orderNum" valid:"Required"`
// 订单总价
TotalPrice float64 `json:"totalPrice" valid:"Required"`
}
func (createOrderCommand *CreateOrderCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (createOrderCommand *CreateOrderCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createOrderCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type DrawDividendsCommand struct {
// 参与分红的合伙人
PartnerId int64 `json:"partnerId" valid:"Required"`
// 进行分红的订单编号
OrderNo string `json:"orderNo" valid:"Required"`
}
func (drawDividendsCommand *DrawDividendsCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (drawDividendsCommand *DrawDividendsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(drawDividendsCommand)
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"
"time"
"github.com/beego/beego/v2/core/validation"
)
type ReceiveGoodsCommand struct {
// 订单号
OrderNo string `json:"orderNo" valid:"Required"`
// 是否是公司负责人
IsPrincipal bool `json:"isPrincipal" valid:"Required"`
// 统一用户id
Uid int64 `json:"uid" valid:"Required"`
// 用户账号
UserAccount string `json:"userAccount" valid:"Required"`
// 用户头像URL
UserAvatarUrl string `json:"userAvatarUrl" valid:"Required"`
// 用户名称
UserName string `json:"userName" valid:"Required"`
// 邮件地址
Email string `json:"email" valid:"Required"`
// 性别
Gender int `json:"gender" valid:"Required"`
// 入职时间
EntryTime time.Time `json:"entryTime" valid:"Required"`
// 分机
Extension string `json:"extension" valid:"Required"`
// 工作地
Workplace string `json:"workplace" valid:"Required"`
// 私人电话
PrivateNumber string `json:"privateNumber" valid:"Required"`
// 工号
JobNumber string `json:"jobNumber" valid:"Required"`
// 公司id
CompanyId int64 `json:"companyId" valid:"Required"`
}
func (receiveGoodsCommand *ReceiveGoodsCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (receiveGoodsCommand *ReceiveGoodsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(receiveGoodsCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type RemoveOrderCommand struct {
// 订单id
OrderId int64 `json:"orderId" valid:"Required"`
}
func (removeOrderCommand *RemoveOrderCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeOrderCommand *RemoveOrderCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeOrderCommand)
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"
"time"
"github.com/beego/beego/v2/core/validation"
)
type ReturnGoodsCommand struct {
// 订单号
OrderNo string `json:"orderNo" valid:"Required"`
// 是否是公司负责人
IsPrincipal bool `json:"isPrincipal" valid:"Required"`
// 统一用户id
Uid int64 `json:"uid" valid:"Required"`
// 用户账号
UserAccount string `json:"userAccount" valid:"Required"`
// 用户头像URL
UserAvatarUrl string `json:"userAvatarUrl" valid:"Required"`
// 用户名称
UserName string `json:"userName" valid:"Required"`
// 邮件地址
Email string `json:"email" valid:"Required"`
// 性别
Gender int `json:"gender" valid:"Required"`
// 入职时间
EntryTime time.Time `json:"entryTime" valid:"Required"`
// 分机
Extension string `json:"extension" valid:"Required"`
// 工作地
Workplace string `json:"workplace" valid:"Required"`
// 私人电话
PrivateNumber string `json:"privateNumber" valid:"Required"`
// 工号
JobNumber string `json:"jobNumber" valid:"Required"`
// 公司id
CompanyId int64 `json:"companyId" valid:"Required"`
}
func (returnGoodsCommand *ReturnGoodsCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (returnGoodsCommand *ReturnGoodsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(returnGoodsCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type ShippingGoodsCommand struct {
// 订单ID
OrderId int `json:"orderId" valid:"Required"`
// 发货单号
DeliveryCode string `json:"deliveryCode" valid:"Required"`
// 订单编号
OrderNo string `json:"orderNo" valid:"Required"`
// 订单数量
OrderNum int64 `json:"orderNum" valid:"Required"`
}
func (shippingGoodsCommand *ShippingGoodsCommand) Valid(validation *validation.Validation) {
//_ = validation.SetError("CustomValid", "未实现的自定义认证")
}
func (shippingGoodsCommand *ShippingGoodsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(shippingGoodsCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type UpdateOrderCommand struct {
// 订单id
OrderId int64 `json:"orderId" valid:"Required"`
}
func (updateOrderCommand *UpdateOrderCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (updateOrderCommand *UpdateOrderCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateOrderCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type GetOrderQuery struct {
// 订单id
OrderId int64 `json:"orderId" valid:"Required"`
}
func (getOrderQuery *GetOrderQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getOrderQuery *GetOrderQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getOrderQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type ListOrderQuery struct {
// 查询偏离量
Offset int `json:"offset" valid:"Required"`
// 查询限制
Limit int `json:"limit" valid:"Required"`
}
func (listOrderQuery *ListOrderQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listOrderQuery *ListOrderQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listOrderQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/order/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/order/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"strconv"
)
// 订单基础服务
type OrderService struct {
}
// 取消订单
func (orderService *OrderService) CancelOrder(cancelCommand *command.CancelOrderCommand) (interface{}, error) {
if err := cancelCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 创建订单增删改查
func (orderService *OrderService) CreateOrder(createOrderCommand *command.CreateOrderCommand) (interface{}, error) {
if err := createOrderCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
newOrder := &domain.Order{
OrderNo: createOrderCommand.OrderNo,
CompanyId: createOrderCommand.CompanyId,
Buyer: &domain.BuyerInfo{
BuyerName: createOrderCommand.BuyerName,
},
TotalPrice: createOrderCommand.TotalPrice,
}
var orderRepository domain.OrderRepository
if value, err := factory.CreateOrderRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
}
if order, err := orderRepository.Save(newOrder); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return order, nil
}
}
// 订单分红服务
func (orderService *OrderService) DrawDividends(drawDividendsCommand *command.DrawDividendsCommand) (interface{}, error) {
if err := drawDividendsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 返回订单增删改查
func (orderService *OrderService) GetOrder(getOrderQuery *query.GetOrderQuery) (interface{}, error) {
if err := getOrderQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
var orderRepository domain.OrderRepository
if value, err := factory.CreateOrderRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
}
order, err := orderRepository.FindOne(map[string]interface{}{"orderId": getOrderQuery.OrderId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if order == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", strconv.FormatInt(getOrderQuery.OrderId, 10)))
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return order, nil
}
}
// 返回订单增删改查列表
func (orderService *OrderService) ListOrder(listOrderQuery *query.ListOrderQuery) (interface{}, error) {
if err := listOrderQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
var orderRepository domain.OrderRepository
if value, err := factory.CreateOrderRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
}
if count, orders, err := orderRepository.Find(tool_funs.SimpleStructToMap(listOrderQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"orders": orders,
}, nil
}
}
// 订单收货服务
func (orderService *OrderService) ReceiveGoods(receivingCommand *command.ReceiveGoodsCommand) (interface{}, error) {
if err := receivingCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 移除订单增删改查
func (orderService *OrderService) RemoveOrder(removeOrderCommand *command.RemoveOrderCommand) (interface{}, error) {
if err := removeOrderCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
var orderRepository domain.OrderRepository
if value, err := factory.CreateOrderRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
}
order, err := orderRepository.FindOne(map[string]interface{}{"orderId": removeOrderCommand.OrderId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if order == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", strconv.FormatInt(removeOrderCommand.OrderId, 10)))
}
if order, err := orderRepository.Remove(order); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return order, nil
}
}
// 订单退货服务
func (orderService *OrderService) ReturnGoods(returnGoodsCommand *command.ReturnGoodsCommand) (interface{}, error) {
if err := returnGoodsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 订单发货服务
func (orderService *OrderService) ShippingGoods(shippingGoodsCommand *command.ShippingGoodsCommand) (interface{}, error) {
if err := shippingGoodsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 更新订单增删改查
func (orderService *OrderService) UpdateOrder(updateOrderCommand *command.UpdateOrderCommand) (interface{}, error) {
if err := updateOrderCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
var orderRepository domain.OrderRepository
if value, err := factory.CreateOrderRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
}
order, err := orderRepository.FindOne(map[string]interface{}{"orderId": updateOrderCommand.OrderId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if order == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", strconv.FormatInt(updateOrderCommand.OrderId, 10)))
}
if err := order.Update(tool_funs.SimpleStructToMap(updateOrderCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if order, err := orderRepository.Save(order); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return order, nil
}
}
func NewOrderService(options map[string]interface{}) *OrderService {
newOrderService := &OrderService{}
return newOrderService
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type CreatePartnerCommand struct {
}
func (createPartnerCommand *CreatePartnerCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (createPartnerCommand *CreatePartnerCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createPartnerCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type RemovePartnerCommand struct {
// 合伙人id
PartnerId int64 `json:"partnerId" valid:"Required"`
}
func (removePartnerCommand *RemovePartnerCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removePartnerCommand *RemovePartnerCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removePartnerCommand)
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"
"github.com/beego/beego/v2/core/validation"
)
type UpdatePartnerCommand struct {
// 合伙人id
PartnerId int64 `json:"partnerId" valid:"Required"`
}
func (updatePartnerCommand *UpdatePartnerCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (updatePartnerCommand *UpdatePartnerCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updatePartnerCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type GetPartnerQuery struct {
// 合伙人id
PartnerId int64 `json:"partnerId" valid:"Required"`
}
func (getPartnerQuery *GetPartnerQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getPartnerQuery *GetPartnerQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getPartnerQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type ListPartnerQuery struct {
// 查询偏离量
Offset int `json:"offset" valid:"Required"`
// 查询限制
Limit int `json:"limit" valid:"Required"`
}
func (listPartnerQuery *ListPartnerQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listPartnerQuery *ListPartnerQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listPartnerQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type PartnerCategoriesQuery struct {
}
func (partnerCategoriesQuery *PartnerCategoriesQuery) Valid(validation *validation.Validation) {
}
func (partnerCategoriesQuery *PartnerCategoriesQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(partnerCategoriesQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
//"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/factory"
//"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/partner/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/partner/query"
//"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
)
// 合伙人服务
type PartnerService struct {
}
//// 创建合伙人增删改查
//func (partnerService *PartnerService) CreatePartner(createPartnerCommand *command.CreatePartnerCommand) (interface{}, error) {
// if err := createPartnerCommand.ValidateCommand(); err != nil {
// return nil, application.ThrowError(application.ARG_ERROR, err.Error())
// }
// transactionContext, err := factory.CreateTransactionContext(nil)
// if err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// if err := transactionContext.StartTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
// newPartner := &domain.Partner{}
// var partnerRepository partner.PartnerRepository
// if value, err := factory.CreatePartnerRepository(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// partnerRepository = value
// }
// if partner, err := partnerRepository.Save(newPartner); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// if err := transactionContext.CommitTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// return partner, nil
// }
//}
//
//// 返回合伙人增删改查
//func (partnerService *PartnerService) GetPartner(getPartnerQuery *query.GetPartnerQuery) (interface{}, error) {
// if err := getPartnerQuery.ValidateQuery(); err != nil {
// return nil, application.ThrowError(application.ARG_ERROR, err.Error())
// }
// transactionContext, err := factory.CreateTransactionContext(nil)
// if err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// if err := transactionContext.StartTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
// var partnerRepository partner.PartnerRepository
// if value, err := factory.CreatePartnerRepository(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// partnerRepository = value
// }
// partner, err := partnerRepository.FindOne(map[string]interface{}{"partnerId": getPartnerQuery.PartnerId})
// if err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// }
// if partner == nil {
// return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getPartnerQuery.PartnerId)))
// } else {
// if err := transactionContext.CommitTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// return partner, nil
// }
//}
//
//// 返回合伙人增删改查列表
//func (partnerService *PartnerService) ListPartner(listPartnerQuery *query.ListPartnerQuery) (interface{}, error) {
// if err := listPartnerQuery.ValidateQuery(); err != nil {
// return nil, application.ThrowError(application.ARG_ERROR, err.Error())
// }
// transactionContext, err := factory.CreateTransactionContext(nil)
// if err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// if err := transactionContext.StartTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
// var partnerRepository partner.PartnerRepository
// if value, err := factory.CreatePartnerRepository(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// partnerRepository = value
// }
// if count, partners, err := partnerRepository.Find(tool_funs.SimpleStructToMap(listPartnerQuery)); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// if err := transactionContext.CommitTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// return map[string]interface{}{
// "count": count,
// "partners": partners,
// }, nil
// }
//}
// 合伙人分类列表
func (partnerService *PartnerService) PartnerCategories(partnerCategoriesQuery *query.PartnerCategoriesQuery) (interface{}, error) {
if err := partnerCategoriesQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
PartnerCategoryRepository, err := factory.CreatePartnerCategoryRepository(map[string]interface{}{"transactionContext": transactionContext})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
total, categories, err := PartnerCategoryRepository.Find(map[string]interface{}{})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{"total": total, "categories": categories}, nil
}
//// 移除合伙人增删改查
//func (partnerService *PartnerService) RemovePartner(removePartnerCommand *command.RemovePartnerCommand) (interface{}, error) {
// if err := removePartnerCommand.ValidateCommand(); err != nil {
// return nil, application.ThrowError(application.ARG_ERROR, err.Error())
// }
// transactionContext, err := factory.CreateTransactionContext(nil)
// if err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// if err := transactionContext.StartTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
// var partnerRepository partner.PartnerRepository
// if value, err := factory.CreatePartnerRepository(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// partnerRepository = value
// }
// partner, err := partnerRepository.FindOne(map[string]interface{}{"partnerId": removePartnerCommand.PartnerId})
// if err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// }
// if partner == nil {
// return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removePartnerCommand.PartnerId)))
// }
// if partner, err := partnerRepository.Remove(partner); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// if err := transactionContext.CommitTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// return partner, nil
// }
//}
//
//// 更新合伙人增删改查
//func (partnerService *PartnerService) UpdatePartner(updatePartnerCommand *command.UpdatePartnerCommand) (interface{}, error) {
// if err := updatePartnerCommand.ValidateCommand(); err != nil {
// return nil, application.ThrowError(application.ARG_ERROR, err.Error())
// }
// transactionContext, err := factory.CreateTransactionContext(nil)
// if err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// if err := transactionContext.StartTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
// var partnerRepository partner.PartnerRepository
// if value, err := factory.CreatePartnerRepository(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// partnerRepository = value
// }
// partner, err := partnerRepository.FindOne(map[string]interface{}{"partnerId": updatePartnerCommand.PartnerId})
// if err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// }
// if partner == nil {
// return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updatePartnerCommand.PartnerId)))
// }
// if err := partner.Update(tool_funs.SimpleStructToMap(updatePartnerCommand)); err != nil {
// return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
// }
// if partner, err := partnerRepository.Save(partner); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// } else {
// if err := transactionContext.CommitTransaction(); err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// }
// return partner, nil
// }
//}
func NewPartnerService(options map[string]interface{}) *PartnerService {
newPartnerService := &PartnerService{}
return newPartnerService
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type MenusQuery struct {
// 用户id
UserId int64 `json:"userId"`
}
func (menusQuery *MenusQuery) Valid(validation *validation.Validation) {
}
func (menusQuery *MenusQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(menusQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/permission/query"
)
// 权限服务
type PermissionService struct {
}
// 根据当前用户返回权限列表
func (permissionService *PermissionService) Menus(menusQuery *query.MenusQuery) (interface{}, error) {
if err := menusQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
PermissionRepository, err := factory.CreatePermissionRepository(map[string]interface{}{"transactionContext": transactionContext})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
total, permissions, err := PermissionRepository.Find(map[string]interface{}{})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{"total": total, "permissions": permissions}, nil
}
func NewPermissionService(options map[string]interface{}) *PermissionService {
newPermissionService := &PermissionService{}
return newPermissionService
}
... ...
package constant
import "os"
const SERVICE_NAME = "partner01"
var LOG_LEVEL = "debug"
func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
}
}
... ...
package constant
import "os"
var (
PARTER01_GATEWAY_ADDRESS = "http://127.0.0.1:8080"
)
func init() {
if os.Getenv("PARTER01_GATEWAY_ADDRESS") != "" {
PARTER01_GATEWAY_ADDRESS = os.Getenv("PARTER01_GATEWAY_ADDRESS")
}
}
... ...
package constant
import "os"
var POSTGRESQL_DB_NAME = "partner01"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "eagle1010"
var POSTGRESQL_HOST = "114.55.200.59"
var POSTGRESQL_PORT = "31543"
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
func init() {
if os.Getenv("POSTGRESQL_DB_NAME") != "" {
POSTGRESQL_DB_NAME = os.Getenv("POSTGRESQL_DB_NAME")
}
if os.Getenv("POSTGRESQL_USER") != "" {
POSTGRESQL_USER = os.Getenv("POSTGRESQL_USER")
}
if os.Getenv("POSTGRESQL_PASSWORD") != "" {
POSTGRESQL_PASSWORD = os.Getenv("POSTGRESQL_PASSWORD")
}
if os.Getenv("POSTGRESQL_HOST") != "" {
POSTGRESQL_HOST = os.Getenv("POSTGRESQL_HOST")
}
if os.Getenv("POSTGRESQL_PORT") != "" {
POSTGRESQL_PORT = os.Getenv("POSTGRESQL_PORT")
}
if os.Getenv("DISABLE_CREATE_TABLE") != "" {
DISABLE_CREATE_TABLE = true
}
if os.Getenv("DISABLE_SQL_GENERATE_PRINT") != "" {
DISABLE_SQL_GENERATE_PRINT = true
}
}
... ...
package domain
import (
"github.com/dgrijalva/jwt-go"
eggJwt "github.com/linmadan/egglib-go/utils/jwt"
"time"
)
const (
secret = "$^%$Rdefault&*^(*&"
)
const (
AccessTokenExpire = 3600
)
type UserTokenClaim struct {
jwt.StandardClaims
UserId int64 `json:"userId"`
CompanyId int64 `json:"companyId"`
}
func NewUserTokenClaim(userId, companyId int64, expire int64) UserTokenClaim {
return UserTokenClaim{
UserId: userId,
CompanyId: companyId,
StandardClaims: jwt.StandardClaims{ExpiresAt: expire},
}
}
func SignToken(userId int64, companyId int64) string {
claim := NewUserTokenClaim(int64(userId), companyId, time.Now().Add(time.Second*AccessTokenExpire).Unix())
token, _ := eggJwt.Sign(claim, secret, "")
return token
}
func ValidToken(token string, claims *UserTokenClaim) (bool, error) {
result, c, err := eggJwt.Valid(token, claims, secret)
claims = c.Claims.(*UserTokenClaim)
return result, err
}
... ...
package domain
// 买家信息值对象
type BuyerInfo struct {
// 买家名称
BuyerName string `json:"buyerName"`
// 联系信息
ContactInfo string `json:"contactInfo"`
// 发货地址
ShippingAddress string `json:"shippingAddress"`
}
... ...
package domain
import "time"
// 公司信息
type Company struct {
// 公司Id
CompanyId int64 `json:"companyId"`
// 公司信息
CompanyInfo *CompanyInfo `json:"companyInfo"`
// 创建时间
CreateAt time.Time `json:"createAt"`
// 更新时间
UpdateAt time.Time `json:"updateAt"`
// 删除时间
DeleteAt time.Time `json:"deleteAt"`
}
type CompanyRepository interface {
Save(company *Company) (*Company, error)
Remove(company *Company) (*Company, error)
FindOne(queryOptions map[string]interface{}) (*Company, error)
Find(queryOptions map[string]interface{}) (int64, []*Company, error)
}
func (company *Company) Identify() interface{} {
if company.CompanyId == 0 {
return nil
}
return company.CompanyId
}
func (company *Company) Update(data map[string]interface{}) error {
if companyId, ok := data["companyId"]; ok {
company.CompanyId = companyId.(int64)
}
if name, ok := data["name"]; ok {
company.CompanyInfo.Name = name.(string)
}
if abbreviation, ok := data["abbreviation"]; ok {
company.CompanyInfo.Abbreviation = abbreviation.(string)
}
if logo, ok := data["logo"]; ok {
company.CompanyInfo.Logo = logo.(string)
}
if phone, ok := data["phone"]; ok {
company.CompanyInfo.Phone = phone.(string)
}
if status, ok := data["status"]; ok {
company.CompanyInfo.Status = status.(int64)
}
if remarks, ok := data["remarks"]; ok {
company.CompanyInfo.Remarks = remarks.(string)
}
if enable, ok := data["enable"]; ok {
company.CompanyInfo.Enable = enable.(int64)
}
if userAccount, ok := data["userAccount"]; ok {
company.CompanyInfo.Admin.UserAccount = userAccount.(string)
}
if userName, ok := data["userName"]; ok {
company.CompanyInfo.Admin.UserName = userName.(string)
}
if createAt, ok := data["createAt"]; ok {
company.CreateAt = createAt.(time.Time)
}
if updateAt, ok := data["updateAt"]; ok {
company.UpdateAt = updateAt.(time.Time)
}
if deleteAt, ok := data["deleteAt"]; ok {
company.DeleteAt = deleteAt.(time.Time)
}
return nil
}
// 更改公司管理员信息
func (company *Company) SetCompanyAdmin(admin *CompanyAdmin) error {
company.CompanyInfo.Admin = admin
return nil
}
... ...
package domain
// 公司信息
type CompanyInfo struct {
Name string `json:"name"` // 公司名称
Abbreviation string `json:"abbreviation"` // 公司简称
Logo string `json:"logo"` // 公司logo
Phone string `json:"phone"` // 公司联系电话
Status int64 `json:"status"` // 状态 1正常 2禁用
Remarks string `json:"remarks"` // 备注
Enable int64 `json:"enable"` // 是否有效【1:有效】【2:无效】
Admin *CompanyAdmin `json:"admin"` // 公司主管理员
}
// 公司管理员信息值对象
type CompanyAdmin struct {
UserAccount string `json:"userPhone"` // 用户手机号
UserName string `json:"userName"` // 用户名称
}
... ...
package domain
// 分红值对象
type Dividend struct {
// 计划分红
PlanBonus float64 `json:"planBonus"`
// 调整后分红
UseBonus float64 `json:"useBonus"`
// 已收分红
BonusHas float64 `json:"bonusHas"`
// 未收分红
BonusNot float64 `json:"bonusNot"`
// 分红支出
BonusExpense float64 `json:"bonusExpense"`
// 分红状态(1:待支付 2:已支付)
BonusStatus int `json:"bonusStatus"`
// 合伙人分红比例
PartnerBonusPercent float64 `json:"partnerBonusPercent"`
// 业务员抽成比例
SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
// 业务员抽成
SalesmanBonus float64 `json:"salesmanBonus"`
}
... ...
package domain
import "time"
// 订单商品实体
type Goods struct {
// 商品id
GoodsId int64 `json:"goodsId"`
// 预定的货品数量
GoodsNum int `json:"goodsNum"`
// 商品分红支付信息
GoodsDividend *Dividend `json:"goodsDividend"`
// 商品分红支付状态
GoodsDividendStatus int `json:"goodsDividendStatus"`
// 商品名称
GoodsName string `json:"goodsName"`
// 商品单价
GoodsTotalPrice float64 `json:"goodsTotalPrice"`
// 备注
Remarks string `json:"remarks"`
// 订单编号
OrderNo string `json:"orderNo"`
GoodsDetail string `json:"goodsDetail"`
// 创建时间
CreateAt time.Time `json:"createAt"`
// 更新时间
UpdateAt time.Time `json:"updateAt"`
// 删除时间
DeleteAt time.Time `json:"deleteAt"`
}
type GoodsRepository interface {
Save(goods *Goods) (*Goods, error)
Remove(goods *Goods) (*Goods, error)
FindOne(queryOptions map[string]interface{}) (*Goods, error)
Find(queryOptions map[string]interface{}) (int64, []*Goods, error)
}
func (goods *Goods) Identify() interface{} {
if goods.GoodsId == 0 {
return nil
}
return goods.GoodsId
}
func (goods *Goods) Update(data map[string]interface{}) error {
if goodsId, ok := data["goodsId"]; ok {
goods.GoodsId = goodsId.(int64)
}
if goodsNum, ok := data["goodsNum"]; ok {
goods.GoodsNum = goodsNum.(int)
}
if planBonus, ok := data["planBonus"]; ok {
goods.GoodsDividend.PlanBonus = planBonus.(float64)
}
if useBonus, ok := data["useBonus"]; ok {
goods.GoodsDividend.UseBonus = useBonus.(float64)
}
if bonusHas, ok := data["bonusHas"]; ok {
goods.GoodsDividend.BonusHas = bonusHas.(float64)
}
if bonusNot, ok := data["bonusNot"]; ok {
goods.GoodsDividend.BonusNot = bonusNot.(float64)
}
if bonusExpense, ok := data["bonusExpense"]; ok {
goods.GoodsDividend.BonusExpense = bonusExpense.(float64)
}
if bonusStatus, ok := data["bonusStatus"]; ok {
goods.GoodsDividend.BonusStatus = bonusStatus.(int)
}
if partnerBonusPercent, ok := data["partnerBonusPercent"]; ok {
goods.GoodsDividend.PartnerBonusPercent = partnerBonusPercent.(float64)
}
if salesmanBonusPercent, ok := data["salesmanBonusPercent"]; ok {
goods.GoodsDividend.SalesmanBonusPercent = salesmanBonusPercent.(float64)
}
if salesmanBonus, ok := data["salesmanBonus"]; ok {
goods.GoodsDividend.SalesmanBonus = salesmanBonus.(float64)
}
if goodsDividendStatus, ok := data["goodsDividendStatus"]; ok {
goods.GoodsDividendStatus = goodsDividendStatus.(int)
}
if goodsName, ok := data["goodsName"]; ok {
goods.GoodsName = goodsName.(string)
}
if goodsTotalPrice, ok := data["goodsTotalPrice"]; ok {
goods.GoodsTotalPrice = goodsTotalPrice.(float64)
}
if remarks, ok := data["remarks"]; ok {
goods.Remarks = remarks.(string)
}
if orderNo, ok := data["orderNo"]; ok {
goods.OrderNo = orderNo.(string)
}
if goodsDetail, ok := data["goodsDetail"]; ok {
goods.GoodsDetail = goodsDetail.(string)
}
if createAt, ok := data["createAt"]; ok {
goods.CreateAt = createAt.(time.Time)
}
if updateAt, ok := data["updateAt"]; ok {
goods.UpdateAt = updateAt.(time.Time)
}
if deleteAt, ok := data["deleteAt"]; ok {
goods.DeleteAt = deleteAt.(time.Time)
}
return nil
}
... ...
package domain
import (
"fmt"
"time"
)
// 订单类型
const (
ORDER_TYPE_ACTUAL = iota + 1 //实际订单
ORDER_TYPE_INTENTION // 意向订单
)
// 订单状态
const (
ORDER_STATUS_UNSHIPPED = iota + 1 // 待发货
ORDER_STATUS_TRANSIT // 待收货(运输中)
ORDER_STATUS_RECEIVED // 已收货
ORDER_STATUS_RETURN // 退换货
ORDER_STATUS_CANCELED // 已取消(关闭)
ORDER_STATUS_COMPLETED // 已完成
)
// 订单实体
type Order struct {
// 订单id
OrderId int64 `json:"orderId"`
// 买家信息
Buyer *BuyerInfo `json:"buyer"`
// 公司Id
CompanyId int64 `json:"companyId"`
// 合伙人id
PartnerId int64 `json:"partnerId"`
// 发货单号
DeliveryCode string `json:"deliveryCode"`
// 是否关闭订单标志
IsDisable int `json:"isDisable"`
// 订单编号
OrderNo string `json:"orderNo"`
// 订单详情
OrderDetail *OrderDetail `json:"orderDetail"`
// 订单分红信息
OrderDividend *Dividend `json:"orderDividend"`
// 订单分红支付状态
OrderDividendStatus int `json:"orderDividendStatus"`
// 订单货品
OrderGoods []*Goods `json:"orderGoods"`
// 订单数据来源
OrderSource *OrderSource `json:"orderSource"`
// 订单类型(1.实际订单;2.意向订单)
OrderType int `json:"orderType"`
// 订单状态(1.发货;2.收货;3.退货;4.取消;5.完成)
OrderStatus int `json:"orderStatus"`
// 订单总价
TotalPrice float64 `json:"totalPrice"`
// 订单区域信息
RegionInfo *RegionInfo `json:"regionInfo"`
// 备注
Remarks string `json:"remarks"`
// 创建时间
CreateAt time.Time `json:"createAt"`
// 更新时间
UpdateAt time.Time `json:"updateAt"`
// 软删
DeleteAt time.Time `json:"deleteAt"`
// 当前状态
CurrentStatus OrderStatus `json:"-"`
}
// 订单状态机
type OrderStatus interface {
Update(order *Order, data map[string]interface{}) error // 更新订单
Checkout(order *Order) error // 下单
Return(order *Order) error // 退换货
Cancel(order *Order) error // 取消订单
Receive(order *Order) error // 收货
}
// 代发货状态
type UnShippedStatus struct{}
// 编辑待发货订单
func (status *UnShippedStatus) Update(order *Order, data map[string]interface{}) error {
if orderId, ok := data["orderId"]; ok {
order.OrderId = orderId.(int64)
}
if buyerName, ok := data["buyerName"]; ok {
order.Buyer.BuyerName = buyerName.(string)
}
if contactInfo, ok := data["contactInfo"]; ok {
order.Buyer.ContactInfo = contactInfo.(string)
}
if shippingAddress, ok := data["shippingAddress"]; ok {
order.Buyer.ShippingAddress = shippingAddress.(string)
}
if companyId, ok := data["companyId"]; ok {
order.CompanyId = companyId.(int64)
}
if partnerId, ok := data["partnerId"]; ok {
order.PartnerId = partnerId.(int64)
}
if deliveryCode, ok := data["deliveryCode"]; ok {
order.DeliveryCode = deliveryCode.(string)
}
if isDisable, ok := data["isDisable"]; ok {
order.IsDisable = isDisable.(int)
}
if orderNo, ok := data["orderNo"]; ok {
order.OrderNo = orderNo.(string)
}
if orderDetailId, ok := data["orderDetailId"]; ok {
order.OrderDetail.OrderDetailId = orderDetailId.(int64)
}
if orderNo, ok := data["orderNo"]; ok {
order.OrderDetail.OrderNo = orderNo.(string)
}
if orderNum, ok := data["orderNum"]; ok {
order.OrderDetail.OrderNum = orderNum.(int)
}
if totalPrice, ok := data["totalPrice"]; ok {
order.OrderDetail.TotalPrice = totalPrice.(float64)
}
if adjustedNum, ok := data["adjustedNum"]; ok {
order.OrderDetail.AdjustedNum = adjustedNum.(int)
}
if adjustedTotalPrice, ok := data["adjustedTotalPrice"]; ok {
order.OrderDetail.AdjustedTotalPrice = adjustedTotalPrice.(float64)
}
if planBonus, ok := data["planBonus"]; ok {
order.OrderDividend.PlanBonus = planBonus.(float64)
}
if useBonus, ok := data["useBonus"]; ok {
order.OrderDividend.UseBonus = useBonus.(float64)
}
if bonusHas, ok := data["bonusHas"]; ok {
order.OrderDividend.BonusHas = bonusHas.(float64)
}
if bonusNot, ok := data["bonusNot"]; ok {
order.OrderDividend.BonusNot = bonusNot.(float64)
}
if bonusExpense, ok := data["bonusExpense"]; ok {
order.OrderDividend.BonusExpense = bonusExpense.(float64)
}
if bonusStatus, ok := data["bonusStatus"]; ok {
order.OrderDividend.BonusStatus = bonusStatus.(int)
}
if partnerBonusPercent, ok := data["partnerBonusPercent"]; ok {
order.OrderDividend.PartnerBonusPercent = partnerBonusPercent.(float64)
}
if salesmanBonusPercent, ok := data["salesmanBonusPercent"]; ok {
order.OrderDividend.SalesmanBonusPercent = salesmanBonusPercent.(float64)
}
if salesmanBonus, ok := data["salesmanBonus"]; ok {
order.OrderDividend.SalesmanBonus = salesmanBonus.(float64)
}
if orderDividendStatus, ok := data["orderDividendStatus"]; ok {
order.OrderDividendStatus = orderDividendStatus.(int)
}
if orderGoods, ok := data["orderGoods"]; ok {
order.OrderGoods = orderGoods.([]*Goods)
}
if dataSourceId, ok := data["dataSourceId"]; ok {
order.OrderSource.DataSourceId = dataSourceId.(int64)
}
if platform, ok := data["platform"]; ok {
order.OrderSource.Platform = platform.(string)
}
if createAt, ok := data["createAt"]; ok {
order.OrderSource.CreateAt = createAt.(time.Time)
}
if orderType, ok := data["orderType"]; ok {
order.OrderType = orderType.(int)
}
if orderStatus, ok := data["orderStatus"]; ok {
order.OrderStatus = orderStatus.(int)
}
if totalPrice, ok := data["totalPrice"]; ok {
order.TotalPrice = totalPrice.(float64)
}
if regionName, ok := data["regionName"]; ok {
order.RegionInfo.RegionName = regionName.(string)
}
if remarks, ok := data["remarks"]; ok {
order.Remarks = remarks.(string)
}
if createAt, ok := data["createAt"]; ok {
order.CreateAt = createAt.(time.Time)
}
if updateAt, ok := data["updateAt"]; ok {
order.UpdateAt = updateAt.(time.Time)
}
if deleteAt, ok := data["deleteAt"]; ok {
order.DeleteAt = deleteAt.(time.Time)
}
return nil
}
func (status *UnShippedStatus) Checkout(order *Order) error {
return nil
}
func (status *UnShippedStatus) Return(order *Order) error {
return fmt.Errorf("待发货订单不能退货")
}
func (status *UnShippedStatus) Cancel(order *Order) error {
return nil
}
func (status *UnShippedStatus) Receive(order *Order) error {
return fmt.Errorf("待发货订单不能收货")
}
// 待收货状态
type TransitStatus struct{}
// 待收货订单不允许编辑
func (status *TransitStatus) Update(order *Order, data map[string]interface{}) error {
return fmt.Errorf("已发货订单不允许编辑")
}
func (status *TransitStatus) Checkout(order *Order) error {
return fmt.Errorf("待收货订单不能重复发货")
}
func (status *TransitStatus) Return(order *Order) error {
return nil
}
func (status *TransitStatus) Cancel(order *Order) error {
return fmt.Errorf("待收货订单不能取消")
}
func (status *TransitStatus) Receive(order *Order) error {
return nil
}
// 收货状态
type ReceivedStatus struct{}
func (status *ReceivedStatus) Update(order *Order, data map[string]interface{}) error {
return fmt.Errorf("已收货订单不能编辑")
}
func (status *ReceivedStatus) Checkout(order *Order) error {
return fmt.Errorf("已收货订单不能重复发货")
}
func (status *ReceivedStatus) Return(order *Order) error {
return nil
}
func (status *ReceivedStatus) Cancel(order *Order) error {
return fmt.Errorf("已收货订单不能取消")
}
func (status *ReceivedStatus) Receive(order *Order) error {
return fmt.Errorf("已收货订单不能重复收货")
}
// 退货状态
type ReturnedStatus struct{}
func (status *ReturnedStatus) Update(order *Order, data map[string]interface{}) error {
return fmt.Errorf("已退货订单不允许编辑")
}
func (status *ReturnedStatus) Checkout(order *Order) error {
return fmt.Errorf("已退货订单不允许发货")
}
func (status *ReturnedStatus) Return(order *Order) error {
return fmt.Errorf("已退货订单不允许再次退货")
}
func (status *ReturnedStatus) Cancel(order *Order) error {
return fmt.Errorf("已退货订单不能取消")
}
func (status *ReturnedStatus) Receive(order *Order) error {
return fmt.Errorf("已退货订单不能收货")
}
// 取消状态
type CanceledStatus struct{}
func (status *CanceledStatus) Update(order *Order, dat map[string]interface{}) error {
return fmt.Errorf("已取消订单不能编辑")
}
func (status *CanceledStatus) Checkout(order *Order) error {
return fmt.Errorf("已取消订单不能发货")
}
func (status *CanceledStatus) Return(order *Order) error {
return fmt.Errorf("已取消订单不能退货")
}
func (status *CanceledStatus) Cancel(order *Order) error {
return fmt.Errorf("已取消订单不能再次取消")
}
func (status *CanceledStatus) Receive(order *Order) error {
return fmt.Errorf("已取消订单不能进行收货")
}
// 已完成状态
type CompletedStatus struct{}
func (status *CompletedStatus) Update(order *Order, data map[string]interface{}) error {
return nil
}
func (status *CompletedStatus) Checkout(order *Order) error {
return fmt.Errorf("已完成订单不能发货")
}
func (status *CompletedStatus) Return(order *Order) error {
return fmt.Errorf("已完成订单不能退货")
}
func (status *CompletedStatus) Cancel(order *Order) error {
return fmt.Errorf("已完成订单不能取消")
}
func (status *CompletedStatus) Receive(order *Order) error {
return fmt.Errorf("已完成订单不能收货")
}
// 订单仓储
type OrderRepository interface {
Save(order *Order) (*Order, error)
Remove(order *Order) (*Order, error)
FindOne(queryOptions map[string]interface{}) (*Order, error)
Find(queryOptions map[string]interface{}) (int64, []*Order, error)
}
func (order *Order) Identify() interface{} {
if order.OrderId == 0 {
return nil
}
return order.OrderId
}
// 更新订单
func (order *Order) Update(data map[string]interface{}) error {
return order.CurrentStatus.Update(order, data)
}
// 发货
func (order *Order) Checkout() error {
return order.CurrentStatus.Checkout(order)
}
// 退货
func (order *Order) Return() error {
return order.CurrentStatus.Return(order)
}
// 收货
func (order *Order) Receive() error {
return order.CurrentStatus.Receive(order)
}
// 取消订单
func (order *Order) Cancel() error {
return order.CurrentStatus.Cancel(order)
}
... ...
package domain
// 订单详情实体
type OrderDetail struct {
// 订单详情id
OrderDetailId int64 `json:"orderDetailId"`
// 订单编号
OrderNo string `json:"orderNo"`
// 订单数量
OrderNum int `json:"orderNum"`
// 订单总金额
TotalPrice float64 `json:"totalPrice"`
// 调整后订单数量
AdjustedNum int `json:"adjustedNum"`
// 调整后订单总金额
AdjustedTotalPrice float64 `json:"adjustedTotalPrice"`
}
... ...
package domain
import "time"
// 订单数据来源值对象
type OrderSource struct {
// 订单数据来源id
DataSourceId int64 `json:"dataSourceId"`
// 订单数据来源平台
Platform string `json:"platform"`
// 创建时间
CreateAt time.Time `json:"createAt"`
}
... ...
package domain
// 合伙人类别 (实体)
type PartnerCategory struct {
// 合伙人类别id
PartnerCategoryId int `json:"partnerCategoryId"`
// 合伙人类别编码
PartnerCategoryCode string `json:"partnerCategoryCode"`
// 合伙人类别名称
PartnerCategoryName string `json:"partnerCategoryName"`
}
type PartnerCategoryRepository interface {
Save(partnerCategory *PartnerCategory) (*PartnerCategory, error)
Remove(partnerCategory *PartnerCategory) (*PartnerCategory, error)
FindOne(queryOptions map[string]interface{}) (*PartnerCategory, error)
Find(queryOptions map[string]interface{}) (int64, []*PartnerCategory, error)
}
func (partnerCategory *PartnerCategory) Identify() interface{} {
if partnerCategory.PartnerCategoryId == 0 {
return nil
}
return partnerCategory.PartnerCategoryId
}
func (partnerCategory *PartnerCategory) Update(data map[string]interface{}) error {
if partnerCategoryId, ok := data["partnerCategoryId"]; ok {
partnerCategory.PartnerCategoryId = partnerCategoryId.(int)
}
if partnerCategoryCode, ok := data["partnerCategoryCode"]; ok {
partnerCategory.PartnerCategoryCode = partnerCategoryCode.(string)
}
if partnerCategoryName, ok := data["partnerCategoryName"]; ok {
partnerCategory.PartnerCategoryName = partnerCategoryName.(string)
}
return nil
}
... ...
package domain
import "time"
// 合伙人信息
type PartnerInfo struct {
// 合伙人账号
PartnerAccount string `json:"partnerAccount"`
// 合伙人姓名
PartnerName string `json:"partnerName"`
// 订单区域信息
RegionInfo *RegionInfo `json:"regionInfo"`
// 状态 1正常 2禁用
Status int64 `json:"status"`
// 合伙时间
CooperateTime time.Time `json:"cooperateTime"`
// 业务员
Salesmans []*Salesman `json:"salesmans"`
// 合伙人类型
PartnerCategorys []*PartnerCategory `json:"partnerCategorys"`
}
... ...
package domain
// 权限
type Permission struct {
// 权限id
PermissionId int `json:"permissionId"`
// 公司名称
Name string `json:"name"`
// 权限编码
Code string `json:"code"`
// 父级id
ParentId int `json:"parentId"`
// 排序
Sort int `json:"sort"`
// 图标
Icon string `json:"icon"`
}
type PermissionRepository interface {
Save(permission *Permission) (*Permission, error)
Remove(permission *Permission) (*Permission, error)
FindOne(queryOptions map[string]interface{}) (*Permission, error)
Find(queryOptions map[string]interface{}) (int64, []*Permission, error)
}
func (permission *Permission) Identify() interface{} {
if permission.PermissionId == 0 {
return nil
}
return permission.PermissionId
}
func (permission *Permission) Update(data map[string]interface{}) error {
if permissionId, ok := data["permissionId"]; ok {
permission.PermissionId = permissionId.(int)
}
if name, ok := data["name"]; ok {
permission.Name = name.(string)
}
if code, ok := data["code"]; ok {
permission.Code = code.(string)
}
if parentId, ok := data["parentId"]; ok {
permission.ParentId = parentId.(int)
}
if sort, ok := data["sort"]; ok {
permission.Sort = sort.(int)
}
if icon, ok := data["icon"]; ok {
permission.Icon = icon.(string)
}
return nil
}
... ...
package domain
// 手机认证
type PhoneAuth struct {
// 手机号
Phone string `json:"phone"`
// 密码
Password string `json:"password"`
}
... ...
package domain
// 区域信息
type RegionInfo struct {
// 区域名称 eg:华南地区
RegionName string `json:"regionName"`
}
... ...
package domain
// 业务员
type Salesman struct {
// 名称
Name string `json:"name"`
// 手机号码
Telephone string `json:"telephone"`
}
... ...
package service
import (
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
)
type CancelOrderService interface {
coreDomain.DomainEventPublisher
Cancel(orderId int64) (*domain.Order, error)
}
... ...
package service
import (
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
)
type ReceivingGoodsService interface {
coreDomain.DomainEventPublisher
Receiving(orderId int64) (*domain.Order, error)
}
... ...
package service
import (
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
)
type ReturnGoodsService interface {
coreDomain.DomainEventPublisher
Return(orderId int64) (*domain.Order, error)
}
... ...
package service
import (
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
)
type ShippingGoodsService interface {
coreDomain.DomainEventPublisher
Shipping(orderId int64) (*domain.Order, error)
}
... ...
package domain
import "time"
const (
StatusEnable int64 = 1
StatusDisable int64 = 2
)
const (
SuperAdministrator = 1
EnterpriseAdministrator = 10
NormalUser = 100
)
// UserType
const (
Manager = 1
Partner = 2
Guest = 3
)
// 用户实体
type User struct {
// 用户id
UserId int64 `json:"userId"`
// 1.高管 2.合伙人 4:游客
UserType int `json:"userType"`
// 用户权限
Permissions []int `json:"permissions"`
// 公司Id
CompanyId int64 `json:"companyId"`
// 用户信息
UserInfo *UserInfo `json:"userInfo"`
// 合伙人信息
PartnerInfo *PartnerInfo `json:"partnerInfo"`
// 状态 1正常 2禁用
Status int64 `json:"status"`
// 管理员类型 1.超级管理员 10:企业管理员 100:普通用户
AdminType int `json:"adminType"`
// 合伙人列表 用户类型为高管时有效
AccessPartners []int64 `json:"accessPartners"`
// 创建时间
CreateAt time.Time `json:"createAt"`
// 更新时间
UpdateAt time.Time `json:"updateAt"`
// 删除时间
DeleteAt time.Time `json:"deleteAt"`
}
type UserRepository interface {
Save(user *User) (*User, error)
Remove(user *User) (*User, error)
FindOne(queryOptions map[string]interface{}) (*User, error)
Find(queryOptions map[string]interface{}) (int64, []*User, error)
}
func (user *User) Identify() interface{} {
if user.UserId == 0 {
return nil
}
return user.UserId
}
func (user *User) Update(data map[string]interface{}) error {
if userId, ok := data["userId"]; ok {
user.UserId = userId.(int64)
}
if userType, ok := data["userType"]; ok {
user.UserType = userType.(int)
}
if permissions, ok := data["permissions"]; ok {
user.Permissions = permissions.([]int)
}
if companyId, ok := data["companyId"]; ok {
user.CompanyId = companyId.(int64)
}
if isPrincipal, ok := data["isPrincipal"]; ok {
user.UserInfo.IsPrincipal = isPrincipal.(bool)
}
if uid, ok := data["uid"]; ok {
user.UserInfo.Uid = uid.(int64)
}
if userAccount, ok := data["userAccount"]; ok {
user.UserInfo.UserAccount = userAccount.(string)
}
if userAvatarUrl, ok := data["userAvatarUrl"]; ok {
user.UserInfo.UserAvatarUrl = userAvatarUrl.(string)
}
if userName, ok := data["userName"]; ok {
user.UserInfo.UserName = userName.(string)
}
if email, ok := data["email"]; ok {
user.UserInfo.Email = email.(string)
}
if gender, ok := data["gender"]; ok {
user.UserInfo.Gender = gender.(int)
}
if entryTime, ok := data["entryTime"]; ok {
user.UserInfo.EntryTime = entryTime.(time.Time)
}
if extension, ok := data["extension"]; ok {
user.UserInfo.Extension = extension.(string)
}
if workplace, ok := data["workplace"]; ok {
user.UserInfo.Workplace = workplace.(string)
}
if privateNumber, ok := data["privateNumber"]; ok {
user.UserInfo.PrivateNumber = privateNumber.(string)
}
if jobNumber, ok := data["jobNumber"]; ok {
user.UserInfo.JobNumber = jobNumber.(string)
}
if partnerAccount, ok := data["partnerAccount"]; ok {
user.PartnerInfo.PartnerAccount = partnerAccount.(string)
}
if partnerName, ok := data["partnerName"]; ok {
user.PartnerInfo.PartnerName = partnerName.(string)
}
if regionName, ok := data["regionName"]; ok {
user.PartnerInfo.RegionInfo.RegionName = regionName.(string)
}
if status, ok := data["status"]; ok {
user.PartnerInfo.Status = status.(int64)
}
return nil
}
... ...
package domain
import "time"
// 用户认证实体
type UserAuth struct {
// 用户认证编号
UserAuthId int64 `json:"userAuthId"`
// 用户id列表
Users []int64 `json:"users"`
// 手机认证
PhoneAuth *PhoneAuth `json:"phoneAuth"`
// 创建时间
CreateAt time.Time `json:"createAt"`
// 更新时间
UpdateAt time.Time `json:"updateAt"`
}
type UserAuthRepository interface {
Save(userAuth *UserAuth) (*UserAuth, error)
Remove(userAuth *UserAuth) (*UserAuth, error)
FindOne(queryOptions map[string]interface{}) (*UserAuth, error)
Find(queryOptions map[string]interface{}) (int64, []*UserAuth, error)
}
func (userAuth *UserAuth) Identify() interface{} {
if userAuth.UserAuthId == 0 {
return nil
}
return userAuth.UserAuthId
}
func (userAuth *UserAuth) Update(data map[string]interface{}) error {
if userAuthId, ok := data["userAuthId"]; ok {
userAuth.UserAuthId = userAuthId.(int64)
}
if users, ok := data["users"]; ok {
userAuth.Users = users.([]int64)
}
if phone, ok := data["phone"]; ok {
userAuth.PhoneAuth.Phone = phone.(string)
}
if password, ok := data["password"]; ok {
userAuth.PhoneAuth.Password = password.(string)
}
if createAt, ok := data["createAt"]; ok {
userAuth.CreateAt = createAt.(time.Time)
}
if updateAt, ok := data["updateAt"]; ok {
userAuth.UpdateAt = updateAt.(time.Time)
}
return nil
}
... ...
package domain
import "time"
// 用户信息值对象
type UserInfo struct {
// 是否是公司负责人
IsPrincipal bool `json:"isPrincipal"`
// 统一用户id
Uid int64 `json:"uid"`
// 用户账号
UserAccount string `json:"userAccount"`
// 用户头像URL
UserAvatarUrl string `json:"userAvatarUrl"`
// 用户名称
UserName string `json:"userName"`
// 邮件地址
Email string `json:"email"`
// 性别
Gender int `json:"gender"`
// 入职时间
EntryTime time.Time `json:"entryTime"`
// 分机
Extension string `json:"extension"`
// 工作地
Workplace string `json:"workplace"`
// 私人电话
PrivateNumber string `json:"privateNumber"`
// 工号
JobNumber string `json:"jobNumber"`
}
... ...
package domainService
import (
"fmt"
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
)
type CancelOrderService struct {
coreDomain.BaseEventPublisher
transactionContext *pgTransaction.TransactionContext
}
func (service *CancelOrderService) Cancel(orderId int64) (*domain.Order, error) {
return nil, nil
}
func NewCancelOrderService(transactionContext *pgTransaction.TransactionContext) (*CancelOrderService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &CancelOrderService{
transactionContext: transactionContext,
}, nil
}
}
... ...
package domainService
import (
"fmt"
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
)
type ReceivingGoodsService struct {
coreDomain.BaseEventPublisher
transactionContext *pgTransaction.TransactionContext
}
func (service *ReceivingGoodsService) Receiving(orderId int64) (*domain.Order, error) {
return nil, nil
}
func NewReceivingGoodsService(transactionContext *pgTransaction.TransactionContext) (*ReceivingGoodsService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ReceivingGoodsService{
transactionContext: transactionContext,
}, nil
}
}
... ...
package domainService
import (
"fmt"
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
)
type ReturnGoodsService struct {
coreDomain.BaseEventPublisher
transactionContext *pgTransaction.TransactionContext
}
func (service *ReturnGoodsService) Return(orderId int64) (*domain.Order, error) {
panic("implement me")
}
func NewReturnGoodsService(transactionContext *pgTransaction.TransactionContext) (*ReturnGoodsService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ReturnGoodsService{
transactionContext: transactionContext,
}, nil
}
}
... ...
package domainService
import (
"fmt"
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
)
type ShippingGoodsService struct {
coreDomain.BaseEventPublisher
transactionContext *pgTransaction.TransactionContext
}
func (service *ShippingGoodsService) Shipping(orderId int64) (*domain.Order, error) {
return nil, nil
}
func NewShippingGoodsService(transactionContext *pgTransaction.TransactionContext) (*ShippingGoodsService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ShippingGoodsService{
transactionContext: transactionContext,
}, nil
}
}
... ...
package gateway
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/tiptok/gocomm/gs"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/constant"
"net/http"
)
const (
AuthsLogin = "AuthsLogin"
AuthsLoginByCompany = "loginByCompany"
AuthsAccessToken = "AuthsAccessToken"
AuthsRefreshToken = "AuthsRefreshToken"
AuthsSendSmsCode = "AuthsSendSmsCode"
AuthsRevoke = "AuthsRevoke"
AuthsChangePhonePassword = "AuthsChangePhonePassword"
)
const (
CompanyGet = "CompanyGet"
CompanyCreate = "CompanyCreate"
CompanyRemove = "CompanyRemove"
CompanyList = "CompanyList"
CompanyUpdate = "CompanyUpdate"
)
var Partner01Service *HttpPartner01ServiceGateway
func init() {
Partner01Service = &HttpPartner01ServiceGateway{gs.NewManagerService(constant.PARTER01_GATEWAY_ADDRESS, Routers())}
Partner01Service.WithDebugModel(true)
}
type HttpPartner01ServiceGateway struct {
*gs.GatewayService
}
func Routers() []gs.Router {
routers := []gs.Router{
{AuthsLogin, "/auths/login", http.MethodPost},
{AuthsLoginByCompany, "/auths/loginByCompany", http.MethodPost},
{AuthsAccessToken, "/auths/accessToken", http.MethodPost},
{AuthsRefreshToken, "/auths/refreshToken", http.MethodPost},
{AuthsSendSmsCode, "/auths/sendSmsCode", http.MethodPost},
{AuthsRevoke, "/auths/revoke", http.MethodPost},
{AuthsChangePhonePassword, "/auths/changePhonePassword", http.MethodPost},
{CompanyGet, "/companies/:companyId", http.MethodGet},
{CompanyRemove, "/companies/:companyId", http.MethodDelete},
{CompanyUpdate, "/companies/:companyId", http.MethodPut},
{CompanyCreate, "/companies/", http.MethodPost},
{CompanyList, "/companies/", http.MethodGet},
}
return routers
}
func (service *HttpPartner01ServiceGateway) CompanyCreate(jsonObject interface{}) (interface{}, error) {
data, err := service.Invoke(CompanyCreate, gs.WithJsonObject(jsonObject))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
func (service *HttpPartner01ServiceGateway) CompanyGet(pathParam interface{}) (interface{}, error) {
data, err := service.Invoke(CompanyGet, gs.WithPathParam(pathParam))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return data.Data, nil
}
... ...
package pg
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/constant"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
"github.com/linmadan/egglib-go/persistent/pg/hooks"
)
var DB *pg.DB
func init() {
DB = pg.Connect(&pg.Options{
User: constant.POSTGRESQL_USER,
Password: constant.POSTGRESQL_PASSWORD,
Database: constant.POSTGRESQL_DB_NAME,
Addr: fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
})
if !constant.DISABLE_SQL_GENERATE_PRINT {
DB.AddQueryHook(hooks.SqlGeneratePrintHook{})
}
if !constant.DISABLE_CREATE_TABLE {
for _, model := range []interface{}{
&models.Permission{},
&models.PartnerCategory{},
&models.UserAuth{},
&models.Goods{},
&models.Order{},
&models.User{},
&models.Company{},
} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
IfNotExists: true,
FKConstraints: true,
})
if err != nil {
panic(err)
}
}
}
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"time"
)
type Company struct {
tableName string `pg:"companies,alias:company"`
// 公司Id
CompanyId int64 `pg:",pk"`
// 公司信息
CompanyInfo *domain.CompanyInfo
// 创建时间
CreateAt time.Time
// 更新时间
UpdateAt time.Time
// 删除时间
DeleteAt time.Time `pg:",soft_delete"`
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"time"
)
type Goods struct {
tableName string `pg:"goodss,alias:goods"`
// 商品id
GoodsId int64
// 预定的货品数量
GoodsNum int
// 商品分红支付信息
GoodsDividend *domain.Dividend
// 商品分红支付状态
GoodsDividendStatus int
// 商品名称
GoodsName string
// 商品单价
GoodsTotalPrice float64
// 备注
Remarks string
// 订单编号
OrderNo string
// 商品详情
GoodsDetail string
// 创建时间
CreateAt time.Time
// 更新时间
UpdateAt time.Time
// 删除时间
DeleteAt time.Time
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"time"
)
type Order struct {
tableName string `pg:"orders,alias:order"`
// 订单id
OrderId int64
// 买家信息
Buyer *domain.BuyerInfo
// 公司Id
CompanyId int64
// 合伙人id
PartnerId int64
// 发货单号
DeliveryCode string
// 是否关闭订单标志
IsDisable int
// 订单编号
OrderNo string
// 订单详情
OrderDetail *domain.OrderDetail
// 订单分红信息
OrderDividend *domain.Dividend
// 订单分红支付状态
OrderDividendStatus int
// 订单货品
OrderGoods []*domain.Goods
// 订单数据来源
OrderSource *domain.OrderSource
// 订单类型(1.实际订单;2.意向订单)
OrderType int
// 订单状态(1.发货;2.收货;3.退货;4.取消;5.完成)
OrderStatus int
// 订单总价
TotalPrice float64
// 订单区域信息
RegionInfo *domain.RegionInfo
// 备注
Remarks string
// 创建时间
CreateAt time.Time
// 更新时间
UpdateAt time.Time
// 软删
DeleteAt time.Time
}
... ...
package models
type PartnerCategory struct {
tableName string `pg:"partner_category"`
// 合伙人类别id
PartnerCategoryId int `pg:",pk"`
// 合伙人类别编码
PartnerCategoryCode string
// 合伙人类别名称
PartnerCategoryName string
}
... ...
package models
type Permission struct {
tableName string `pg:"permissions,alias:permission"`
// 权限id
PermissionId int `pg:",pk"`
// 公司名称
Name string
// 权限编码
Code string
// 父级id
ParentId int
// 排序
Sort int
// 图标
Icon string
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"time"
)
type User struct {
tableName string `pg:"users,alias:users"`
// 用户id
UserId int64 `pg:",pk"`
// 1.高管 2.合伙人 4:游客
UserType int
// 用户权限
Permissions []int `pg:",array"`
// 公司Id
CompanyId int64
// 用户信息
UserInfo *domain.UserInfo
// 合伙人信息
PartnerInfo *domain.PartnerInfo
// 状态 1正常 2禁用
Status int64
// 管理员类型 1.超级管理员 10:企业管理员 100:普通用户
AdminType int
// 合伙人列表 用户类型为高管时有效
AccessPartners []int64 `pg:",array"`
// 创建时间
CreateAt time.Time
// 更新时间
UpdateAt time.Time
// 删除时间
DeleteAt time.Time
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"time"
)
type UserAuth struct {
tableName string `pg:"user_auth,alias:user_auth"`
// 用户认证编号
UserAuthId int64 `pg:",pk"`
// 用户id列表
Users []int64 `pg:",array"`
// 手机认证
PhoneAuth *domain.PhoneAuth
// 创建时间
CreateAt time.Time
// 更新时间
UpdateAt time.Time
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
)
func TransformToCompanyDomainModelFromPgModels(companyModel *models.Company) (*domain.Company, error) {
return &domain.Company{
CompanyId: companyModel.CompanyId,
CompanyInfo: companyModel.CompanyInfo,
CreateAt: companyModel.CreateAt,
UpdateAt: companyModel.UpdateAt,
DeleteAt: companyModel.DeleteAt,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
)
func TransformToGoodsDomainModelFromPgModels(goodsModel *models.Goods) (*domain.Goods, error) {
return &domain.Goods{
GoodsId: goodsModel.GoodsId,
GoodsNum: goodsModel.GoodsNum,
GoodsDividend: goodsModel.GoodsDividend,
GoodsDividendStatus: goodsModel.GoodsDividendStatus,
GoodsName: goodsModel.GoodsName,
GoodsTotalPrice: goodsModel.GoodsTotalPrice,
Remarks: goodsModel.Remarks,
OrderNo: goodsModel.OrderNo,
GoodsDetail: goodsModel.GoodsDetail,
CreateAt: goodsModel.CreateAt,
UpdateAt: goodsModel.UpdateAt,
DeleteAt: goodsModel.DeleteAt,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
)
func TransformToOrderDomainModelFromPgModels(orderModel *models.Order) (*domain.Order, error) {
return &domain.Order{
OrderId: orderModel.OrderId,
Buyer: orderModel.Buyer,
CompanyId: orderModel.CompanyId,
PartnerId: orderModel.PartnerId,
DeliveryCode: orderModel.DeliveryCode,
IsDisable: orderModel.IsDisable,
OrderNo: orderModel.OrderNo,
OrderDetail: orderModel.OrderDetail,
OrderDividend: orderModel.OrderDividend,
OrderDividendStatus: orderModel.OrderDividendStatus,
OrderGoods: orderModel.OrderGoods,
OrderSource: orderModel.OrderSource,
OrderType: orderModel.OrderType,
OrderStatus: orderModel.OrderStatus,
TotalPrice: orderModel.TotalPrice,
RegionInfo: orderModel.RegionInfo,
Remarks: orderModel.Remarks,
CreateAt: orderModel.CreateAt,
UpdateAt: orderModel.UpdateAt,
DeleteAt: orderModel.DeleteAt,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
)
func TransformToPartnerCategoryDomainModelFromPgModels(partnerCategoryModel *models.PartnerCategory) (*domain.PartnerCategory, error) {
return &domain.PartnerCategory{
PartnerCategoryId: partnerCategoryModel.PartnerCategoryId,
PartnerCategoryCode: partnerCategoryModel.PartnerCategoryCode,
PartnerCategoryName: partnerCategoryModel.PartnerCategoryName,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
)
func TransformToPermissionDomainModelFromPgModels(permissionModel *models.Permission) (*domain.Permission, error) {
return &domain.Permission{
PermissionId: permissionModel.PermissionId,
Name: permissionModel.Name,
Code: permissionModel.Code,
ParentId: permissionModel.ParentId,
Sort: permissionModel.Sort,
Icon: permissionModel.Icon,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
)
func TransformToUserDomainModelFromPgModels(userModel *models.User) (*domain.User, error) {
return &domain.User{
UserId: userModel.UserId,
UserType: userModel.UserType,
Permissions: userModel.Permissions,
CompanyId: userModel.CompanyId,
UserInfo: userModel.UserInfo,
PartnerInfo: userModel.PartnerInfo,
Status: userModel.Status,
AdminType: userModel.AdminType,
AccessPartners: userModel.AccessPartners,
CreateAt: userModel.CreateAt,
UpdateAt: userModel.UpdateAt,
DeleteAt: userModel.DeleteAt,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
)
func TransformToUserAuthDomainModelFromPgModels(userAuthModel *models.UserAuth) (*domain.UserAuth, error) {
return &domain.UserAuth{
UserAuthId: userAuthModel.UserAuthId,
Users: userAuthModel.Users,
PhoneAuth: userAuthModel.PhoneAuth,
CreateAt: userAuthModel.CreateAt,
UpdateAt: userAuthModel.UpdateAt,
}, nil
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/transform"
)
type CompanyRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *CompanyRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *CompanyRepository) Save(company *domain.Company) (*domain.Company, error) {
sqlBuildFields := []string{
"company_id",
"company_info",
"create_at",
"update_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "company_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if company.Identify() == nil {
companyId, err := repository.nextIdentify()
if err != nil {
return company, err
} else {
company.CompanyId = companyId
}
if _, err := tx.QueryOne(
pg.Scan(
&company.CompanyId,
&company.CompanyInfo,
&company.CreateAt,
&company.UpdateAt,
&company.DeleteAt,
),
fmt.Sprintf("INSERT INTO companies (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
company.CompanyId,
company.CompanyInfo,
company.CreateAt,
company.UpdateAt,
company.DeleteAt,
); err != nil {
return company, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&company.CompanyId,
&company.CompanyInfo,
&company.CreateAt,
&company.UpdateAt,
&company.DeleteAt,
),
fmt.Sprintf("UPDATE companies SET %s WHERE company_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
company.CompanyInfo,
company.CreateAt,
company.UpdateAt,
company.DeleteAt,
company.Identify(),
); err != nil {
return company, err
}
}
return company, nil
}
func (repository *CompanyRepository) Remove(company *domain.Company) (*domain.Company, error) {
tx := repository.transactionContext.PgTx
companyModel := new(models.Company)
companyModel.CompanyId = company.Identify().(int64)
if _, err := tx.Model(companyModel).WherePK().Delete(); err != nil {
return company, err
}
return company, nil
}
func (repository *CompanyRepository) FindOne(queryOptions map[string]interface{}) (*domain.Company, error) {
tx := repository.transactionContext.PgTx
companyModel := new(models.Company)
query := sqlbuilder.BuildQuery(tx.Model(companyModel), queryOptions)
query.SetWhereByQueryOption("company.company_id = ?", "companyId")
query.SetWhereByQueryOption(`company.company_info @>'{"status":?}'`, "status")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if companyModel.CompanyId == 0 {
return nil, nil
} else {
return transform.TransformToCompanyDomainModelFromPgModels(companyModel)
}
}
func (repository *CompanyRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Company, error) {
tx := repository.transactionContext.PgTx
var companyModels []*models.Company
companies := make([]*domain.Company, 0)
query := sqlbuilder.BuildQuery(tx.Model(&companyModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("company_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, companies, err
} else {
for _, companyModel := range companyModels {
if company, err := transform.TransformToCompanyDomainModelFromPgModels(companyModel); err != nil {
return 0, companies, err
} else {
companies = append(companies, company)
}
}
return int64(count), companies, nil
}
}
func NewCompanyRepository(transactionContext *pgTransaction.TransactionContext) (*CompanyRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &CompanyRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/transform"
)
type GoodsRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *GoodsRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *GoodsRepository) Save(goods *domain.Goods) (*domain.Goods, error) {
sqlBuildFields := []string{
"goods_id",
"goods_num",
"goods_dividend",
"goods_dividend_status",
"goods_name",
"goods_total_price",
"remarks",
"order_no",
"goods_detail",
"create_at",
"update_at",
"delete_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "goods_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if goods.Identify() == nil {
goodsId, err := repository.nextIdentify()
if err != nil {
return goods, err
} else {
goods.GoodsId = goodsId
}
if _, err := tx.QueryOne(
pg.Scan(
&goods.GoodsId,
&goods.GoodsNum,
&goods.GoodsDividend,
&goods.GoodsDividendStatus,
&goods.GoodsName,
&goods.GoodsTotalPrice,
&goods.Remarks,
&goods.OrderNo,
&goods.GoodsDetail,
&goods.CreateAt,
&goods.UpdateAt,
&goods.DeleteAt,
),
fmt.Sprintf("INSERT INTO goodss (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
goods.GoodsId,
goods.GoodsNum,
goods.GoodsDividend,
goods.GoodsDividendStatus,
goods.GoodsName,
goods.GoodsTotalPrice,
goods.Remarks,
goods.OrderNo,
goods.GoodsDetail,
goods.CreateAt,
goods.UpdateAt,
goods.DeleteAt,
); err != nil {
return goods, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&goods.GoodsId,
&goods.GoodsNum,
&goods.GoodsDividend,
&goods.GoodsDividendStatus,
&goods.GoodsName,
&goods.GoodsTotalPrice,
&goods.Remarks,
&goods.OrderNo,
&goods.GoodsDetail,
&goods.CreateAt,
&goods.UpdateAt,
&goods.DeleteAt,
),
fmt.Sprintf("UPDATE goodss SET %s WHERE goods_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
goods.GoodsId,
goods.GoodsNum,
goods.GoodsDividend,
goods.GoodsDividendStatus,
goods.GoodsName,
goods.GoodsTotalPrice,
goods.Remarks,
goods.OrderNo,
goods.GoodsDetail,
goods.CreateAt,
goods.UpdateAt,
goods.DeleteAt,
goods.Identify(),
); err != nil {
return goods, err
}
}
return goods, nil
}
func (repository *GoodsRepository) Remove(goods *domain.Goods) (*domain.Goods, error) {
tx := repository.transactionContext.PgTx
goodsModel := new(models.Goods)
goodsModel.GoodsId = goods.Identify().(int64)
if _, err := tx.Model(goodsModel).WherePK().Delete(); err != nil {
return goods, err
}
return goods, nil
}
func (repository *GoodsRepository) FindOne(queryOptions map[string]interface{}) (*domain.Goods, error) {
tx := repository.transactionContext.PgTx
goodsModel := new(models.Goods)
query := sqlbuilder.BuildQuery(tx.Model(goodsModel), queryOptions)
query.SetWhereByQueryOption("goods.goods_id = ?", "goodsId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if goodsModel.GoodsId == 0 {
return nil, nil
} else {
return transform.TransformToGoodsDomainModelFromPgModels(goodsModel)
}
}
func (repository *GoodsRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Goods, error) {
tx := repository.transactionContext.PgTx
var goodsModels []*models.Goods
goodss := make([]*domain.Goods, 0)
query := sqlbuilder.BuildQuery(tx.Model(&goodsModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("goods_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, goodss, err
} else {
for _, goodsModel := range goodsModels {
if goods, err := transform.TransformToGoodsDomainModelFromPgModels(goodsModel); err != nil {
return 0, goodss, err
} else {
goodss = append(goodss, goods)
}
}
return int64(count), goodss, nil
}
}
func NewGoodsRepository(transactionContext *pgTransaction.TransactionContext) (*GoodsRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &GoodsRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/transform"
)
type OrderRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *OrderRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *OrderRepository) Save(order *domain.Order) (*domain.Order, error) {
sqlBuildFields := []string{
"order_id",
"buyer",
"company_id",
"partner_id",
"delivery_code",
"is_disable",
"order_no",
"order_detail",
"order_dividend",
"order_dividend_status",
"order_goods",
"order_source",
"order_type",
"order_status",
"total_price",
"region_info",
"remarks",
"create_at",
"update_at",
"delete_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "order_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if order.Identify() == nil {
orderId, err := repository.nextIdentify()
if err != nil {
return order, err
} else {
order.OrderId = orderId
}
if _, err := tx.QueryOne(
pg.Scan(
&order.OrderId,
&order.Buyer,
&order.CompanyId,
&order.PartnerId,
&order.DeliveryCode,
&order.IsDisable,
&order.OrderNo,
&order.OrderDetail,
&order.OrderDividend,
&order.OrderDividendStatus,
pg.Array(&order.OrderGoods),
&order.OrderSource,
&order.OrderType,
&order.OrderStatus,
&order.TotalPrice,
&order.RegionInfo,
&order.Remarks,
&order.CreateAt,
&order.UpdateAt,
&order.DeleteAt,
),
fmt.Sprintf("INSERT INTO orders (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
order.OrderId,
order.Buyer,
order.CompanyId,
order.PartnerId,
order.DeliveryCode,
order.IsDisable,
order.OrderNo,
order.OrderDetail,
order.OrderDividend,
order.OrderDividendStatus,
pg.Array(order.OrderGoods),
order.OrderSource,
order.OrderType,
order.OrderStatus,
order.TotalPrice,
order.RegionInfo,
order.Remarks,
order.CreateAt,
order.UpdateAt,
order.DeleteAt,
); err != nil {
return order, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&order.OrderId,
&order.Buyer,
&order.CompanyId,
&order.PartnerId,
&order.DeliveryCode,
&order.IsDisable,
&order.OrderNo,
&order.OrderDetail,
&order.OrderDividend,
&order.OrderDividendStatus,
pg.Array(&order.OrderGoods),
&order.OrderSource,
&order.OrderType,
&order.OrderStatus,
&order.TotalPrice,
&order.RegionInfo,
&order.Remarks,
&order.CreateAt,
&order.UpdateAt,
&order.DeleteAt,
),
fmt.Sprintf("UPDATE orders SET %s WHERE order_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
order.OrderId,
order.Buyer,
order.CompanyId,
order.PartnerId,
order.DeliveryCode,
order.IsDisable,
order.OrderNo,
order.OrderDetail,
order.OrderDividend,
order.OrderDividendStatus,
pg.Array(order.OrderGoods),
order.OrderSource,
order.OrderType,
order.OrderStatus,
order.TotalPrice,
order.RegionInfo,
order.Remarks,
order.CreateAt,
order.UpdateAt,
order.DeleteAt,
order.Identify(),
); err != nil {
return order, err
}
}
return order, nil
}
func (repository *OrderRepository) Remove(order *domain.Order) (*domain.Order, error) {
tx := repository.transactionContext.PgTx
orderModel := new(models.Order)
orderModel.OrderId = order.Identify().(int64)
if _, err := tx.Model(orderModel).WherePK().Delete(); err != nil {
return order, err
}
return order, nil
}
func (repository *OrderRepository) FindOne(queryOptions map[string]interface{}) (*domain.Order, error) {
tx := repository.transactionContext.PgTx
orderModel := new(models.Order)
query := sqlbuilder.BuildQuery(tx.Model(orderModel), queryOptions)
query.SetWhereByQueryOption("order.order_id = ?", "orderId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if orderModel.OrderId == 0 {
return nil, nil
} else {
return transform.TransformToOrderDomainModelFromPgModels(orderModel)
}
}
func (repository *OrderRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Order, error) {
tx := repository.transactionContext.PgTx
var orderModels []*models.Order
orders := make([]*domain.Order, 0)
query := sqlbuilder.BuildQuery(tx.Model(&orderModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("order_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, orders, err
} else {
for _, orderModel := range orderModels {
if order, err := transform.TransformToOrderDomainModelFromPgModels(orderModel); err != nil {
return 0, orders, err
} else {
orders = append(orders, order)
}
}
return int64(count), orders, nil
}
}
func NewOrderRepository(transactionContext *pgTransaction.TransactionContext) (*OrderRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &OrderRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/transform"
)
type PartnerCategoryRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *PartnerCategoryRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *PartnerCategoryRepository) Save(partnerCategory *domain.PartnerCategory) (*domain.PartnerCategory, error) {
sqlBuildFields := []string{
"partner_category_id",
"partner_category_code",
"partner_category_name",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "partnerCategory_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if partnerCategory.Identify() == nil {
partnerCategoryId, err := repository.nextIdentify()
if err != nil {
return partnerCategory, err
} else {
partnerCategory.PartnerCategoryId = int(partnerCategoryId)
}
if _, err := tx.QueryOne(
pg.Scan(
&partnerCategory.PartnerCategoryId,
&partnerCategory.PartnerCategoryCode,
&partnerCategory.PartnerCategoryName,
),
fmt.Sprintf("INSERT INTO partner_categorys (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
partnerCategory.PartnerCategoryId,
partnerCategory.PartnerCategoryCode,
partnerCategory.PartnerCategoryName,
); err != nil {
return partnerCategory, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&partnerCategory.PartnerCategoryId,
&partnerCategory.PartnerCategoryCode,
&partnerCategory.PartnerCategoryName,
),
fmt.Sprintf("UPDATE partner_categorys SET %s WHERE partner_category_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
partnerCategory.PartnerCategoryId,
partnerCategory.PartnerCategoryCode,
partnerCategory.PartnerCategoryName,
partnerCategory.Identify(),
); err != nil {
return partnerCategory, err
}
}
return partnerCategory, nil
}
func (repository *PartnerCategoryRepository) Remove(partnerCategory *domain.PartnerCategory) (*domain.PartnerCategory, error) {
tx := repository.transactionContext.PgTx
partnerCategoryModel := new(models.PartnerCategory)
partnerCategoryModel.PartnerCategoryId = partnerCategory.Identify().(int)
if _, err := tx.Model(partnerCategoryModel).WherePK().Delete(); err != nil {
return partnerCategory, err
}
return partnerCategory, nil
}
func (repository *PartnerCategoryRepository) FindOne(queryOptions map[string]interface{}) (*domain.PartnerCategory, error) {
tx := repository.transactionContext.PgTx
partnerCategoryModel := new(models.PartnerCategory)
query := sqlbuilder.BuildQuery(tx.Model(partnerCategoryModel), queryOptions)
query.SetWhereByQueryOption("partner_category.partner_category_id = ?", "partnerCategoryId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if partnerCategoryModel.PartnerCategoryId == 0 {
return nil, nil
} else {
return transform.TransformToPartnerCategoryDomainModelFromPgModels(partnerCategoryModel)
}
}
func (repository *PartnerCategoryRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.PartnerCategory, error) {
tx := repository.transactionContext.PgTx
var partnerCategoryModels []*models.PartnerCategory
partnerCategorys := make([]*domain.PartnerCategory, 0)
query := sqlbuilder.BuildQuery(tx.Model(&partnerCategoryModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("partner_category_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, partnerCategorys, err
} else {
for _, partnerCategoryModel := range partnerCategoryModels {
if partnerCategory, err := transform.TransformToPartnerCategoryDomainModelFromPgModels(partnerCategoryModel); err != nil {
return 0, partnerCategorys, err
} else {
partnerCategorys = append(partnerCategorys, partnerCategory)
}
}
return int64(count), partnerCategorys, nil
}
}
func NewPartnerCategoryRepository(transactionContext *pgTransaction.TransactionContext) (*PartnerCategoryRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &PartnerCategoryRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/transform"
)
type PermissionRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *PermissionRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *PermissionRepository) Save(permission *domain.Permission) (*domain.Permission, error) {
sqlBuildFields := []string{
"permission_id",
"name",
"code",
"parent_id",
"sort",
"icon",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "permission_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if permission.Identify() == nil {
permissionId, err := repository.nextIdentify()
if err != nil {
return permission, err
} else {
permission.PermissionId = int(permissionId)
}
if _, err := tx.QueryOne(
pg.Scan(
&permission.PermissionId,
&permission.Name,
&permission.Code,
&permission.ParentId,
&permission.Sort,
&permission.Icon,
),
fmt.Sprintf("INSERT INTO permissions (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
permission.PermissionId,
permission.Name,
permission.Code,
permission.ParentId,
permission.Sort,
permission.Icon,
); err != nil {
return permission, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&permission.PermissionId,
&permission.Name,
&permission.Code,
&permission.ParentId,
&permission.Sort,
&permission.Icon,
),
fmt.Sprintf("UPDATE permissions SET %s WHERE permission_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
permission.PermissionId,
permission.Name,
permission.Code,
permission.ParentId,
permission.Sort,
permission.Icon,
permission.Identify(),
); err != nil {
return permission, err
}
}
return permission, nil
}
func (repository *PermissionRepository) Remove(permission *domain.Permission) (*domain.Permission, error) {
tx := repository.transactionContext.PgTx
permissionModel := new(models.Permission)
permissionModel.PermissionId = permission.Identify().(int)
if _, err := tx.Model(permissionModel).WherePK().Delete(); err != nil {
return permission, err
}
return permission, nil
}
func (repository *PermissionRepository) FindOne(queryOptions map[string]interface{}) (*domain.Permission, error) {
tx := repository.transactionContext.PgTx
permissionModel := new(models.Permission)
query := sqlbuilder.BuildQuery(tx.Model(permissionModel), queryOptions)
query.SetWhereByQueryOption("permission.permission_id = ?", "permissionId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if permissionModel.PermissionId == 0 {
return nil, nil
} else {
return transform.TransformToPermissionDomainModelFromPgModels(permissionModel)
}
}
func (repository *PermissionRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Permission, error) {
tx := repository.transactionContext.PgTx
var permissionModels []*models.Permission
permissions := make([]*domain.Permission, 0)
query := sqlbuilder.BuildQuery(tx.Model(&permissionModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("permission_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, permissions, err
} else {
for _, permissionModel := range permissionModels {
if permission, err := transform.TransformToPermissionDomainModelFromPgModels(permissionModel); err != nil {
return 0, permissions, err
} else {
permissions = append(permissions, permission)
}
}
return int64(count), permissions, nil
}
}
func NewPermissionRepository(transactionContext *pgTransaction.TransactionContext) (*PermissionRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &PermissionRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/transform"
)
type UserAuthRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *UserAuthRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *UserAuthRepository) Save(userAuth *domain.UserAuth) (*domain.UserAuth, error) {
sqlBuildFields := []string{
"user_auth_id",
"users",
"phone_auth",
"create_at",
"update_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "userAuth_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if userAuth.Identify() == nil {
userAuthId, err := repository.nextIdentify()
if err != nil {
return userAuth, err
} else {
userAuth.UserAuthId = userAuthId
}
if _, err := tx.QueryOne(
pg.Scan(
&userAuth.UserAuthId,
pg.Array(&userAuth.Users),
&userAuth.PhoneAuth,
&userAuth.CreateAt,
&userAuth.UpdateAt,
),
fmt.Sprintf("INSERT INTO user_auth (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
userAuth.UserAuthId,
pg.Array(userAuth.Users),
userAuth.PhoneAuth,
userAuth.CreateAt,
userAuth.UpdateAt,
); err != nil {
return userAuth, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&userAuth.UserAuthId,
pg.Array(&userAuth.Users),
&userAuth.PhoneAuth,
&userAuth.CreateAt,
&userAuth.UpdateAt,
),
fmt.Sprintf("UPDATE user_auth SET %s WHERE user_auth_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
userAuth.UserAuthId,
pg.Array(userAuth.Users),
userAuth.PhoneAuth,
userAuth.CreateAt,
userAuth.UpdateAt,
userAuth.Identify(),
); err != nil {
return userAuth, err
}
}
return userAuth, nil
}
func (repository *UserAuthRepository) Remove(userAuth *domain.UserAuth) (*domain.UserAuth, error) {
tx := repository.transactionContext.PgTx
userAuthModel := new(models.UserAuth)
userAuthModel.UserAuthId = userAuth.Identify().(int64)
if _, err := tx.Model(userAuthModel).WherePK().Delete(); err != nil {
return userAuth, err
}
return userAuth, nil
}
func (repository *UserAuthRepository) FindOne(queryOptions map[string]interface{}) (*domain.UserAuth, error) {
tx := repository.transactionContext.PgTx
userAuthModel := new(models.UserAuth)
query := sqlbuilder.BuildQuery(tx.Model(userAuthModel), queryOptions)
query.SetWhereByQueryOption("user_auth.user_auth_id = ?", "userAuthId")
if v, ok := queryOptions["phone"]; ok {
query.Where(fmt.Sprintf(`user_auth.phone_auth @>'{"phone":"%v"}'`, v))
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if userAuthModel.UserAuthId == 0 {
return nil, nil
} else {
return transform.TransformToUserAuthDomainModelFromPgModels(userAuthModel)
}
}
func (repository *UserAuthRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.UserAuth, error) {
tx := repository.transactionContext.PgTx
var userAuthModels []*models.UserAuth
userAuths := make([]*domain.UserAuth, 0)
query := sqlbuilder.BuildQuery(tx.Model(&userAuthModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("user_auth_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, userAuths, err
} else {
for _, userAuthModel := range userAuthModels {
if userAuth, err := transform.TransformToUserAuthDomainModelFromPgModels(userAuthModel); err != nil {
return 0, userAuths, err
} else {
userAuths = append(userAuths, userAuth)
}
}
return int64(count), userAuths, nil
}
}
func NewUserAuthRepository(transactionContext *pgTransaction.TransactionContext) (*UserAuthRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &UserAuthRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg/transform"
)
type UserRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *UserRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *UserRepository) Save(user *domain.User) (*domain.User, error) {
sqlBuildFields := []string{
"user_id",
"user_type",
"permissions",
"company_id",
"user_info",
"partner_info",
"status",
"admin_type",
"access_partners",
"create_at",
"update_at",
"delete_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if user.Identify() == nil {
userId, err := repository.nextIdentify()
if err != nil {
return user, err
} else {
user.UserId = userId
}
if _, err := tx.QueryOne(
pg.Scan(
&user.UserId,
&user.UserType,
pg.Array(&user.Permissions),
&user.CompanyId,
&user.UserInfo,
&user.PartnerInfo,
&user.Status,
&user.AdminType,
pg.Array(&user.AccessPartners),
&user.CreateAt,
&user.UpdateAt,
&user.DeleteAt,
),
fmt.Sprintf("INSERT INTO users (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
user.UserId,
user.UserType,
pg.Array(user.Permissions),
user.CompanyId,
user.UserInfo,
user.PartnerInfo,
user.Status,
user.AdminType,
pg.Array(user.AccessPartners),
user.CreateAt,
user.UpdateAt,
user.DeleteAt,
); err != nil {
return user, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&user.UserId,
&user.UserType,
pg.Array(&user.Permissions),
&user.CompanyId,
&user.UserInfo,
&user.PartnerInfo,
&user.Status,
&user.AdminType,
pg.Array(&user.AccessPartners),
&user.CreateAt,
&user.UpdateAt,
&user.DeleteAt,
),
fmt.Sprintf("UPDATE users SET %s WHERE user_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
user.UserId,
user.UserType,
pg.Array(user.Permissions),
user.CompanyId,
user.UserInfo,
user.PartnerInfo,
user.Status,
user.AdminType,
pg.Array(user.AccessPartners),
user.CreateAt,
user.UpdateAt,
user.DeleteAt,
user.Identify(),
); err != nil {
return user, err
}
}
return user, nil
}
func (repository *UserRepository) Remove(user *domain.User) (*domain.User, error) {
tx := repository.transactionContext.PgTx
userModel := new(models.User)
userModel.UserId = user.Identify().(int64)
if _, err := tx.Model(userModel).WherePK().Delete(); err != nil {
return user, err
}
return user, nil
}
func (repository *UserRepository) FindOne(queryOptions map[string]interface{}) (*domain.User, error) {
tx := repository.transactionContext.PgTx
userModel := new(models.User)
query := sqlbuilder.BuildQuery(tx.Model(userModel), queryOptions)
query.SetWhereByQueryOption("users.user_id = ?", "userId")
query.SetWhereByQueryOption("users.status = ?", "status")
query.SetWhereByQueryOption("users.user_type = ?", "userType")
if v, ok := queryOptions["inUserIds"]; ok {
query.Where("users.user_id in (?)", pg.Array(v))
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if userModel.UserId == 0 {
return nil, nil
} else {
return transform.TransformToUserDomainModelFromPgModels(userModel)
}
}
func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.User, error) {
tx := repository.transactionContext.PgTx
var userModels []*models.User
users := make([]*domain.User, 0)
query := sqlbuilder.BuildQuery(tx.Model(&userModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("user_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, users, err
} else {
for _, userModel := range userModels {
if user, err := transform.TransformToUserDomainModelFromPgModels(userModel); err != nil {
return 0, users, err
} else {
users = append(users, user)
}
}
return int64(count), users, nil
}
}
func NewUserRepository(transactionContext *pgTransaction.TransactionContext) (*UserRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &UserRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package log
import (
"github.com/linmadan/egglib-go/log"
"github.com/linmadan/egglib-go/log/logrus"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/constant"
)
var Logger log.Logger
func init() {
Logger = logrus.NewLogrusLogger()
Logger.SetServiceName(constant.SERVICE_NAME)
Logger.SetLevel(constant.LOG_LEVEL)
}
... ...
package beego
import (
"github.com/beego/beego/v2/server/web"
"github.com/linmadan/egglib-go/web/beego/filters"
"os"
"strconv"
. "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/log"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego/routers"
)
func init() {
web.BConfig.AppName = "partner01"
web.BConfig.CopyRequestBody = true
web.BConfig.RunMode = "dev"
web.BConfig.Listen.HTTPPort = 8081
web.BConfig.Listen.EnableAdmin = false
web.BConfig.WebConfig.CommentRouterPath = "/pkg/port/beego"
if os.Getenv("RUN_MODE") != "" {
web.BConfig.RunMode = os.Getenv("RUN_MODE")
}
if os.Getenv("HTTP_PORT") != "" {
portStr := os.Getenv("HTTP_PORT")
if port, err := strconv.Atoi(portStr); err == nil {
web.BConfig.Listen.HTTPPort = port
}
}
web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(Logger))
web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/auth/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/auth/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/auth/service"
)
type AuthController struct {
beego.BaseController
}
func (controller *AuthController) Login() {
authService := service.NewAuthService(nil)
loginQuery := &query.LoginQuery{}
controller.Unmarshal(loginQuery)
data, err := authService.Login(loginQuery)
controller.Response(data, err)
}
func (controller *AuthController) LoginByCompany() {
authService := service.NewAuthService(nil)
loginByCompanyCommand := &command.LoginByCompanyCommand{}
controller.Unmarshal(loginByCompanyCommand)
data, err := authService.LoginByCompany(loginByCompanyCommand)
controller.Response(data, err)
}
func (controller *AuthController) AccessToken() {
authService := service.NewAuthService(nil)
accessTokenCommand := &command.AccessTokenCommand{}
controller.Unmarshal(accessTokenCommand)
data, err := authService.AccessToken(accessTokenCommand)
controller.Response(data, err)
}
func (controller *AuthController) RefreshToken() {
authService := service.NewAuthService(nil)
refreshTokenCommand := &command.RefreshTokenCommand{}
controller.Unmarshal(refreshTokenCommand)
data, err := authService.RefreshToken(refreshTokenCommand)
controller.Response(data, err)
}
func (controller *AuthController) SendSmsCode() {
authService := service.NewAuthService(nil)
sendSmsCodeCommand := &command.SendSmsCodeCommand{}
controller.Unmarshal(sendSmsCodeCommand)
data, err := authService.SendSmsCode(sendSmsCodeCommand)
controller.Response(data, err)
}
func (controller *AuthController) Revoke() {
authService := service.NewAuthService(nil)
revokeCommand := &command.RevokeCommand{}
controller.Unmarshal(revokeCommand)
data, err := authService.Revoke(revokeCommand)
controller.Response(data, err)
}
func (controller *AuthController) ChangePassword() {
authService := service.NewAuthService(nil)
changePasswordCommand := &command.ChangePasswordCommand{}
controller.Unmarshal(changePasswordCommand)
data, err := authService.ChangePassword(changePasswordCommand)
controller.Response(data, err)
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/company/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/company/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/company/service"
)
type CompanyController struct {
beego.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)
companyId, _ := controller.GetInt64(":companyId")
updateCompanyCommand.CompanyId = companyId
data, err := companyService.UpdateCompany(updateCompanyCommand)
controller.Response(data, err)
}
func (controller *CompanyController) GetCompany() {
companyService := service.NewCompanyService(nil)
getCompanyQuery := &query.GetCompanyQuery{}
companyId, _ := controller.GetInt64(":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) ListCompany() {
companyService := service.NewCompanyService(nil)
listCompanyQuery := &query.ListCompanyQuery{}
offset, _ := controller.GetInt("offset")
listCompanyQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listCompanyQuery.Limit = limit
data, err := companyService.ListCompany(listCompanyQuery)
controller.Response(data, err)
}
func (controller *CompanyController) ConvertCompanyStatus() {
companyService := service.NewCompanyService(nil)
convertCompanyStatusCommand := &command.ConvertCompanyStatusCommand{}
controller.Unmarshal(convertCompanyStatusCommand)
data, err := companyService.ConvertCompanyStatus(convertCompanyStatusCommand)
controller.Response(data, err)
}
func (controller *CompanyController) SetCompanyAdmin() {
companyService := service.NewCompanyService(nil)
setCompanyAdminCommand := &command.SetCompanyAdminCommand{}
controller.Unmarshal(setCompanyAdminCommand)
data, err := companyService.SetCompanyAdmin(setCompanyAdminCommand)
controller.Response(data, err)
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/order/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/order/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/order/service"
)
type OrderController struct {
beego.BaseController
}
func (controller *OrderController) CreateOrder() {
orderService := service.NewOrderService(nil)
createOrderCommand := &command.CreateOrderCommand{}
controller.Unmarshal(createOrderCommand)
data, err := orderService.CreateOrder(createOrderCommand)
controller.Response(data, err)
}
func (controller *OrderController) UpdateOrder() {
orderService := service.NewOrderService(nil)
updateOrderCommand := &command.UpdateOrderCommand{}
_ = controller.Unmarshal(updateOrderCommand)
orderId, _ := controller.GetInt64(":orderId")
updateOrderCommand.OrderId = orderId
data, err := orderService.UpdateOrder(updateOrderCommand)
controller.Response(data, err)
}
func (controller *OrderController) GetOrder() {
orderService := service.NewOrderService(nil)
getOrderQuery := &query.GetOrderQuery{}
orderId, _ := controller.GetInt64(":orderId")
getOrderQuery.OrderId = orderId
data, err := orderService.GetOrder(getOrderQuery)
controller.Response(data, err)
}
func (controller *OrderController) RemoveOrder() {
orderService := service.NewOrderService(nil)
removeOrderCommand := &command.RemoveOrderCommand{}
_ = controller.Unmarshal(removeOrderCommand)
orderId, _ := controller.GetInt64(":orderId")
removeOrderCommand.OrderId = orderId
data, err := orderService.RemoveOrder(removeOrderCommand)
controller.Response(data, err)
}
func (controller *OrderController) ListOrder() {
orderService := service.NewOrderService(nil)
listOrderQuery := &query.ListOrderQuery{}
offset, _ := controller.GetInt("offset")
listOrderQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listOrderQuery.Limit = limit
data, err := orderService.ListOrder(listOrderQuery)
controller.Response(data, err)
}
func (controller *OrderController) Shipping() {
orderService := service.NewOrderService(nil)
shippingCmd := &command.ShippingGoodsCommand{}
_ = controller.Unmarshal(shippingCmd)
orderId, _ := controller.GetInt(":orderId")
shippingCmd.OrderId = orderId
data, err := orderService.ShippingGoods(shippingCmd)
controller.Response(data, err)
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/partner/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/partner/service"
)
type PartnerController struct {
beego.BaseController
}
func (controller *PartnerController) PartnerCategories() {
partnerService := service.NewPartnerService(nil)
partnerCategoriesQuery := &query.PartnerCategoriesQuery{}
data, err := partnerService.PartnerCategories(partnerCategoriesQuery)
controller.Response(data, err)
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/permission/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/application/permission/service"
)
type PermissionController struct {
beego.BaseController
}
func (controller *PermissionController) Menus() {
permissionService := service.NewPermissionService(nil)
menusQuery := &query.MenusQuery{}
data, err := permissionService.Menus(menusQuery)
controller.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego/controllers"
)
func init() {
web.Router("/auths/login", &controllers.AuthController{}, "Post:Login")
web.Router("/auths/loginByCompany", &controllers.AuthController{}, "Post:LoginByCompany")
web.Router("/auths/accessToken", &controllers.AuthController{}, "Post:AccessToken")
web.Router("/auths/refreshToken", &controllers.AuthController{}, "Post:RefreshToken")
web.Router("/auths/sendSmsCode", &controllers.AuthController{}, "Post:SendSmsCode")
web.Router("/auths/revoke", &controllers.AuthController{}, "Post:Revoke")
web.Router("/auths/changePhonePassword", &controllers.AuthController{}, "Post:ChangePassword")
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego/controllers"
)
func init() {
web.Router("/companies/", &controllers.CompanyController{}, "Post:CreateCompany")
web.Router("/companies/:companyId", &controllers.CompanyController{}, "Put:UpdateCompany")
web.Router("/companies/:companyId", &controllers.CompanyController{}, "Get:GetCompany")
web.Router("/companies/:companyId", &controllers.CompanyController{}, "Delete:RemoveCompany")
web.Router("/companies/", &controllers.CompanyController{}, "Get:ListCompany")
web.Router("/companies/convertCompanyStatus", &controllers.CompanyController{}, "Post:ConvertCompanyStatus")
web.Router("/companies/setCompanyAdmin", &controllers.CompanyController{}, "Post:SetCompanyAdmin")
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego/controllers"
)
func init() {
web.Router("/orders/", &controllers.OrderController{}, "Post:CreateOrder")
web.Router("/orders/:orderId", &controllers.OrderController{}, "Put:UpdateOrder")
web.Router("/orders/:orderId", &controllers.OrderController{}, "Get:GetOrder")
web.Router("/orders/:orderId", &controllers.OrderController{}, "Delete:RemoveOrder")
web.Router("/orders/", &controllers.OrderController{}, "Get:ListOrder")
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego/controllers"
)
func init() {
web.Router("/partners/categories", &controllers.PartnerController{}, "Get:PartnerCategories")
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego/controllers"
)
func init() {
web.Router("/permission/menus", &controllers.PermissionController{}, "Get:Menus")
}
... ...
package auth
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
)
var _ = Describe("用户按公司登录", func() {
//var Id int64
//return
BeforeEach(func() {
//_, err := pG.DB.QueryOne(
// pg.Scan(&Id),
// "INSERT INTO s () VALUES () RETURNING _id",
//)
//Expect(err).NotTo(HaveOccurred())
})
Describe("用户按公司登录", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"authCode": domain.SignToken(1, 1000),
}
httpExpect.POST("/auths/accessToken").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
//_, err := pG.DB.Exec("DELETE FROM s WHERE true")
//Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/gateway"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego"
)
func TestAuth(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port Auth Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("修改手机号密码", func() {
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
)
Expect(err).NotTo(HaveOccurred())
})
Describe("修改手机号密码", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"oldPwd": "password",
"newPwd": "newPassword",
"confirmPwd": "newPassword",
"phone": "18800000001",
}
httpExpect.POST("/auths/changePhonePassword").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok")
//ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM user_auth WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("用户按公司登录", func() {
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
"INSERT INTO users (user_id,user_type,company_id) VALUES (1,1,1000) RETURNING user_id",
)
_, err = pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO companys (company_id,company_info) VALUES (1000,'{"company_id":1000,"name":"company","status":1}') RETURNING company_id`,
)
_, err = pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
)
Expect(err).NotTo(HaveOccurred())
})
Describe("用户按公司登录", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"userType": 1,
"credentials": "string",
"userId": 1,
}
httpExpect.POST("/auths/loginByCompany").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM users WHERE true")
_, err = pG.DB.Exec("DELETE FROM companys WHERE true")
_, err = pG.DB.Exec("DELETE FROM user_auth WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("用户登录 返回有权限的公司列表", func() {
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
"INSERT INTO users (user_id,user_type,company_id) VALUES (1,1,1000) RETURNING user_id",
)
_, err = pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO companys (company_id,company_info) VALUES (1000,'{"company_id":1000,"name":"company"}') RETURNING company_id`,
)
_, err = pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
)
Expect(err).NotTo(HaveOccurred())
})
Describe("用户登录 返回有权限的公司列表", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"phone": "18800000001",
"grantType": "signInPassword",
"password": "password",
"captcha": "",
"credentials": "",
}
httpExpect.POST("/auths/login").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM users WHERE true")
_, err = pG.DB.Exec("DELETE FROM companys WHERE true")
_, err = pG.DB.Exec("DELETE FROM user_auth WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/domain"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
)
var _ = Describe("更新授权令牌accessToken", func() {
//return
//var Id int64
BeforeEach(func() {
//_, err := pG.DB.QueryOne(
// pg.Scan(&Id),
// "INSERT INTO s () VALUES () RETURNING _id",
//)
//Expect(err).NotTo(HaveOccurred())
})
Describe("更新授权令牌accessToken", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"refreshToken": domain.SignToken(1, 1000),
}
httpExpect.POST("/auths/refreshToken").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
//_, err := pG.DB.Exec("DELETE FROM s WHERE true")
//Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("注销登录", func() {
return
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
"INSERT INTO s () VALUES () RETURNING _id",
)
Expect(err).NotTo(HaveOccurred())
})
Describe("注销登录", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.POST("/auths/revoke").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM s WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("发送验证码", func() {
return
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
"INSERT INTO s () VALUES () RETURNING _id",
)
Expect(err).NotTo(HaveOccurred())
})
Describe("发送验证码", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"phone": "string",
}
httpExpect.POST("/auths/sendSmsCode").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM s WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package order
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = FDescribe("创建订单增删改查", func() {
Describe("提交数据创建订单增删改查", func() {
Context("提交正确的新订单实体数据", func() {
It("返回订单实体数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"orderNo": "string",
"companyId": "int64",
"buyerName": "string",
"contactInfo": "string",
"shippingAddress": "string",
"orderNum": "int64",
"totalPrice": "float64",
}
httpExpect.POST("/orders/").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("orderId").ValueNotEqual("orderId", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM orders WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package order
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("返回订单增删改查", func() {
var orderId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&orderId),
"INSERT INTO orders (order_id, buyer, company_id, partner_id, delivery_code, is_disable, order_no, order_detail, order_dividend, order_dividend_status, order_goods, order_source, order_type, order_status, total_price, region_info, remarks, create_at, update_at, delete_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING order_id",
"testOrderId", "testBuyer", "testCompanyId", "testPartnerId", "testDeliveryCode", "testIsDisable", "testOrderNo", "testOrderDetail", "testOrderDividend", "testOrderDividendStatus", "testOrderGoods", "testOrderSource", "testOrderType", "testOrderStatus", "testTotalPrice", "testRegionInfo", "testRemarks", "testCreateAt", "testUpdateAt", "testDeleteAt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据orderId参数返回订单实体", func() {
Context("传入有效的orderId", func() {
It("返回订单实体数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/orders/{orderId}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM orders WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package order
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("返回订单增删改查列表", func() {
var orderId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&orderId),
"INSERT INTO orders (order_id, buyer, company_id, partner_id, delivery_code, is_disable, order_no, order_detail, order_dividend, order_dividend_status, order_goods, order_source, order_type, order_status, total_price, region_info, remarks, create_at, update_at, delete_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING order_id",
"testOrderId", "testBuyer", "testCompanyId", "testPartnerId", "testDeliveryCode", "testIsDisable", "testOrderNo", "testOrderDetail", "testOrderDividend", "testOrderDividendStatus", "testOrderGoods", "testOrderSource", "testOrderType", "testOrderStatus", "testTotalPrice", "testRegionInfo", "testRemarks", "testCreateAt", "testUpdateAt", "testDeleteAt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数返回订单实体列表", func() {
Context("传入有效的参数", func() {
It("返回订单实体数据列表", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/orders/").
WithQuery("offset", "int").
WithQuery("limit", "int").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("count").ValueEqual("count", 1).
ContainsKey("orders").Value("orders").Array()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM orders WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package order
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego"
)
func TestOrder(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port Order Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package order
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("移除订单增删改查", func() {
var orderId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&orderId),
"INSERT INTO orders (order_id, buyer, company_id, partner_id, delivery_code, is_disable, order_no, order_detail, order_dividend, order_dividend_status, order_goods, order_source, order_type, order_status, total_price, region_info, remarks, create_at, update_at, delete_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING order_id",
"testOrderId", "testBuyer", "testCompanyId", "testPartnerId", "testDeliveryCode", "testIsDisable", "testOrderNo", "testOrderDetail", "testOrderDividend", "testOrderDividendStatus", "testOrderGoods", "testOrderSource", "testOrderType", "testOrderStatus", "testTotalPrice", "testRegionInfo", "testRemarks", "testCreateAt", "testUpdateAt", "testDeleteAt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数移除订单增删改查", func() {
Context("传入有效的orderId", func() {
It("返回被移除订单实体的数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.DELETE("/orders/{orderId}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM orders WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package order
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("更新订单增删改查", func() {
var orderId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&orderId),
"INSERT INTO orders (order_id, buyer, company_id, partner_id, delivery_code, is_disable, order_no, order_detail, order_dividend, order_dividend_status, order_goods, order_source, order_type, order_status, total_price, region_info, remarks, create_at, update_at, delete_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING order_id",
"testOrderId", "testBuyer", "testCompanyId", "testPartnerId", "testDeliveryCode", "testIsDisable", "testOrderNo", "testOrderDetail", "testOrderDividend", "testOrderDividendStatus", "testOrderGoods", "testOrderSource", "testOrderType", "testOrderStatus", "testTotalPrice", "testRegionInfo", "testRemarks", "testCreateAt", "testUpdateAt", "testDeleteAt")
Expect(err).NotTo(HaveOccurred())
})
Describe("提交数据更新订单增删改查", func() {
Context("提交正确的订单实体数据", func() {
It("返回更新后的订单实体数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.PUT("/orders/{orderId}").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("orderId").ValueEqual("orderId", orderId)
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM orders WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package partner
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("合伙人分类列表", func() {
var id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&id),
"INSERT INTO partner_category (partner_category_id,partner_category_code,partner_category_name) VALUES (?,?,?) RETURNING partner_category_id",
1000, "testPartnerCategoryCode", "testPartnerCategoryName")
Expect(err).NotTo(HaveOccurred())
})
Describe("合伙人分类列表", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/partners/categories").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM partner_category WHERE partner_category_id = 1000")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package partner
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego"
)
func TestPartner(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port Partner Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package permission
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
)
var _ = Describe("根据当前用户返回权限列表", func() {
var permissionId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&permissionId),
"INSERT INTO permissions (permission_id,name,code,parent_id,sort,icon) VALUES (?,?,?,?,?,?) RETURNING permission_id",
1000, "testPermission", "testPermissionCode", 0, 1, "testPermissionIcon")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据当前用户返回权限列表", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/permission/menus").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().ValueNotEqual("total", 0)
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM permissions WHERE permission_id = 1000")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package permission
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01-gateway/pkg/port/beego"
)
func TestPermission(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port Permission Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...