作者 yangfu

合伙人项目初始化

正在显示 53 个修改的文件 包含 2294 行增加0 行删除
# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
*.vscode
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
*.log
*debug
*wasm
*.idea
*.tmp
*.sum
opp
/vendor
/*.exe~
... ...
FROM golang:latest
ENV APP_DIR $GOPATH/src/partner
RUN mkdir -p $APP_DIR
WORKDIR $APP_DIR/
COPY ./pkg pkg
COPY ./conf conf
COPY ./go.mod go.mod
COPY ./main.go main.go
RUN ["ln","-sf","/usr/share/zoneinfo/Asia/Shanghai","/etc/localtime"]
ENV GO111MODULE on
ENV GOPROXY https://goproxy.cn
RUN ["go","mod","tidy"]
RUN ["go","build"]
ENTRYPOINT ["./partner"]
\ No newline at end of file
... ...
#价值系统
\ No newline at end of file
... ...
appname = partner
runmode = "${RUN_MODE||dev}"
httpport = "${HTTP_PORT||8080}"
#开启监控
EnableAdmin = false
#开启JSON请求
copyrequestbody = true
#防止跨站请求伪造 未启用
enablexsrf = false
xsrfkey = asdfioerjlasdfmFADFOEJF2323SDFF
xsrfexpire = 3600
[lang]
types = en-US|zh-CN
names = English|简体中文
\ No newline at end of file
... ...
#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n mmm-suplus-dev get pods | grep -q partner
if [ "$?" == "1" ];then
kubectl create -f /tmp/dev/partner/partner.yaml --record
kubectl -n mmm-suplus-dev get svc | grep -q partner
if [ "$?" == "0" ];then
echo "partner service install success!"
else
echo "partner service install fail!"
fi
kubectl -n mmm-suplus-dev get pods | grep -q partner
if [ "$?" == "0" ];then
echo "partner deployment install success!"
else
echo "partner deployment install fail!"
fi
else
kubectl delete -f /tmp/dev/partner/partner.yaml
kubectl -n mmm-suplus-dev get svc | grep -q partner
while [ "$?" == "0" ]
do
kubectl -n mmm-suplus-dev get svc | grep -q partner
done
kubectl -n mmm-suplus-dev get pods | grep -q partner
while [ "$?" == "0" ]
do
kubectl -n mmm-suplus-dev get pods | grep -q partner
done
kubectl create -f /tmp/dev/partner/partner.yaml --record
kubectl -n mmm-suplus-dev get svc | grep -q partner
if [ "$?" == "0" ];then
echo "partner service update success!"
else
echo "partner service update fail!"
fi
kubectl -n mmm-suplus-dev get pods | grep -q partner
if [ "$?" == "0" ];then
echo "partner deployment update success!"
else
echo "partner deployment update fail!"
fi
fi
\ No newline at end of file
... ...
apiVersion: v1
kind: Service
metadata:
name: partner
namespace: mmm-suplus-dev
labels:
k8s-app: partner
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
selector:
k8s-app: partner
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: partner
namespace: mmm-suplus-dev
labels:
k8s-app: partner
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: partner
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: partner
image: 192.168.0.243:5000/mmm/partner:dev
imagePullPolicy: Always
ports:
- containerPort: 8082
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
env:
- name: POSTGRESQL_DB_NAME
value: "partner_dev"
- name: POSTGRESQL_USER
value: "postgres"
- name: POSTGRESQL_PASSWORD
value: "postgres_15432"
- name: POSTGRESQL_HOST
value: "101.37.68.23"
- name: POSTGRESQL_PORT
value: "15432"
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
value: "1000"
- name: ABILITY_SERVICE_HOST
value: "https://suplus-worth-app-gateway-dev.fjmaimaimai.com"
- name: MMM_OPEN_API_SERVICE_HOST
value: "http://mmm-open-api-dev.fjmaimaimai.com"
volumes:
- name: accesslogs
emptyDir: {}
\ No newline at end of file
... ...
#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n mmm-suplus-prd get pods | grep -q partner
if [ "$?" == "1" ];then
kubectl create -f /tmp/prd/partner/partner.yaml --record
kubectl -n mmm-suplus-prd get svc | grep -q partner
if [ "$?" == "0" ];then
echo "partner service install success!"
else
echo "partner service install fail!"
fi
kubectl -n mmm-suplus-prd get pods | grep -q partner
if [ "$?" == "0" ];then
echo "partner deployment install success!"
else
echo "partner deployment install fail!"
fi
else
kubectl delete -f /tmp/prd/partner/partner.yaml
kubectl -n mmm-suplus-prd get svc | grep -q partner
while [ "$?" == "0" ]
do
kubectl -n mmm-suplus-prd get svc | grep -q partner
done
kubectl -n mmm-suplus-prd get pods | grep -q partner
while [ "$?" == "0" ]
do
kubectl -n mmm-suplus-prd get pods | grep -q partner
done
kubectl create -f /tmp/prd/partner/partner.yaml --record
kubectl -n mmm-suplus-prd get svc | grep -q partner
if [ "$?" == "0" ];then
echo "partner service update success!"
else
echo "partner service update fail!"
fi
kubectl -n mmm-suplus-prd get pods | grep -q partner
if [ "$?" == "0" ];then
echo "partner deployment update success!"
else
echo "partner deployment update fail!"
fi
fi
\ No newline at end of file
... ...
apiVersion: v1
kind: Service
metadata:
name: partner
namespace: mmm-suplus-prd
labels:
k8s-app: partner
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
selector:
k8s-app: partner
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: partner
namespace: mmm-suplus-prd
labels:
k8s-app: partner
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: partner
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: partner
image: 192.168.0.243:5000/mmm/partner:master
imagePullPolicy: Always
ports:
- containerPort: 8082
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
env:
- name: POSTGRESQL_DB_NAME
value: "partner"
- name: POSTGRESQL_USER
value: "postgres"
- name: POSTGRESQL_PASSWORD
value: "postgres_55_online"
- name: POSTGRESQL_HOST
value: "112.124.115.55"
- name: POSTGRESQL_PORT
value: "15432"
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
value: "1000"
- name: ABILITY_SERVICE_HOST
value: "https://ability.fjmaimaimai.com"
- name: MMM_OPEN_API_SERVICE_HOST
value: "https://public-interface.fjmaimaimai.com/openapi"
volumes:
- name: accesslogs
emptyDir: {}
\ No newline at end of file
... ...
#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n mmm-suplus-test get pods | grep -q partner
if [ "$?" == "1" ];then
kubectl create -f /tmp/test/partner/partner.yaml --record
kubectl -n mmm-suplus-test get svc | grep -q partner
if [ "$?" == "0" ];then
echo "partner service install success!"
else
echo "partner service install fail!"
fi
kubectl -n mmm-suplus-test get pods | grep -q partner
if [ "$?" == "0" ];then
echo "partner deployment install success!"
else
echo "partner deployment install fail!"
fi
else
kubectl delete -f /tmp/test/partner/partner.yaml
kubectl -n mmm-suplus-test get svc | grep -q partner
while [ "$?" == "0" ]
do
kubectl -n mmm-suplus-test get svc | grep -q partner
done
kubectl -n mmm-suplus-test get pods | grep -q partner
while [ "$?" == "0" ]
do
kubectl -n mmm-suplus-test get pods | grep -q partner
done
kubectl create -f /tmp/test/partner/partner.yaml --record
kubectl -n mmm-suplus-test get svc | grep -q partner
if [ "$?" == "0" ];then
echo "partner service update success!"
else
echo "partner service update fail!"
fi
kubectl -n mmm-suplus-test get pods | grep -q partner
if [ "$?" == "0" ];then
echo "partner deployment update success!"
else
echo "partner deployment update fail!"
fi
fi
\ No newline at end of file
... ...
apiVersion: v1
kind: Service
metadata:
name: partner
namespace: mmm-suplus-test
labels:
k8s-app: partner
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
selector:
k8s-app: partner
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: partner
namespace: mmm-suplus-test
labels:
k8s-app: partner
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: partner
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: partner
image: 192.168.0.243:5000/mmm/partner:test
imagePullPolicy: Always
ports:
- containerPort: 8082
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
env:
- name: POSTGRESQL_DB_NAME
value: "partner_test"
- name: POSTGRESQL_USER
value: "postgres"
- name: POSTGRESQL_PASSWORD
value: "postgres_15432"
- name: POSTGRESQL_HOST
value: "101.37.68.23"
- name: POSTGRESQL_PORT
value: "15432"
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
value: "1000"
- name: ABILITY_SERVICE_HOST
value: "https://suplus-worth-app-gateway-test.fjmaimaimai.com"
- name: MMM_OPEN_API_SERVICE_HOST
value: "http://mmm-open-api-test.fjmaimaimai.com"
volumes:
- name: accesslogs
emptyDir: {}
\ No newline at end of file
... ...
module gitlab.fjmaimaimai.com/mmm-go/partner
go 1.13
require (
github.com/ajg/form v1.5.1 // indirect
github.com/astaxie/beego v1.12.1
github.com/fatih/structs v1.1.0 // indirect
github.com/gavv/httpexpect v2.0.0+incompatible
github.com/go-pg/pg/v10 v10.0.0-beta.2
github.com/google/go-querystring v1.0.0 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/imkira/go-interpol v1.1.0 // indirect
github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9
github.com/moul/http2curl v1.0.0 // indirect
github.com/onsi/ginkgo v1.10.3
github.com/onsi/gomega v1.7.1
github.com/sergi/go-diff v1.1.0 // indirect
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
github.com/valyala/fasthttp v1.14.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
)
... ...
package main
import (
"github.com/astaxie/beego"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego"
)
func main() {
beego.Run()
}
... ...
package factory
//func CreateTaskDao(options map[string]interface{}) (*dao.TaskDao, error) {
// var transactionContext *pg.TransactionContext
// if value, ok := options["transactionContext"]; ok {
// transactionContext = value.(*pg.TransactionContext)
// }
// return dao.NewTaskDao(transactionContext)
//}
... ...
package factory
import (
//pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
//"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain/service"
//domainService "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/domain_service"
)
//func CreateReadSentNotificationService(options map[string]interface{}) (service.ReadSentNotificationService, error) {
// var transactionContext *pgTransaction.TransactionContext
// if value, ok := options["transactionContext"]; ok {
// transactionContext = value.(*pgTransaction.TransactionContext)
// }
// return domainService.NewReadSentNotificationService(transactionContext)
//}
... ...
package factory
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/repository"
)
//CreatePartnerInfoRepository 合伙人信息
func CreatePartnerInfoRepository(options map[string]interface{}) (domain.PartnerInfoRepository, error) {
var transactionContext *transaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*transaction.TransactionContext)
}
return repository.NewPartnerInfoRepository(transactionContext)
}
... ...
package factory
//import serviceGateway "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/service_gateway"
//
//func CreateAbilityServiceGateway(options map[string]interface{}) (serviceGateway.AbilityServiceGateway, error) {
// return serviceGateway.NewHttplibAbilityServiceGateway(), nil
//}
... ...
package factory
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
)
func CreateTransactionContext(options map[string]interface{}) (application.TransactionContext, error) {
return &transaction.TransactionContext{
PgDd: pg.DB,
}, nil
}
... ...
package command
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"github.com/astaxie/beego/validation"
)
type CreatePartnerInfoCommand struct {
domain.PartnerInfo
}
func (c *CreatePartnerInfoCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(c)
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/astaxie/beego/validation"
)
type RemovePartnerInfoCommand struct {
// 合伙人ID
Id int `json:"id" valid:"Required"`
}
func (c *RemovePartnerInfoCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(c)
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/astaxie/beego/validation"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
)
type UpdatePartnerInfoCommand struct {
// 合伙人Id
Id int `json:"id,omitempty"`
// 合伙人姓名
PartnerName string `json:"partnerName,omitempty"`
// 登录账号
Account string `json:"account,omitempty"`
// 登录密码
Password string `json:"password,omitempty"`
// 状态(1:启用或者0:禁用)
Status int `json:"status"`
// 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
PartnerCategory int `json:"partnerCategory,omitempty"`
//关联业务员
Salesman []*domain.Salesman `json:"salesman,omitempty"`
}
func (c *UpdatePartnerInfoCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(c)
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/astaxie/beego/validation"
)
type GetPartnerInfoQuery struct {
// 合伙人ID
Id int `json:"id" valid:"Required"`
}
func (q *GetPartnerInfoQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(q)
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/astaxie/beego/validation"
)
type ListPartnerInfoQuery struct {
//状态
Status int `json:"status,omitempty"`
// 合伙人类别
PartnerCategory int `json:"partnerCategory,omitempty"`
//按创建任务时间排序(ASC,DESC)
SortByCreateTime string `json:"sortByCreateTime,omitempty"`
//按创建任务时间排序(ASC,DESC)
SortByUpdateTime string `json:"sortByUpdateTime,omitempty"`
// 查询偏离量
Offset int `json:"offset,omitempty"`
// 查询限制
Limit int `json:"limit,omitempty"`
}
func (q *ListPartnerInfoQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(q)
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/partner/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/command"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/query"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"time"
)
// 客户价值服务
type PartnerInfoService struct {
}
// 创建客户价值
func (PartnerInfoService *PartnerInfoService) CreatePartnerInfo(command *command.CreatePartnerInfoCommand) (data interface{}, err error) {
var (
count int64
transactionContext, _ = factory.CreateTransactionContext(nil)
)
if err = command.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
if err != nil {
transactionContext.RollbackTransaction()
}
}()
newPartnerInfo := &command.PartnerInfo
newPartnerInfo.CreateAt = time.Now()
newPartnerInfo.UpdateAt = time.Now()
var PartnerInfoRepository domain.PartnerInfoRepository
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
if count, _, err = PartnerInfoRepository.Find(map[string]interface{}{"account": command.Account}); err != nil {
return nil, err
}
if count > 0 {
return nil, fmt.Errorf("标签不可重复名称")
}
if data, err = PartnerInfoRepository.Save(newPartnerInfo); err != nil {
return
}
err = transactionContext.CommitTransaction()
return
}
// 返回客户价值
func (PartnerInfoService *PartnerInfoService) GetPartnerInfo(command *query.GetPartnerInfoQuery) (data interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
)
if err = command.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
if err != nil {
transactionContext.RollbackTransaction()
}
}()
var PartnerInfoRepository domain.PartnerInfoRepository
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
data, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": command.Id})
if err != nil {
return nil, err
}
if data == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(command.Id)))
}
err = transactionContext.CommitTransaction()
return
}
// 更新客户价值
func (PartnerInfoService *PartnerInfoService) UpdatePartnerInfo(updatePartnerInfoCommand *command.UpdatePartnerInfoCommand) (data interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfo *domain.PartnerInfo
)
if err = updatePartnerInfoCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
if err != nil {
transactionContext.RollbackTransaction()
}
}()
var PartnerInfoRepository domain.PartnerInfoRepository
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
PartnerInfo, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": updatePartnerInfoCommand.Id})
if err != nil {
return nil, err
}
if PartnerInfo == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updatePartnerInfoCommand.Id)))
}
//if count, PartnerInfos, err := PartnerInfoRepository.Find(map[string]interface{}{
// "PartnerInfoName": updatePartnerInfoCommand.PartnerInfoName,
// "companyId": PartnerInfo.CompanyId,
//}); err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
//} else {
// if count > 0 && PartnerInfos[0].PartnerInfoId != PartnerInfo.PartnerInfoId {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "标签不可重复名称")
// }
//}
if err := PartnerInfo.Update(tool_funs.SimpleStructToMap(updatePartnerInfoCommand)); err != nil {
return nil, err
}
if data, err = PartnerInfoRepository.Save(PartnerInfo); err != nil {
return nil, err
}
err = transactionContext.CommitTransaction()
return
}
// 移除客户价值
func (PartnerInfoService *PartnerInfoService) RemovePartnerInfo(removePartnerInfoCommand *command.RemovePartnerInfoCommand) (data interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfo *domain.PartnerInfo
)
if err = removePartnerInfoCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
if err != nil {
transactionContext.RollbackTransaction()
}
}()
var PartnerInfoRepository domain.PartnerInfoRepository
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
PartnerInfo, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": removePartnerInfoCommand.Id})
if err != nil {
return nil, err
}
if PartnerInfo == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removePartnerInfoCommand.Id)))
}
if data, err = PartnerInfoRepository.Remove(PartnerInfo); err != nil {
return nil, err
}
err = transactionContext.CommitTransaction()
return
}
// 返回客户价值列表
func (PartnerInfoService *PartnerInfoService) ListPartnerInfo(listPartnerInfoQuery *query.ListPartnerInfoQuery) (data interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfos []*domain.PartnerInfo
count int64
)
if err = listPartnerInfoQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
if err != nil {
transactionContext.RollbackTransaction()
}
}()
var PartnerInfoRepository domain.PartnerInfoRepository
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
if count, PartnerInfos, err = PartnerInfoRepository.Find(tool_funs.SimpleStructToMap(listPartnerInfoQuery)); err != nil {
return nil, err
}
if err = transactionContext.CommitTransaction(); err != nil {
return nil, err
}
return map[string]interface{}{
"count": count,
"partnerInfos": PartnerInfos,
}, nil
}
func NewPartnerInfoService(options map[string]interface{}) *PartnerInfoService {
newPartnerInfoService := &PartnerInfoService{}
return newPartnerInfoService
}
... ...
package constant
import "os"
const SERVICE_NAME = "partner"
var LOG_LEVEL = "debug"
var LOG_File = "app.log"
var ABILITY_SERVICE_HOST = "https://suplus-worth-app-gateway-dev.fjmaimaimai.com"
var MMM_OPEN_API_SERVICE_HOST = "http://mmm-open-api-dev.fjmaimaimai.com"
func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
}
if os.Getenv("ABILITY_SERVICE_HOST") != "" {
ABILITY_SERVICE_HOST = os.Getenv("ABILITY_SERVICE_HOST")
}
if os.Getenv("MMM_OPEN_API_SERVICE_HOST") != "" {
MMM_OPEN_API_SERVICE_HOST = os.Getenv("MMM_OPEN_API_SERVICE_HOST")
}
}
... ...
package constant
import "os"
var POSTGRESQL_DB_NAME = "partner"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "pgsql@123"
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "5432"
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 event
//import (
// coreDomain "github.com/linmadan/egglib-go/core/domain"
// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
//)
//
//const TASK_ROBED_EVENT = "task-robed-event"
//
//type TaskRobed struct {
// coreDomain.BaseEvent
// // 任务ID
// TaskId int64 `json:"taskId"`
// // 公司ID
// CompanyId int64 `json:"companyId"`
// // 任务名称
// TaskName string `json:"taskName"`
// // 任务类型Type
// TaskType int `json:"taskType"`
// // 任务发起者
// Sponsor *domain.EmployeeInfo `json:"sponsor"`
// // 任务状态
// TaskStatus int `json:"taskStatus"`
// // 引用资源
// ReferenceResource *domain.ReferenceResource `json:"referenceResource"`
// // 抢单任务信息
// RobInfo *domain.RobInfo `json:"robInfo"`
//}
//
//func (event *TaskRobed) EventType() string {
// return TASK_ROBED_EVENT
//}
... ...
package domain
import "time"
type PartnerInfoRepository interface {
Save(dm *PartnerInfo) (*PartnerInfo, error)
Remove(dm *PartnerInfo) (*PartnerInfo, error)
FindOne(queryOptions map[string]interface{}) (*PartnerInfo, error)
Find(queryOptions map[string]interface{}) (int64, []*PartnerInfo, error)
}
type PartnerInfo struct {
// 合伙人ID
Id int64 `json:"id"`
// 合伙人姓名
PartnerName string `json:"partnerName"`
// 登录账号
Account string `json:"account"`
// 登录密码
Password string `json:"password"`
// 状态(1:启用或者0:禁用)
Status int `json:"status"`
// 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
PartnerCategory int `json:"partnerCategory"`
//创建时间
CreateAt time.Time `json:"createAt"`
//更新时间
UpdateAt time.Time `json:"updateAt"`
//关联业务员
Salesman []*Salesman `json:"salesman"`
}
func (m *PartnerInfo) Identify() interface{} {
if m.Id == 0 {
return nil
}
return m.Id
}
func (m *PartnerInfo) Update(data map[string]interface{}) error {
if partnerName, ok := data["partnerName"]; ok && partnerName != "" {
m.PartnerName = partnerName.(string)
}
if account, ok := data["account"]; ok && account != "" {
m.Account = account.(string)
}
if password, ok := data["account"]; ok && password != "" {
m.Password = password.(string)
}
if status, ok := data["status"]; ok && status != 0 {
m.Status = status.(int)
}
if partnerCategory, ok := data["partnerCategory"]; ok && partnerCategory != 0 {
m.PartnerCategory = partnerCategory.(int)
}
if salesman, ok := data["salesman"]; ok {
m.Salesman = salesman.([]*Salesman)
}
m.UpdateAt = time.Now()
return nil
}
... ...
package domain
type Salesman struct {
//Id int64 `json:"id"`
Name string `json:"name"`
Telephone string `json:"telephone"`
}
... ...
package service
//import (
// coreDomain "github.com/linmadan/egglib-go/core/domain"
// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
//)
//
//type RobTaskService interface {
// coreDomain.DomainEventPublisher
// Rob(taskId int64, receiverUid int64) (*domain.Task, error)
//}
... ...
package dao
//import (
// "fmt"
// "github.com/go-pg/pg/v10"
// pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg/models"
// "time"
//)
//
//type EmployeeDao struct {
// transactionContext *pgTransaction.TransactionContext
//}
//
//func (dao *EmployeeDao) BatchRemove(uids []int64) error {
// tx := dao.transactionContext.PgTx
// _, err := tx.QueryOne(
// pg.Scan(),
// "DELETE FROM employees WHERE uid IN (?)",
// pg.In(uids))
// return err
//}
//
//func (dao *EmployeeDao) BatchSetStatus(uids []int64, status int) error {
// tx := dao.transactionContext.PgTx
// _, err := tx.QueryOne(
// pg.Scan(),
// "UPDATE employees SET status=? WHERE uid IN (?)",
// status, pg.In(uids))
// return err
//}
//
//func (dao *EmployeeDao) ChangePrincipal(companyId int64, employeeAccount string) error {
// tx := dao.transactionContext.PgTx
// if _, err := tx.Query(
// pg.Scan(),
// "UPDATE employees SET is_principal=? WHERE company_id=?",
// false, companyId); err != nil {
// return err
// }
// if _, err := tx.QueryOne(
// pg.Scan(),
// "UPDATE employees SET is_principal=? WHERE company_id=? AND employee_account=?",
// true, companyId, employeeAccount); err != nil {
// return err
// }
// return nil
//}
//
//func (dao *EmployeeDao) TransferSuMoney(uid int64, suMoney float64) error {
// tx := dao.transactionContext.PgTx
// _, err := tx.QueryOne(
// pg.Scan(),
// "UPDATE employees SET su_money=su_money+? WHERE uid=?",
// suMoney, uid)
// return err
//}
//
//func (dao *EmployeeDao) CalculatePersonUnReadNotification(uid int64) (map[string]int, error) {
// var unReadSystemNotification int
// var unReadInteractionNotification int
// tx := dao.transactionContext.PgTx
// sentNotificationModel := new(models.SentNotification)
// if count, err := tx.Model(sentNotificationModel).Relation("Notification").
// Where(`sent_notification.receiver @> '{"uid":?}'`, uid).
// Where("notification.notification_type = ?", domain.NOTIFICATION_TYPE_SYSTEM).
// Where("sent_notification.is_read = ?", false).
// Count(); err != nil {
// return nil, err
// } else {
// unReadSystemNotification = count
// }
// if count, err := tx.Model(sentNotificationModel).Relation("Notification").
// Where(`sent_notification.receiver @> '{"uid":?}'`, uid).
// Where("notification.notification_type = ?", domain.NOTIFICATION_TYPE_INTERACTION).
// Where("sent_notification.is_read = ?", false).
// Count(); err != nil {
// return nil, err
// } else {
// unReadInteractionNotification = count
// }
// return map[string]int{
// "unReadSystemNotification": unReadSystemNotification,
// "unReadInteractionNotification": unReadInteractionNotification,
// }, nil
//}
//
//func (dao *EmployeeDao) CalculatePersonSuMoney(uid int64) (map[string]interface{}, error) {
// var incomeSuMoney float64
// var incomeSuMoneyOfYesterday float64
// tx := dao.transactionContext.PgTx
// suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
// yesterday := time.Now().AddDate(0, 0, -1)
// if err := tx.Model(suMoneyTransactionRecordModel).
// ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
// Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
// Where(`su_money_transaction_record.record_type = ?`, 2).
// Where(`su_money_transaction_record.create_time > ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, yesterday.Location())).
// Where(`su_money_transaction_record.create_time < ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 0, yesterday.Location())).
// Select(&incomeSuMoneyOfYesterday); err != nil {
// return nil, err
// }
// if err := tx.Model(suMoneyTransactionRecordModel).
// ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
// Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
// Where(`su_money_transaction_record.record_type = ?`, 2).
// Select(&incomeSuMoney); err != nil {
// return nil, err
// }
// return map[string]interface{}{
// "incomeSuMoney": incomeSuMoney,
// "incomeSuMoneyOfYesterday": incomeSuMoneyOfYesterday,
// }, nil
//}
//
//func (dao *EmployeeDao) CalculateSuMoneyTransactionRecord(uid int64, transactionStartTime time.Time, transactionEndTime time.Time) (map[string]interface{}, error) {
// var incomeSuMoney float64
// var expendSuMoney float64
// tx := dao.transactionContext.PgTx
// suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
// if err := tx.Model(suMoneyTransactionRecordModel).
// ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
// Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
// Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{2, 3})).
// Where(`su_money_transaction_record.create_time > ?`, transactionStartTime).
// Where(`su_money_transaction_record.create_time < ?`, transactionEndTime).
// Select(&incomeSuMoney); err != nil {
// return nil, err
// }
// if err := tx.Model(suMoneyTransactionRecordModel).
// ColumnExpr("sum(su_money_transaction_record.su_money) AS expend_su_money").
// Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
// Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{1, 4})).
// Where(`su_money_transaction_record.create_time > ?`, transactionStartTime).
// Where(`su_money_transaction_record.create_time < ?`, transactionEndTime).
// Select(&expendSuMoney); err != nil {
// return nil, err
// }
// return map[string]interface{}{
// "incomeSuMoney": incomeSuMoney,
// "expendSuMoney": expendSuMoney,
// }, nil
//}
//
//func NewEmployeeDao(transactionContext *pgTransaction.TransactionContext) (*EmployeeDao, error) {
// if transactionContext == nil {
// return nil, fmt.Errorf("transactionContext参数不能为nil")
// } else {
// return &EmployeeDao{
// transactionContext: transactionContext,
// }, nil
// }
//}
... ...
package domain_service
//import (
// "fmt"
// coreDomain "github.com/linmadan/egglib-go/core/domain"
// pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain/event"
// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/dao"
// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/repository"
// "time"
//)
//
//type RobTaskService struct {
// coreDomain.BaseEventPublisher
// transactionContext *pgTransaction.TransactionContext
//}
//
//func (service *RobTaskService) Rob(taskId int64, receiverUid int64) (*domain.Task, error) {
// var employeeRepository domain.EmployeeRepository
// var taskRepository domain.TaskRepository
// var taskDao *dao.TaskDao
// if repository, err := repository.NewEmployeeRepository(service.transactionContext); err != nil {
// return nil, err
// } else {
// employeeRepository = repository
// }
// if repository, err := repository.NewTaskRepository(service.transactionContext); err != nil {
// return nil, err
// } else {
// taskRepository = repository
// }
// if dao, err := dao.NewTaskDao(service.transactionContext); err != nil {
// return nil, err
// } else {
// taskDao = dao
// }
// receiver, err := employeeRepository.FindOne(map[string]interface{}{
// "uid": receiverUid,
// })
// if err != nil {
// return nil, err
// }
// if receiver == nil {
// return nil, fmt.Errorf("无效的领取人")
// }
// task, err := taskRepository.FindOne(map[string]interface{}{
// "taskId": taskId,
// })
// if err != nil {
// return nil, err
// }
// if task == nil {
// return nil, fmt.Errorf("无效的任务")
// }
// if receiver.EmployeeInfo.Uid == task.Sponsor.Uid {
// return nil, fmt.Errorf("无法领取自己发布的任务")
// }
// if task.RobInfo != nil && task.RobInfo.Receiver != nil {
// return nil, fmt.Errorf("任务已经被人领取")
// }
// if err := task.Rob(receiver.EmployeeInfo); err != nil {
// return nil, err
// }
// if err := taskDao.AddRobInfo(taskId, receiver.EmployeeInfo); err != nil {
// return nil, fmt.Errorf("抢单失败,任务可能已经被人领取")
// }
// if task, err := taskRepository.Save(task); err != nil {
// return nil, err
// } else {
// taskRobedEvent := new(event.TaskRobed)
// taskRobedEvent.OccurredOn = time.Now()
// taskRobedEvent.TaskId = task.TaskId
// taskRobedEvent.CompanyId = task.CompanyId
// taskRobedEvent.TaskName = task.TaskName
// taskRobedEvent.TaskType = task.TaskType
// taskRobedEvent.Sponsor = task.Sponsor
// taskRobedEvent.TaskStatus = task.TaskStatus
// taskRobedEvent.ReferenceResource = task.ReferenceResource
// taskRobedEvent.RobInfo = task.RobInfo
// if err := service.Publish(taskRobedEvent); err != nil {
// return nil, err
// }
// return task, nil
// }
//}
//
//func NewRobTaskService(transactionContext *pgTransaction.TransactionContext) (*RobTaskService, error) {
// if transactionContext == nil {
// return nil, fmt.Errorf("transactionContext参数不能为nil")
// } else {
// return &RobTaskService{
// transactionContext: transactionContext,
// }, nil
// }
//}
... ...
package pg
import (
"context"
"fmt"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
)
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(SqlGeneratePrintHook{})
}
if !constant.DISABLE_CREATE_TABLE {
for _, model := range []interface{}{
//(*models.Employee)(nil),
(*models.PartnerInfo)(nil),
} {
err := DB.CreateTable(model, &orm.CreateTableOptions{
Temp: false,
IfNotExists: true,
FKConstraints: true,
})
if err != nil {
panic(err)
}
}
}
}
type SqlGeneratePrintHook struct{}
func (hook SqlGeneratePrintHook) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) {
return c, nil
}
func (hook SqlGeneratePrintHook) AfterQuery(c context.Context, q *pg.QueryEvent) error {
data, err := q.FormattedQuery()
fmt.Println(string(data))
return err
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"time"
)
type PartnerInfo struct {
tableName struct{} `pg:"partner_infos,alias:partner_info"`
// 合伙人ID
Id int64 `pg:",pk"`
// 合伙人姓名
PartnerName string
// 登录账号
Account string
// 登录密码
Password string
// 状态(1:启用或者0:禁用)
Status int `pg:",notnull,default:1"`
// 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
PartnerCategory int `pg:",notnull,default:1"`
//创建时间
CreateAt time.Time
//更新时间
UpdateAt time.Time
//关联业务员
Salesman []*domain.Salesman
}
... ...
package transaction
import "github.com/go-pg/pg/v10"
type TransactionContext struct {
PgDd *pg.DB
PgTx *pg.Tx
}
func (transactionContext *TransactionContext) StartTransaction() error {
tx, err := transactionContext.PgDd.Begin()
if err != nil {
return err
}
transactionContext.PgTx = tx
return nil
}
func (transactionContext *TransactionContext) CommitTransaction() error {
err := transactionContext.PgTx.Commit()
return err
}
func (transactionContext *TransactionContext) RollbackTransaction() error {
err := transactionContext.PgTx.Rollback()
return err
}
func NewPGTransactionContext(pgDd *pg.DB) *TransactionContext {
return &TransactionContext{
PgDd: pgDd,
}
}
... ...
package repository
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
)
type PartnerInfoRepository struct {
transactionContext *transaction.TransactionContext
}
func (repository *PartnerInfoRepository) Save(dm *domain.PartnerInfo) (*domain.PartnerInfo, error) {
var (
err error
m = &models.PartnerInfo{}
tx = repository.transactionContext.PgTx
)
if err = GobModelTransform(m, dm); err != nil {
return nil, err
}
if dm.Identify() == nil {
if dm.Id, err = NewSnowflakeId(); err != nil {
return dm, err
}
m.Id = dm.Id
if err = tx.Insert(m); err != nil {
return nil, err
}
return dm, nil
}
if err = tx.Update(m); err != nil {
return nil, err
}
return dm, nil
}
func (repository *PartnerInfoRepository) Remove(PartnerInfo *domain.PartnerInfo) (*domain.PartnerInfo, error) {
var (
tx = repository.transactionContext.PgTx
PartnerInfoModel = &models.PartnerInfo{Id: PartnerInfo.Identify().(int64)}
)
if _, err := tx.Model(PartnerInfoModel).Where("id = ?", PartnerInfo.Id).Delete(); err != nil {
return PartnerInfo, err
}
return PartnerInfo, nil
}
func (repository *PartnerInfoRepository) FindOne(queryOptions map[string]interface{}) (*domain.PartnerInfo, error) {
tx := repository.transactionContext.PgTx
PartnerInfoModel := new(models.PartnerInfo)
query := NewQuery(tx.Model(PartnerInfoModel), queryOptions)
query.SetWhere("partner_info.id = ?", "id")
if err := query.First(); err != nil {
return nil, query.HandleError(err, "没有此合伙人")
}
if PartnerInfoModel.Id == 0 {
return nil, nil
}
return repository.transformPgModelToDomainModel(PartnerInfoModel)
}
func (repository *PartnerInfoRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.PartnerInfo, error) {
tx := repository.transactionContext.PgTx
var PartnerInfoModels []*models.PartnerInfo
PartnerInfos := make([]*domain.PartnerInfo, 0)
query := NewQuery(tx.Model(&PartnerInfoModels), queryOptions)
query.
SetWhere("partner_info.account = ?", "account").
SetWhere(`partner_info.status = ?`, "status").
SetWhere(`partner_info.partner_category = ?`, "partnerCategory").
SetLimit().
SetOrder("partner_info.create_at", "sortByCreateTime").
SetOrder("partner_info.update_at", "sortByUpdateTime")
var err error
if query.AffectRow, err = query.SelectAndCount(); err != nil {
return 0, PartnerInfos, err
}
for _, PartnerInfoModel := range PartnerInfoModels {
if PartnerInfo, err := repository.transformPgModelToDomainModel(PartnerInfoModel); err != nil {
return 0, PartnerInfos, err
} else {
PartnerInfos = append(PartnerInfos, PartnerInfo)
}
}
return int64(query.AffectRow), PartnerInfos, nil
}
func (repository *PartnerInfoRepository) transformPgModelToDomainModel(PartnerInfoModel *models.PartnerInfo) (*domain.PartnerInfo, error) {
m := &domain.PartnerInfo{}
err := GobModelTransform(m, PartnerInfoModel)
return m, err
}
func NewPartnerInfoRepository(transactionContext *transaction.TransactionContext) (*PartnerInfoRepository, error) {
if transactionContext == nil {
return nil, ERR_EMPTY_TC
}
return &PartnerInfoRepository{transactionContext: transactionContext}, nil
}
... ...
package repository
import (
"bytes"
"encoding/gob"
"fmt"
"github.com/go-pg/pg/v10/orm"
"github.com/linmadan/egglib-go/utils/snowflake"
)
var (
ERR_EMPTY_TC = fmt.Errorf("transactionContext参数不能为nil")
)
type Query struct {
*orm.Query
queryOptions map[string]interface{}
AffectRow int
}
func NewQuery(query *orm.Query, queryOptions map[string]interface{}) *Query {
return &Query{
query,
queryOptions,
0,
}
}
func (query *Query) SetWhere(condition, key string) *Query {
if v, ok := query.queryOptions[key]; ok {
query.Where(condition, v)
}
return query
}
func (query *Query) SetLimit() *Query {
if offset, ok := query.queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
query.Offset(offset)
}
} else {
query.Offset(0)
}
if limit, ok := query.queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
query.Limit(limit)
} else {
query.Limit(20)
}
}
return query
}
func (query *Query) SetOrder(orderColumn string, key string) *Query {
//query.Order(condition...)
//return query
if v, ok := query.queryOptions[key]; ok {
query.Order(fmt.Sprintf("%v %v", orderColumn, v))
}
return query
}
func (query *Query) HandleError(err error, errMsg string) error {
if err.Error() == "pg: no rows in result set" {
return fmt.Errorf(errMsg)
} else {
return err
}
}
func NewSnowflakeId() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(2)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
//GobModelTransform 模型转换
func GobModelTransform(dst interface{}, src interface{}) error {
var data bytes.Buffer
enc := gob.NewEncoder(&data)
if err := enc.Encode(src); err != nil {
return err
}
dec := gob.NewDecoder(&data)
if err := dec.Decode(dst); err != nil {
return err
}
return nil
}
... ...
package service_gateway
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"strings"
"time"
)
type HttplibAbilityServiceGateway struct {
httplibBaseServiceGateway
}
func (serviceGateway *HttplibAbilityServiceGateway) CommitQuestionQuotes(uid int64, taskId int64, serials []int64) (map[string]interface{}, error) {
url := strings.Join([]string{serviceGateway.baseURL, "task/commitQuestionQuotes"}, "/")
request := serviceGateway.createRequest(url, "post")
options := make(map[string]interface{})
options["uid"] = uid
options["taskId"] = taskId
options["serials"] = serials
request.JSONBody(options)
response := make(map[string]interface{})
request.ToJSON(&response)
data, err := serviceGateway.responseHandle(response)
return data, err
}
func (serviceGateway *HttplibAbilityServiceGateway) CommitQuestionSolution(qid int64, uid int64, solveUid int64, content string, scoreSolve float64, imgs []string, partners []map[string]interface{}) (map[string]interface{}, error) {
url := strings.Join([]string{serviceGateway.baseURL, "task/commitQuestionSolution"}, "/")
request := serviceGateway.createRequest(url, "post")
options := make(map[string]interface{})
options["qid"] = qid
options["uid"] = uid
options["solveUid"] = solveUid
options["content"] = content
options["scoreSolve"] = scoreSolve
options["imgs"] = imgs
options["partners"] = partners
request.JSONBody(options)
response := make(map[string]interface{})
request.ToJSON(&response)
data, err := serviceGateway.responseHandle(response)
return data, err
}
func (serviceGateway *HttplibAbilityServiceGateway) CloseTaskCallback(taskId int64, referenceResourceIds []int64) (map[string]interface{}, error) {
url := strings.Join([]string{serviceGateway.baseURL, "task/closeTaskCallback"}, "/")
request := serviceGateway.createRequest(url, "post")
options := make(map[string]interface{})
options["taskId"] = taskId
options["referenceResourceIds"] = referenceResourceIds
request.JSONBody(options)
response := make(map[string]interface{})
request.ToJSON(&response)
data, err := serviceGateway.responseHandle(response)
return data, err
}
func (serviceGateway *HttplibAbilityServiceGateway) ReceiverTaskCallback(uid int64, taskId int64, referenceResourceIds []int64, operatorId int64, operatorTime time.Time) (map[string]interface{}, error) {
url := strings.Join([]string{serviceGateway.baseURL, "task/receiverTaskCallback"}, "/")
request := serviceGateway.createRequest(url, "post")
options := make(map[string]interface{})
options["uid"] = uid
options["taskId"] = taskId
options["referenceResourceIds"] = referenceResourceIds
options["operator_id"] = operatorId
options["operator_time"] = operatorTime
request.JSONBody(options)
response := make(map[string]interface{})
request.ToJSON(&response)
data, err := serviceGateway.responseHandle(response)
return data, err
}
func (serviceGateway *HttplibAbilityServiceGateway) SaveTaskCallback(uid int64, taskId int64, serials []int64) (map[string]interface{}, error) {
url := strings.Join([]string{serviceGateway.baseURL, "task/saveTaskCallback"}, "/")
request := serviceGateway.createRequest(url, "post")
options := make(map[string]interface{})
options["uid"] = uid
options["taskId"] = taskId
options["serials"] = serials
request.JSONBody(options)
response := make(map[string]interface{})
request.ToJSON(&response)
data, err := serviceGateway.responseHandle(response)
return data, err
}
func (serviceGateway *HttplibAbilityServiceGateway) DeleteTaskCallback(uid int64, taskId int64, serials []int64) (map[string]interface{}, error) {
url := strings.Join([]string{serviceGateway.baseURL, "task/deleteTaskCallback"}, "/")
request := serviceGateway.createRequest(url, "post")
options := make(map[string]interface{})
options["uid"] = uid
options["taskId"] = taskId
options["serials"] = serials
request.JSONBody(options)
response := make(map[string]interface{})
request.ToJSON(&response)
data, err := serviceGateway.responseHandle(response)
return data, err
}
func NewHttplibAbilityServiceGateway() *HttplibAbilityServiceGateway {
return &HttplibAbilityServiceGateway{
httplibBaseServiceGateway: httplibBaseServiceGateway{
baseURL: constant.ABILITY_SERVICE_HOST,
connectTimeout: 100 * time.Second,
readWriteTimeout: 30 * time.Second,
},
}
}
... ...
package service_gateway
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"strings"
"time"
)
type HttplibMmmOpenApiServiceGateway struct {
httplibBaseServiceGateway
}
func (serviceGateway *HttplibMmmOpenApiServiceGateway) PushInfo(msgType int, uids []int64, title string, content string, ext map[string]interface{}) (map[string]interface{}, error) {
url := strings.Join([]string{serviceGateway.baseURL, "v1", "push", "pushInfo"}, "/")
request := serviceGateway.createRequest(url, "post")
options := make(map[string]interface{})
options["mmmType"] = msgType
options["project"] = "worth"
options["receivers"] = uids
options["title"] = title
options["content"] = content
options["ext"] = ext
request.JSONBody(options)
response := make(map[string]interface{})
request.ToJSON(&response)
data, err := serviceGateway.responseHandle(response)
return data, err
}
func NewHttplibMmmOpenApiServiceGateway() *HttplibMmmOpenApiServiceGateway {
return &HttplibMmmOpenApiServiceGateway{
httplibBaseServiceGateway: httplibBaseServiceGateway{
baseURL: constant.MMM_OPEN_API_SERVICE_HOST,
connectTimeout: 100 * time.Second,
readWriteTimeout: 30 * time.Second,
},
}
}
... ...
package service_gateway
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego/httplib"
"strconv"
"strings"
"time"
)
type httplibBaseServiceGateway struct {
baseURL string
connectTimeout time.Duration
readWriteTimeout time.Duration
}
func (serviceGateway *httplibBaseServiceGateway) createRequest(url string, method string) *httplib.BeegoHTTPRequest {
var request *httplib.BeegoHTTPRequest
switch method {
case "get":
request = httplib.Get(url)
break
case "post":
request = httplib.Post(url)
break
case "put":
request = httplib.Put(url)
break
case "delete":
request = httplib.Delete(url)
break
case "head":
request = httplib.Head(url)
break
default:
request = httplib.Get(url)
}
return request.SetTimeout(serviceGateway.connectTimeout, serviceGateway.readWriteTimeout)
}
func (serviceGateway *httplibBaseServiceGateway) responseHandle(response map[string]interface{}) (map[string]interface{}, error) {
data := make(map[string]interface{})
var err error
if code, ok := response["code"]; ok {
code := code.(float64)
if code == 0 {
data = response["data"].(map[string]interface{})
} else {
msg := response["msg"].(string)
err = fmt.Errorf(strings.Join([]string{strconv.FormatFloat(code, 'f', -1, 64), msg}, " "))
}
} else {
jsonBytes, marshalErr := json.Marshal(response)
if marshalErr != nil {
err = marshalErr
}
err = fmt.Errorf("无法解析的网关服务数据返回格式:%s", string(jsonBytes))
}
return data, err
}
... ...
package service_gateway
import "time"
type AbilityServiceGateway interface {
CommitQuestionQuotes(uid int64, taskId int64, serials []int64) (map[string]interface{}, error)
CommitQuestionSolution(qid int64, uid int64, solveUid int64, content string, scoreSolve float64, imgs []string, partners []map[string]interface{}) (map[string]interface{}, error)
CloseTaskCallback(taskId int64, referenceResourceIds []int64) (map[string]interface{}, error)
ReceiverTaskCallback(uid int64, taskId int64, referenceResourceIds []int64, operatorId int64, operatorTime time.Time) (map[string]interface{}, error)
SaveTaskCallback(uid int64, taskId int64, serials []int64) (map[string]interface{}, error)
DeleteTaskCallback(uid int64, taskId int64, serials []int64) (map[string]interface{}, error)
}
type MmmOpenApiServiceGateway interface {
PushInfo(msgType int, uids []int64, title string, content string, ext map[string]interface{}) (map[string]interface{}, error)
}
... ...
package constant
import (
"github.com/astaxie/beego/logs"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"path/filepath"
"strconv"
)
var Logger *logs.BeeLogger
func init() {
Logger = NewBeegoLogger(LoggerConfig{
Filename: constant.LOG_File,
Level: constant.LOG_LEVEL,
})
}
type LoggerConfig struct {
Level string `json:"level,omitempty"`
Filename string `json:"filename,omitempty"`
MaxSize int `json:"max_size,omitempty"`
MaxBackups int `json:"max_backups,omitempty"`
MaxAge int `json:"max_age,omitempty"`
Compress bool `json:"compress,omitempty"`
}
func NewBeegoLogger(conf LoggerConfig) *logs.BeeLogger {
filename := `{"filename":"` + filepath.ToSlash(conf.Filename) + `"}`
log := logs.GetBeeLogger()
log.SetLogger(logs.AdapterFile, filename)
ilv, err := strconv.Atoi(conf.Level)
if err != nil {
ilv = logs.LevelDebug
}
log.SetLevel(ilv)
log.EnableFuncCallDepth(true)
log.SetLogFuncCallDepth(3)
return log
}
... ...
package constant
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
"time"
)
func CreateRequstLogFilter(logger *logs.BeeLogger) func(ctx *context.Context) {
return func(ctx *context.Context) {
requestId := fmt.Sprintf("%v.%v.%v", ctx.Input.Method(), ctx.Input.URI(), time.Now().UnixNano())
ctx.Request.Header.Add("requestId", requestId)
var body string = "{}"
if ctx.Input.GetData("requestBody") != nil {
body = string(ctx.Input.GetData("requestBody").([]byte))
}
logger.Debug(fmt.Sprintf("====>Recv RequestId:%s BodyData:%s", requestId, body))
}
}
func CreateResponseLogFilter(logger *logs.BeeLogger) func(ctx *context.Context) {
return func(ctx *context.Context) {
requestId := ctx.Request.Header.Get("requestId")
body, _ := json.Marshal(ctx.Input.GetData("outputData"))
if len(body) > 1000 {
body = body[:1000]
}
logger.Debug(fmt.Sprintf("<====Send RequestId:%v BodyData:%s", requestId, body))
}
}
... ...
package beego
import (
"github.com/astaxie/beego"
"github.com/linmadan/egglib-go/web/beego/filters"
. "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego/routers"
)
func init() {
beego.InsertFilter("/*", beego.BeforeExec, filters.CreateRequestBodyFilter())
beego.InsertFilter("/*", beego.BeforeExec, CreateRequstLogFilter(Logger))
beego.InsertFilter("/*", beego.AfterExec, CreateResponseLogFilter(Logger), false)
}
... ...
package controllers
import (
"encoding/json"
"github.com/astaxie/beego"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/web/beego/utils"
)
type BaseController struct {
beego.Controller
}
func (controller BaseController) JsonUnmarshal(v interface{}) error {
body := controller.Ctx.Input.GetData("requestBody").([]byte)
//fmt.Println("【RequestBody】 ",controller.Ctx.Input.Method(),controller.Ctx.Input.URL(),string(body))
return json.Unmarshal(body, v)
}
func (controller BaseController) HandlerResponse(data interface{}, err error) {
var response utils.JsonResponse
defer func() {
controller.Data["json"] = response
controller.ServeJSON()
}()
if err == nil {
response = utils.ResponseData(controller.Ctx, data)
return
}
if _, ok := err.(*application.ServiceError); !ok {
err = application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
response = utils.ResponseError(controller.Ctx, err)
}
func (controller BaseController) GetLimitInfo() (offset int, limit int) {
offset, _ = controller.GetInt("offset")
limit, _ = controller.GetInt("limit")
return
}
... ...
package controllers
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/command"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/query"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/service"
)
type PartnerInfoController struct {
BaseController
}
//CreatePartnerInfo 创建合伙人
func (controller *PartnerInfoController) CreatePartnerInfo() {
var (
service = service.NewPartnerInfoService(nil)
command = &command.CreatePartnerInfoCommand{}
)
controller.JsonUnmarshal(command)
controller.HandlerResponse(service.CreatePartnerInfo(command))
}
//UpdatePartnerInfo 更新合伙人
func (controller *PartnerInfoController) UpdatePartnerInfo() {
var (
service = service.NewPartnerInfoService(nil)
command = &command.UpdatePartnerInfoCommand{}
)
controller.JsonUnmarshal(command)
id, _ := controller.GetInt(":id")
command.Id = id
controller.HandlerResponse(service.UpdatePartnerInfo(command))
}
//GetPartnerInfo 获取合伙人
func (controller *PartnerInfoController) GetPartnerInfo() {
var (
service = service.NewPartnerInfoService(nil)
command = &query.GetPartnerInfoQuery{}
)
uid, _ := controller.GetInt(":id")
command.Id = uid
controller.HandlerResponse(service.GetPartnerInfo(command))
}
//GetPartnerInfo 移除合伙人
func (controller *PartnerInfoController) RemovePartnerInfo() {
var (
service = service.NewPartnerInfoService(nil)
command = &command.RemovePartnerInfoCommand{}
)
uid, _ := controller.GetInt(":id")
command.Id = uid
controller.HandlerResponse(service.RemovePartnerInfo(command))
}
//ListPartnerInfo 合伙人列表
func (controller *PartnerInfoController) ListPartnerInfo() {
var (
service = service.NewPartnerInfoService(nil)
command = &query.ListPartnerInfoQuery{}
)
command.PartnerCategory, _ = controller.GetInt("partnerCategory")
command.Status, _ = controller.GetInt("status")
command.SortByCreateTime = controller.GetString("sortByCreateTime")
command.SortByUpdateTime = controller.GetString("sortByUpdateTime")
command.Offset, command.Limit = controller.GetLimitInfo()
controller.HandlerResponse(service.ListPartnerInfo(command))
}
... ...
package routers
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego/controllers"
)
func init() {
beego.Router("/partnerInfos/", &controllers.PartnerInfoController{}, "Post:CreatePartnerInfo")
beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Put:UpdatePartnerInfo")
beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Get:GetPartnerInfo")
beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Delete:RemovePartnerInfo")
beego.Router("/partnerInfos/", &controllers.PartnerInfoController{}, "Get:ListPartnerInfo")
}
... ...
package routers
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
)
func init() {
beego.SetStaticPath("/log", constant.LOG_File)
}
... ...
package partnerInfo
import (
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
"net/http"
)
var _ = Describe("创建新合伙人", func() {
Describe("创建新合伙人", func() {
Context("创建新合伙人", func() {
It("返回合伙人数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"partnerName": "employeeName",
"account": "account123",
"password": "password",
"status": 1,
"partnerCategory": 1,
//"createAt":time.Now(),
//"updateAt":time.Now(),
"salesman": []map[string]interface{}{
{"name": "name", "telephone": "18860183051"},
{"name2": "name", "telephone": "18860183052j"},
},
}
httpExpect.POST("/partnerInfos").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("id").ValueNotEqual("id", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package partnerInfo
import (
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
"net/http"
)
var _ = Describe("删除合伙人", func() {
BeforeEach(func() {
_, err := pG.DB.Exec(`INSERT INTO "public"."partner_infos"("id", "partner_name", "account", "password", "status", "partner_category", "create_at", "update_at", "salesman") VALUES (2929531956394199040, 'employeeName', 'account', 'password', 1, 1, '2020-06-19 15:23:31.616934+08', '2020-06-19 15:23:31.616934+08', '[{"name": "name", "telephone": "18860183051"}, {"name": "", "telephone": "18860183052j"}]');`)
Expect(err).NotTo(HaveOccurred())
})
Describe("删除合伙人", func() {
Context("删除合伙人", func() {
It("删除合伙人数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.DELETE("/partnerInfos/2929531956394199040").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("id").ValueNotEqual("id", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package partnerInfo
import (
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
"net/http"
)
var _ = Describe("获取合伙人", func() {
BeforeEach(func() {
_, err := pG.DB.Exec(`INSERT INTO "public"."partner_infos"("id", "partner_name", "account", "password", "status", "partner_category", "create_at", "update_at", "salesman") VALUES (2929531956394199040, 'employeeName', 'account', 'password', 1, 1, '2020-06-19 15:23:31.616934+08', '2020-06-19 15:23:31.616934+08', '[{"name": "name", "telephone": "18860183051"}, {"name": "", "telephone": "18860183052j"}]');`)
Expect(err).NotTo(HaveOccurred())
})
Describe("获取合伙人", func() {
Context("获取合伙人", func() {
It("返回合伙人数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.GET("/partnerInfos/2929531956394199040").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("id").ValueNotEqual("id", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package partnerInfo
import (
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
"net/http"
)
var _ = Describe("获取合伙人列表", func() {
BeforeEach(func() {
_, err := pG.DB.Exec(`INSERT INTO "public"."partner_infos"("id", "partner_name", "account", "password", "status", "partner_category", "create_at", "update_at", "salesman") VALUES (2929531956394199040, 'employeeName', 'account', 'password', 1, 1, '2020-06-19 15:23:31.616934+08', '2020-06-19 15:23:31.616934+08', '[{"name": "name", "telephone": "18860183051"}, {"name": "", "telephone": "18860183052j"}]');`)
Expect(err).NotTo(HaveOccurred())
})
Describe("获取合伙人列表", func() {
Context("获取合伙人列表", func() {
It("获取合伙人列表", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.GET("/partnerInfos").
WithQuery("partnerCategory", 1).
WithQuery("status", 1).
WithQuery("status", 1).
WithQuery("sortByCreateTime", "DESC").
WithQuery("sortByUpdateTime", "DESC").
WithQuery("offset", 0).
WithQuery("limit", 20).
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().ContainsKey("partnerInfos")
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package partnerInfo
import (
"github.com/astaxie/beego"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"net/http"
"net/http/httptest"
"testing"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego"
)
func TestPartnerInfo(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port Employee Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = beego.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package partnerInfo
import (
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
"net/http"
)
var _ = Describe("创建新合伙人", func() {
BeforeEach(func() {
_, err := pG.DB.Exec(`INSERT INTO "public"."partner_infos"("id", "partner_name", "account", "password", "status", "partner_category", "create_at", "update_at", "salesman") VALUES (2929531956394199040, 'employeeName', 'account', 'password', 1, 1, '2020-06-19 15:23:31.616934+08', '2020-06-19 15:23:31.616934+08', '[{"name": "name", "telephone": "18860183051"}, {"name": "", "telephone": "18860183052j"}]');`)
Expect(err).NotTo(HaveOccurred())
})
Describe("创建新合伙人", func() {
Context("创建新合伙人", func() {
It("返回合伙人数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"partnerName": "employeeName",
"account": "account123",
"password": "password",
"status": 1,
"partnerCategory": 1,
"salesman": []map[string]interface{}{
{"name": "name", "telephone": "18860183051"},
{"name2": "name", "telephone": "18860183052j"},
},
}
httpExpect.PUT("/partnerInfos/2929531956394199040").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("id").ValueNotEqual("id", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...