作者 tangxvhui

新建项目

正在显示 57 个修改的文件 包含 2359 行增加0 行删除
  1 +# Binaries for programs and plugins
  2 +*.exe
  3 +*.dll
  4 +*.so
  5 +*.dylib
  6 +*.vscode
  7 +
  8 +# Test binary, build with `go test -c`
  9 +*.test
  10 +
  11 +# Output of the go coverage tool, specifically when used with LiteIDE
  12 +*.out
  13 +
  14 +*.log
  15 +*debug
  16 +*wasm
  17 +
  18 +*.idea
  19 +
  20 +*.tmp
  21 +
  22 +*.sum
  23 +
  24 +opp
  25 +/vendor
  26 +/*.exe~
  27 +/log
  1 +FROM golang:latest
  2 +ENV APP_DIR $GOPATH/src/partnermg
  3 +RUN mkdir -p $APP_DIR
  4 +WORKDIR $APP_DIR/
  5 +COPY ./pkg pkg
  6 +COPY ./conf conf
  7 +COPY ./go.mod go.mod
  8 +COPY ./main.go main.go
  9 +RUN ["ln","-sf","/usr/share/zoneinfo/Asia/Shanghai","/etc/localtime"]
  10 +ENV GO111MODULE on
  11 +ENV GOPROXY https://goproxy.cn
  12 +RUN ["go","mod","tidy"]
  13 +RUN ["go","build"]
  14 +ENTRYPOINT ["./partnermg"]
  1 +# 合伙人项目
  1 +appname = partner
  2 +runmode = "${RUN_MODE||dev}"
  3 +httpport = "${HTTP_PORT||8080}"
  4 +
  5 +#开启监控
  6 +EnableAdmin = false
  7 +#开启JSON请求
  8 +copyrequestbody = true
  9 +#防止跨站请求伪造 未启用
  10 +enablexsrf = false
  11 +xsrfkey = asdfioerjlasdfmFADFOEJF2323SDFF
  12 +xsrfexpire = 3600
  13 +[lang]
  14 +types = en-US|zh-CN
  15 +names = English|简体中文
  1 +#!/bin/bash
  2 +export PATH=/root/local/bin:$PATH
  3 +kubectl -n mmm-suplus-dev get pods | grep -q partner
  4 +if [ "$?" == "1" ];then
  5 + kubectl create -f /tmp/dev/partner/partner.yaml --record
  6 + kubectl -n mmm-suplus-dev get svc | grep -q partner
  7 + if [ "$?" == "0" ];then
  8 + echo "partner service install success!"
  9 + else
  10 + echo "partner service install fail!"
  11 + fi
  12 + kubectl -n mmm-suplus-dev get pods | grep -q partner
  13 + if [ "$?" == "0" ];then
  14 + echo "partner deployment install success!"
  15 + else
  16 + echo "partner deployment install fail!"
  17 + fi
  18 +else
  19 + kubectl delete -f /tmp/dev/partner/partner.yaml
  20 + kubectl -n mmm-suplus-dev get svc | grep -q partner
  21 + while [ "$?" == "0" ]
  22 + do
  23 + kubectl -n mmm-suplus-dev get svc | grep -q partner
  24 + done
  25 + kubectl -n mmm-suplus-dev get pods | grep -q partner
  26 + while [ "$?" == "0" ]
  27 + do
  28 + kubectl -n mmm-suplus-dev get pods | grep -q partner
  29 + done
  30 + kubectl create -f /tmp/dev/partner/partner.yaml --record
  31 + kubectl -n mmm-suplus-dev get svc | grep -q partner
  32 + if [ "$?" == "0" ];then
  33 + echo "partner service update success!"
  34 + else
  35 + echo "partner service update fail!"
  36 + fi
  37 + kubectl -n mmm-suplus-dev get pods | grep -q partner
  38 + if [ "$?" == "0" ];then
  39 + echo "partner deployment update success!"
  40 + else
  41 + echo "partner deployment update fail!"
  42 + fi
  43 +fi
  1 +apiVersion: v1
  2 +kind: Service
  3 +metadata:
  4 + name: partner
  5 + namespace: mmm-suplus-dev
  6 + labels:
  7 + k8s-app: partner
  8 +spec:
  9 + ports:
  10 + - name: "http"
  11 + port: 80
  12 + targetPort: 8082
  13 + selector:
  14 + k8s-app: partner
  15 +---
  16 +apiVersion: extensions/v1beta1
  17 +kind: Deployment
  18 +metadata:
  19 + name: partner
  20 + namespace: mmm-suplus-dev
  21 + labels:
  22 + k8s-app: partner
  23 +spec:
  24 + replicas: 1
  25 + template:
  26 + metadata:
  27 + labels:
  28 + k8s-app: partner
  29 + spec:
  30 + affinity:
  31 + nodeAffinity:
  32 + preferredDuringSchedulingIgnoredDuringExecution:
  33 + - preference: {}
  34 + weight: 100
  35 + requiredDuringSchedulingIgnoredDuringExecution:
  36 + nodeSelectorTerms:
  37 + - matchExpressions:
  38 + - key: kubernetes.io/hostname
  39 + operator: In
  40 + values:
  41 + - cn-hangzhou.i-bp1djh1xn7taumbue1ze
  42 + - cn-hangzhou.i-bp1djh1xn7taumbue1zd
  43 + - cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
  44 + - cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
  45 + containers:
  46 + - name: partner
  47 + image: 192.168.0.243:5000/mmm/partner:dev
  48 + imagePullPolicy: Always
  49 + ports:
  50 + - containerPort: 8082
  51 + volumeMounts:
  52 + - mountPath: /opt/logs
  53 + name: accesslogs
  54 + env:
  55 + - name: POSTGRESQL_DB_NAME
  56 + value: "partner_dev"
  57 + - name: POSTGRESQL_USER
  58 + value: "postgres"
  59 + - name: POSTGRESQL_PASSWORD
  60 + value: "postgres_15432"
  61 + - name: POSTGRESQL_HOST
  62 + value: "101.37.68.23"
  63 + - name: POSTGRESQL_PORT
  64 + value: "15432"
  65 + - name: LOG_LEVEL
  66 + value: "debug"
  67 + - name: ERROR_BASE_CODE
  68 + value: "1"
  69 + - name: ERROR_BASE_CODE_MULTIPLE
  70 + value: "1000"
  71 + - name: ABILITY_SERVICE_HOST
  72 + value: "https://suplus-worth-app-gateway-dev.fjmaimaimai.com"
  73 + - name: MMM_OPEN_API_SERVICE_HOST
  74 + value: "http://mmm-open-api-dev.fjmaimaimai.com"
  75 + volumes:
  76 + - name: accesslogs
  77 + emptyDir: {}
  1 +#!/bin/bash
  2 +export PATH=/root/local/bin:$PATH
  3 +kubectl -n mmm-suplus-prd get pods | grep -q partner
  4 +if [ "$?" == "1" ];then
  5 + kubectl create -f /tmp/prd/partner/partner.yaml --record
  6 + kubectl -n mmm-suplus-prd get svc | grep -q partner
  7 + if [ "$?" == "0" ];then
  8 + echo "partner service install success!"
  9 + else
  10 + echo "partner service install fail!"
  11 + fi
  12 + kubectl -n mmm-suplus-prd get pods | grep -q partner
  13 + if [ "$?" == "0" ];then
  14 + echo "partner deployment install success!"
  15 + else
  16 + echo "partner deployment install fail!"
  17 + fi
  18 +else
  19 + kubectl delete -f /tmp/prd/partner/partner.yaml
  20 + kubectl -n mmm-suplus-prd get svc | grep -q partner
  21 + while [ "$?" == "0" ]
  22 + do
  23 + kubectl -n mmm-suplus-prd get svc | grep -q partner
  24 + done
  25 + kubectl -n mmm-suplus-prd get pods | grep -q partner
  26 + while [ "$?" == "0" ]
  27 + do
  28 + kubectl -n mmm-suplus-prd get pods | grep -q partner
  29 + done
  30 + kubectl create -f /tmp/prd/partner/partner.yaml --record
  31 + kubectl -n mmm-suplus-prd get svc | grep -q partner
  32 + if [ "$?" == "0" ];then
  33 + echo "partner service update success!"
  34 + else
  35 + echo "partner service update fail!"
  36 + fi
  37 + kubectl -n mmm-suplus-prd get pods | grep -q partner
  38 + if [ "$?" == "0" ];then
  39 + echo "partner deployment update success!"
  40 + else
  41 + echo "partner deployment update fail!"
  42 + fi
  43 +fi
  1 +apiVersion: v1
  2 +kind: Service
  3 +metadata:
  4 + name: partner
  5 + namespace: mmm-suplus-prd
  6 + labels:
  7 + k8s-app: partner
  8 +spec:
  9 + ports:
  10 + - name: "http"
  11 + port: 80
  12 + targetPort: 8082
  13 + selector:
  14 + k8s-app: partner
  15 +---
  16 +apiVersion: extensions/v1beta1
  17 +kind: Deployment
  18 +metadata:
  19 + name: partner
  20 + namespace: mmm-suplus-prd
  21 + labels:
  22 + k8s-app: partner
  23 +spec:
  24 + replicas: 1
  25 + template:
  26 + metadata:
  27 + labels:
  28 + k8s-app: partner
  29 + spec:
  30 + affinity:
  31 + nodeAffinity:
  32 + preferredDuringSchedulingIgnoredDuringExecution:
  33 + - preference: {}
  34 + weight: 100
  35 + requiredDuringSchedulingIgnoredDuringExecution:
  36 + nodeSelectorTerms:
  37 + - matchExpressions:
  38 + - key: kubernetes.io/hostname
  39 + operator: In
  40 + values:
  41 + - cn-hangzhou.i-bp1djh1xn7taumbue1ze
  42 + - cn-hangzhou.i-bp1djh1xn7taumbue1zd
  43 + - cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
  44 + - cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
  45 + containers:
  46 + - name: partner
  47 + image: 192.168.0.243:5000/mmm/partner:master
  48 + imagePullPolicy: Always
  49 + ports:
  50 + - containerPort: 8082
  51 + volumeMounts:
  52 + - mountPath: /opt/logs
  53 + name: accesslogs
  54 + env:
  55 + - name: POSTGRESQL_DB_NAME
  56 + value: "partner"
  57 + - name: POSTGRESQL_USER
  58 + value: "postgres"
  59 + - name: POSTGRESQL_PASSWORD
  60 + value: "postgres_55_online"
  61 + - name: POSTGRESQL_HOST
  62 + value: "112.124.115.55"
  63 + - name: POSTGRESQL_PORT
  64 + value: "15432"
  65 + - name: LOG_LEVEL
  66 + value: "debug"
  67 + - name: ERROR_BASE_CODE
  68 + value: "1"
  69 + - name: ERROR_BASE_CODE_MULTIPLE
  70 + value: "1000"
  71 + - name: ABILITY_SERVICE_HOST
  72 + value: "https://ability.fjmaimaimai.com"
  73 + - name: MMM_OPEN_API_SERVICE_HOST
  74 + value: "https://public-interface.fjmaimaimai.com/openapi"
  75 + volumes:
  76 + - name: accesslogs
  77 + emptyDir: {}
  1 +#!/bin/bash
  2 +export PATH=/root/local/bin:$PATH
  3 +kubectl -n mmm-suplus-test get pods | grep -q partner
  4 +if [ "$?" == "1" ];then
  5 + kubectl create -f /tmp/test/partner/partner.yaml --record
  6 + kubectl -n mmm-suplus-test get svc | grep -q partner
  7 + if [ "$?" == "0" ];then
  8 + echo "partner service install success!"
  9 + else
  10 + echo "partner service install fail!"
  11 + fi
  12 + kubectl -n mmm-suplus-test get pods | grep -q partner
  13 + if [ "$?" == "0" ];then
  14 + echo "partner deployment install success!"
  15 + else
  16 + echo "partner deployment install fail!"
  17 + fi
  18 +else
  19 + kubectl delete -f /tmp/test/partner/partner.yaml
  20 + kubectl -n mmm-suplus-test get svc | grep -q partner
  21 + while [ "$?" == "0" ]
  22 + do
  23 + kubectl -n mmm-suplus-test get svc | grep -q partner
  24 + done
  25 + kubectl -n mmm-suplus-test get pods | grep -q partner
  26 + while [ "$?" == "0" ]
  27 + do
  28 + kubectl -n mmm-suplus-test get pods | grep -q partner
  29 + done
  30 + kubectl create -f /tmp/test/partner/partner.yaml --record
  31 + kubectl -n mmm-suplus-test get svc | grep -q partner
  32 + if [ "$?" == "0" ];then
  33 + echo "partner service update success!"
  34 + else
  35 + echo "partner service update fail!"
  36 + fi
  37 + kubectl -n mmm-suplus-test get pods | grep -q partner
  38 + if [ "$?" == "0" ];then
  39 + echo "partner deployment update success!"
  40 + else
  41 + echo "partner deployment update fail!"
  42 + fi
  43 +fi
  1 +apiVersion: v1
  2 +kind: Service
  3 +metadata:
  4 + name: partner
  5 + namespace: mmm-suplus-test
  6 + labels:
  7 + k8s-app: partner
  8 +spec:
  9 + ports:
  10 + - name: "http"
  11 + port: 80
  12 + targetPort: 8082
  13 + selector:
  14 + k8s-app: partner
  15 +---
  16 +apiVersion: extensions/v1beta1
  17 +kind: Deployment
  18 +metadata:
  19 + name: partner
  20 + namespace: mmm-suplus-test
  21 + labels:
  22 + k8s-app: partner
  23 +spec:
  24 + replicas: 1
  25 + template:
  26 + metadata:
  27 + labels:
  28 + k8s-app: partner
  29 + spec:
  30 + affinity:
  31 + nodeAffinity:
  32 + preferredDuringSchedulingIgnoredDuringExecution:
  33 + - preference: {}
  34 + weight: 100
  35 + requiredDuringSchedulingIgnoredDuringExecution:
  36 + nodeSelectorTerms:
  37 + - matchExpressions:
  38 + - key: kubernetes.io/hostname
  39 + operator: In
  40 + values:
  41 + - cn-hangzhou.i-bp1djh1xn7taumbue1ze
  42 + - cn-hangzhou.i-bp1djh1xn7taumbue1zd
  43 + - cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
  44 + - cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
  45 + containers:
  46 + - name: partner
  47 + image: 192.168.0.243:5000/mmm/partner:test
  48 + imagePullPolicy: Always
  49 + ports:
  50 + - containerPort: 8082
  51 + volumeMounts:
  52 + - mountPath: /opt/logs
  53 + name: accesslogs
  54 + env:
  55 + - name: POSTGRESQL_DB_NAME
  56 + value: "partner_test"
  57 + - name: POSTGRESQL_USER
  58 + value: "postgres"
  59 + - name: POSTGRESQL_PASSWORD
  60 + value: "postgres_15432"
  61 + - name: POSTGRESQL_HOST
  62 + value: "101.37.68.23"
  63 + - name: POSTGRESQL_PORT
  64 + value: "15432"
  65 + - name: LOG_LEVEL
  66 + value: "debug"
  67 + - name: ERROR_BASE_CODE
  68 + value: "1"
  69 + - name: ERROR_BASE_CODE_MULTIPLE
  70 + value: "1000"
  71 + - name: ABILITY_SERVICE_HOST
  72 + value: "https://suplus-worth-app-gateway-test.fjmaimaimai.com"
  73 + - name: MMM_OPEN_API_SERVICE_HOST
  74 + value: "http://mmm-open-api-test.fjmaimaimai.com"
  75 + volumes:
  76 + - name: accesslogs
  77 + emptyDir: {}
  1 +module gitlab.fjmaimaimai.com/mmm-go/partnermg
  2 +
  3 +go 1.14
  4 +
  5 +require (
  6 + github.com/ajg/form v1.5.1 // indirect
  7 + github.com/astaxie/beego v1.12.1
  8 + github.com/dgrijalva/jwt-go v3.2.0+incompatible
  9 + github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
  10 + github.com/fatih/structs v1.1.0 // indirect
  11 + github.com/gavv/httpexpect v2.0.0+incompatible
  12 + github.com/go-pg/pg/v10 v10.0.0-beta.2
  13 + github.com/google/go-querystring v1.0.0 // indirect
  14 + github.com/gorilla/websocket v1.4.2 // indirect
  15 + github.com/imkira/go-interpol v1.1.0 // indirect
  16 + github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
  17 + github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9
  18 + github.com/mattn/go-colorable v0.1.6 // indirect
  19 + github.com/moul/http2curl v1.0.0 // indirect
  20 + github.com/onsi/ginkgo v1.13.0
  21 + github.com/onsi/gomega v1.10.1
  22 + github.com/prometheus/common v0.10.0
  23 + github.com/sergi/go-diff v1.1.0 // indirect
  24 + github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
  25 + github.com/smartystreets/goconvey v1.6.4 // indirect
  26 + github.com/valyala/fasthttp v1.14.0 // indirect
  27 + github.com/xeipuuv/gojsonschema v1.2.0 // indirect
  28 + github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
  29 + github.com/yudai/gojsondiff v1.0.0 // indirect
  30 + github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
  31 + github.com/yudai/pp v2.0.1+incompatible // indirect
  32 +)
  1 +package main
  2 +
  3 +import (
  4 + "github.com/astaxie/beego"
  5 + "github.com/astaxie/beego/logs"
  6 + _ "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  7 + _ "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/log"
  8 + _ "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego"
  9 +)
  10 +
  11 +func main() {
  12 + logs.Info("应用启动")
  13 + beego.Run()
  14 +}
  1 +package query
  2 +
  3 +type GetAdminUserQuery struct {
  4 + Id int64 `json:"id"`
  5 + Admin_Account string `json:"admin_account"`
  6 +}
  1 +package query
  2 +
  3 +//ListAdminUserQuery 获取用户列表
  4 +type ListAdminUserQuery struct {
  5 + //账号匹配
  6 + AdminAccountMatch string `json:"admin_account_match" form:"account_match"`
  7 + // 查询偏离量
  8 + Offset int `json:"offset" form:"offset"`
  9 + // 查询限制
  10 + Limit int `json:"limit" form:"limit"`
  11 +}
  1 +package service
  2 +
  3 +import (
  4 + "github.com/linmadan/egglib-go/core/application"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/query"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  7 +)
  8 +
  9 +//AdminUserService 管理员相关服务
  10 +type AdminUserService struct {
  11 +}
  12 +
  13 +func NewAdminUserService(option map[string]interface{}) *AdminUserService {
  14 + newAdminUserService := new(AdminUserService)
  15 + return newAdminUserService
  16 +}
  17 +
  18 +func (adminUserSrv AdminUserService) GetAdminUser(getAdminUserQuery *query.GetAdminUserQuery) (interface{}, error) {
  19 + //实际业务
  20 + var err error
  21 + if err != nil {
  22 + return nil, application.ThrowError(application.BUSINESS_ERROR, "业务逻辑错误")
  23 + }
  24 +
  25 + return domain.AdminUser{}, nil
  26 +}
  1 +package factory
  2 +
  3 +//func CreateTaskDao(options map[string]interface{}) (*dao.TaskDao, error) {
  4 +// var transactionContext *pg.TransactionContext
  5 +// if value, ok := options["transactionContext"]; ok {
  6 +// transactionContext = value.(*pg.TransactionContext)
  7 +// }
  8 +// return dao.NewTaskDao(transactionContext)
  9 +//}
  1 +package factory
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/repository"
  7 +)
  8 +
  9 +//CreatePartnerInfoRepository 合伙人信息
  10 +func CreatePartnerInfoRepository(options map[string]interface{}) (domain.PartnerInfoRepository, error) {
  11 + var transactionContext *transaction.TransactionContext
  12 + if value, ok := options["transactionContext"]; ok {
  13 + transactionContext = value.(*transaction.TransactionContext)
  14 + }
  15 + return repository.NewPartnerInfoRepository(transactionContext)
  16 +}
  17 +
  18 +//CreateAdminUserRepository 管理员信息
  19 +func CreateAdminUserRepository(options map[string]interface{}) (domain.AdminUserRepository, error) {
  20 + var transactionContext *transaction.TransactionContext
  21 + if value, ok := options["transactionContext"]; ok {
  22 + transactionContext = value.(*transaction.TransactionContext)
  23 + }
  24 + return repository.NewAdminUserRepository(transactionContext)
  25 +}
  1 +package factory
  2 +
  3 +import (
  4 + "github.com/linmadan/egglib-go/core/application"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
  7 +)
  8 +
  9 +func CreateTransactionContext(options map[string]interface{}) (application.TransactionContext, error) {
  10 + return &transaction.TransactionContext{
  11 + PgDd: pg.DB,
  12 + }, nil
  13 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  6 +
  7 + "github.com/astaxie/beego/validation"
  8 +)
  9 +
  10 +type CreatePartnerInfoCommand struct {
  11 + domain.PartnerInfo
  12 +}
  13 +
  14 +func (c *CreatePartnerInfoCommand) ValidateCommand() error {
  15 + valid := validation.Validation{}
  16 + b, err := valid.Valid(c)
  17 + if err != nil {
  18 + return err
  19 + }
  20 + if !b {
  21 + for _, validErr := range valid.Errors {
  22 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  23 + }
  24 + }
  25 + return nil
  26 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/astaxie/beego/validation"
  7 +)
  8 +
  9 +type RemovePartnerInfoCommand struct {
  10 + // 合伙人ID
  11 + Id int `json:"id" valid:"Required"`
  12 +}
  13 +
  14 +func (c *RemovePartnerInfoCommand) ValidateCommand() error {
  15 + valid := validation.Validation{}
  16 + b, err := valid.Valid(c)
  17 + if err != nil {
  18 + return err
  19 + }
  20 + if !b {
  21 + for _, validErr := range valid.Errors {
  22 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  23 + }
  24 + }
  25 + return nil
  26 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/astaxie/beego/validation"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  7 +)
  8 +
  9 +type UpdatePartnerInfoCommand struct {
  10 + // 合伙人Id
  11 + Id int `json:"id,omitempty"`
  12 +
  13 + // 合伙人姓名
  14 + PartnerName string `json:"partnerName,omitempty"`
  15 + // 登录账号
  16 + Account string `json:"account,omitempty"`
  17 + // 登录密码
  18 + Password string `json:"password,omitempty"`
  19 + // 状态(1:启用或者0:禁用)
  20 + Status int `json:"status"`
  21 + // 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
  22 + PartnerCategory int `json:"partnerCategory,omitempty"`
  23 +
  24 + //关联业务员
  25 + Salesman []*domain.Salesman `json:"salesman,omitempty"`
  26 +}
  27 +
  28 +func (c *UpdatePartnerInfoCommand) ValidateCommand() error {
  29 + valid := validation.Validation{}
  30 + b, err := valid.Valid(c)
  31 + if err != nil {
  32 + return err
  33 + }
  34 + if !b {
  35 + for _, validErr := range valid.Errors {
  36 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  37 + }
  38 + }
  39 + return nil
  40 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/astaxie/beego/validation"
  7 +)
  8 +
  9 +type GetPartnerInfoQuery struct {
  10 + // 合伙人ID
  11 + Id int `json:"id" valid:"Required"`
  12 +}
  13 +
  14 +func (q *GetPartnerInfoQuery) ValidateQuery() error {
  15 + valid := validation.Validation{}
  16 + b, err := valid.Valid(q)
  17 + if err != nil {
  18 + return err
  19 + }
  20 + if !b {
  21 + for _, validErr := range valid.Errors {
  22 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  23 + }
  24 + }
  25 + return nil
  26 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/astaxie/beego/validation"
  7 +)
  8 +
  9 +type ListPartnerInfoQuery struct {
  10 + //状态
  11 + Status int `json:"status,omitempty"`
  12 + // 合伙人类别
  13 + PartnerCategory int `json:"partnerCategory,omitempty"`
  14 + //按创建任务时间排序(ASC,DESC)
  15 + SortByCreateTime string `json:"sortByCreateTime,omitempty"`
  16 + //按创建任务时间排序(ASC,DESC)
  17 + SortByUpdateTime string `json:"sortByUpdateTime,omitempty"`
  18 + // 查询偏离量
  19 + Offset int `json:"offset,omitempty"`
  20 + // 查询限制
  21 + Limit int `json:"limit,omitempty"`
  22 +}
  23 +
  24 +func (q *ListPartnerInfoQuery) ValidateQuery() error {
  25 + valid := validation.Validation{}
  26 + b, err := valid.Valid(q)
  27 + if err != nil {
  28 + return err
  29 + }
  30 + if !b {
  31 + for _, validErr := range valid.Errors {
  32 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  33 + }
  34 + }
  35 + return nil
  36 +}
  1 +package service
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/linmadan/egglib-go/core/application"
  6 + "github.com/linmadan/egglib-go/utils/tool_funs"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/partnerInfo/command"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/partnerInfo/query"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  11 + "time"
  12 +)
  13 +
  14 +// 客户价值服务
  15 +type PartnerInfoService struct {
  16 +}
  17 +
  18 +// 创建客户价值
  19 +func (PartnerInfoService *PartnerInfoService) CreatePartnerInfo(command *command.CreatePartnerInfoCommand) (data interface{}, err error) {
  20 + var (
  21 + count int64
  22 + transactionContext, _ = factory.CreateTransactionContext(nil)
  23 + )
  24 + if err = command.ValidateCommand(); err != nil {
  25 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  26 + }
  27 + if err = transactionContext.StartTransaction(); err != nil {
  28 + return nil, err
  29 + }
  30 + defer func() {
  31 + if err != nil {
  32 + transactionContext.RollbackTransaction()
  33 + }
  34 + }()
  35 +
  36 + newPartnerInfo := &command.PartnerInfo
  37 + newPartnerInfo.CreateAt = time.Now()
  38 + newPartnerInfo.UpdateAt = time.Now()
  39 +
  40 + var PartnerInfoRepository domain.PartnerInfoRepository
  41 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
  42 + return nil, err
  43 + }
  44 + if count, _, err = PartnerInfoRepository.Find(map[string]interface{}{"account": command.Account}); err != nil {
  45 + return nil, err
  46 + }
  47 + if count > 0 {
  48 + return nil, fmt.Errorf("标签不可重复名称")
  49 + }
  50 +
  51 + if data, err = PartnerInfoRepository.Save(newPartnerInfo); err != nil {
  52 + return
  53 + }
  54 + err = transactionContext.CommitTransaction()
  55 + return
  56 +}
  57 +
  58 +// 返回客户价值
  59 +func (PartnerInfoService *PartnerInfoService) GetPartnerInfo(command *query.GetPartnerInfoQuery) (data interface{}, err error) {
  60 + var (
  61 + transactionContext, _ = factory.CreateTransactionContext(nil)
  62 + )
  63 + if err = command.ValidateQuery(); err != nil {
  64 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  65 + }
  66 + if err := transactionContext.StartTransaction(); err != nil {
  67 + return nil, err
  68 + }
  69 + defer func() {
  70 + if err != nil {
  71 + transactionContext.RollbackTransaction()
  72 + }
  73 + }()
  74 + var PartnerInfoRepository domain.PartnerInfoRepository
  75 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
  76 + return nil, err
  77 + }
  78 + data, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": command.Id})
  79 + if err != nil {
  80 + return nil, err
  81 + }
  82 + if data == nil {
  83 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(command.Id)))
  84 + }
  85 + err = transactionContext.CommitTransaction()
  86 + return
  87 +}
  88 +
  89 +// 更新客户价值
  90 +func (PartnerInfoService *PartnerInfoService) UpdatePartnerInfo(updatePartnerInfoCommand *command.UpdatePartnerInfoCommand) (data interface{}, err error) {
  91 + var (
  92 + transactionContext, _ = factory.CreateTransactionContext(nil)
  93 + PartnerInfo *domain.PartnerInfo
  94 + )
  95 + if err = updatePartnerInfoCommand.ValidateCommand(); err != nil {
  96 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  97 + }
  98 + if err := transactionContext.StartTransaction(); err != nil {
  99 + return nil, err
  100 + }
  101 + defer func() {
  102 + if err != nil {
  103 + transactionContext.RollbackTransaction()
  104 + }
  105 + }()
  106 + var PartnerInfoRepository domain.PartnerInfoRepository
  107 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
  108 + return nil, err
  109 + }
  110 + PartnerInfo, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": updatePartnerInfoCommand.Id})
  111 + if err != nil {
  112 + return nil, err
  113 + }
  114 + if PartnerInfo == nil {
  115 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updatePartnerInfoCommand.Id)))
  116 + }
  117 + //if count, PartnerInfos, err := PartnerInfoRepository.Find(map[string]interface{}{
  118 + // "PartnerInfoName": updatePartnerInfoCommand.PartnerInfoName,
  119 + // "companyId": PartnerInfo.CompanyId,
  120 + //}); err != nil {
  121 + // return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  122 + //} else {
  123 + // if count > 0 && PartnerInfos[0].PartnerInfoId != PartnerInfo.PartnerInfoId {
  124 + // return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "标签不可重复名称")
  125 + // }
  126 + //}
  127 + if err := PartnerInfo.Update(tool_funs.SimpleStructToMap(updatePartnerInfoCommand)); err != nil {
  128 + return nil, err
  129 + }
  130 +
  131 + if data, err = PartnerInfoRepository.Save(PartnerInfo); err != nil {
  132 + return nil, err
  133 + }
  134 + err = transactionContext.CommitTransaction()
  135 + return
  136 +}
  137 +
  138 +// 移除客户价值
  139 +func (PartnerInfoService *PartnerInfoService) RemovePartnerInfo(removePartnerInfoCommand *command.RemovePartnerInfoCommand) (data interface{}, err error) {
  140 + var (
  141 + transactionContext, _ = factory.CreateTransactionContext(nil)
  142 + PartnerInfo *domain.PartnerInfo
  143 + )
  144 + if err = removePartnerInfoCommand.ValidateCommand(); err != nil {
  145 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  146 + }
  147 + if err = transactionContext.StartTransaction(); err != nil {
  148 + return nil, err
  149 + }
  150 + defer func() {
  151 + if err != nil {
  152 + transactionContext.RollbackTransaction()
  153 + }
  154 + }()
  155 + var PartnerInfoRepository domain.PartnerInfoRepository
  156 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
  157 + return nil, err
  158 + }
  159 + PartnerInfo, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": removePartnerInfoCommand.Id})
  160 + if err != nil {
  161 + return nil, err
  162 + }
  163 + if PartnerInfo == nil {
  164 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removePartnerInfoCommand.Id)))
  165 + }
  166 + if data, err = PartnerInfoRepository.Remove(PartnerInfo); err != nil {
  167 + return nil, err
  168 + }
  169 + err = transactionContext.CommitTransaction()
  170 + return
  171 +}
  172 +
  173 +// 返回客户价值列表
  174 +func (PartnerInfoService *PartnerInfoService) ListPartnerInfo(listPartnerInfoQuery *query.ListPartnerInfoQuery) (data interface{}, err error) {
  175 + var (
  176 + transactionContext, _ = factory.CreateTransactionContext(nil)
  177 + PartnerInfos []*domain.PartnerInfo
  178 + count int64
  179 + )
  180 + if err = listPartnerInfoQuery.ValidateQuery(); err != nil {
  181 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  182 + }
  183 + if err := transactionContext.StartTransaction(); err != nil {
  184 + return nil, err
  185 + }
  186 + defer func() {
  187 + if err != nil {
  188 + transactionContext.RollbackTransaction()
  189 + }
  190 + }()
  191 + var PartnerInfoRepository domain.PartnerInfoRepository
  192 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
  193 + return nil, err
  194 + }
  195 + if count, PartnerInfos, err = PartnerInfoRepository.Find(tool_funs.SimpleStructToMap(listPartnerInfoQuery)); err != nil {
  196 + return nil, err
  197 + }
  198 + if err = transactionContext.CommitTransaction(); err != nil {
  199 + return nil, err
  200 + }
  201 + return map[string]interface{}{
  202 + "count": count,
  203 + "partnerInfos": PartnerInfos,
  204 + }, nil
  205 +}
  206 +
  207 +func NewPartnerInfoService(options map[string]interface{}) *PartnerInfoService {
  208 + newPartnerInfoService := &PartnerInfoService{}
  209 + return newPartnerInfoService
  210 +}
  1 +package constant
  2 +
  3 +import "os"
  4 +
  5 +const SERVICE_NAME = "partnermg"
  6 +
  7 +var LOG_LEVEL = "debug"
  8 +var LOG_File = "app.log"
  9 +
  10 +func init() {
  11 + if os.Getenv("LOG_LEVEL") != "" {
  12 + LOG_LEVEL = os.Getenv("LOG_LEVEL")
  13 + }
  14 +}
  1 +package constant
  2 +
  3 +import "os"
  4 +
  5 +var POSTGRESQL_DB_NAME = "partner_dev"
  6 +var POSTGRESQL_USER = "postgres"
  7 +var POSTGRESQL_PASSWORD = "postgres_15432"
  8 +var POSTGRESQL_HOST = "101.37.68.23"
  9 +var POSTGRESQL_PORT = "15432"
  10 +var DISABLE_CREATE_TABLE = true
  11 +var DISABLE_SQL_GENERATE_PRINT = false
  12 +
  13 +func init() {
  14 + if os.Getenv("POSTGRESQL_DB_NAME") != "" {
  15 + POSTGRESQL_DB_NAME = os.Getenv("POSTGRESQL_DB_NAME")
  16 + }
  17 + if os.Getenv("POSTGRESQL_USER") != "" {
  18 + POSTGRESQL_USER = os.Getenv("POSTGRESQL_USER")
  19 + }
  20 + if os.Getenv("POSTGRESQL_PASSWORD") != "" {
  21 + POSTGRESQL_PASSWORD = os.Getenv("POSTGRESQL_PASSWORD")
  22 + }
  23 + if os.Getenv("POSTGRESQL_HOST") != "" {
  24 + POSTGRESQL_HOST = os.Getenv("POSTGRESQL_HOST")
  25 + }
  26 + if os.Getenv("POSTGRESQL_PORT") != "" {
  27 + POSTGRESQL_PORT = os.Getenv("POSTGRESQL_PORT")
  28 + }
  29 + if os.Getenv("DISABLE_CREATE_TABLE") != "" {
  30 + DISABLE_CREATE_TABLE = true
  31 + }
  32 + if os.Getenv("DISABLE_SQL_GENERATE_PRINT") != "" {
  33 + DISABLE_SQL_GENERATE_PRINT = true
  34 + }
  35 +}
  1 +package domain
  2 +
  3 +//权限代码
  4 +const (
  5 + PERMINSSION_ADMIN_USER string = "ADMIN_USER"
  6 + PERMINSSION_PARTNER string = "PARTNER"
  7 +)
  8 +
  9 +//权限数据
  10 +var ConstAdminPermissions = map[string]AdminPermission{
  11 + PERMINSSION_ADMIN_USER: AdminPermission{
  12 + Code: PERMINSSION_ADMIN_USER,
  13 + Name: "管理员管理",
  14 + },
  15 + PERMINSSION_PARTNER: AdminPermission{
  16 + Code: PERMINSSION_PARTNER,
  17 + Name: "合伙人管理",
  18 + },
  19 +}
  20 +
  21 +// 权限结构
  22 +type AdminPermission struct {
  23 + Code string `json:"code"`
  24 + Name string `json:"name"`
  25 +}
  26 +
  27 +func (permission AdminPermission) GetPermissions(codes []string) []AdminPermission {
  28 + newPermissions := []AdminPermission{}
  29 + if len(codes) == 0 {
  30 + return newPermissions
  31 + }
  32 + for i := range codes {
  33 + code := codes[i]
  34 + if _, ok := ConstAdminPermissions[code]; ok {
  35 + newPermissions = append(newPermissions, ConstAdminPermissions[code])
  36 + }
  37 + }
  38 + return newPermissions
  39 +}
  1 +package domain
  2 +
  3 +//AdminUser 管理员
  4 +type AdminUser struct {
  5 + //id
  6 + Id int64 `json:"id"`
  7 + //账号
  8 + Account string `json:"account"`
  9 + //密码
  10 + Password string `json:"password"`
  11 + //管理员名称
  12 + AdminName string `json:"admin_name"`
  13 + //是否是默认系统账号
  14 + IsDefault bool `json:"is_default"`
  15 + //账号是否可用
  16 + IsUsable bool `json:"is_userable"`
  17 + //创建时间
  18 + CreateAt string `json:"create_at"`
  19 + //用户权限
  20 + Permission []AdminPermission `json:"permission"`
  21 +}
  22 +
  23 +type AdminUserFindQuery struct {
  24 + AccountLike string
  25 + Offset int
  26 + Limit int
  27 +}
  28 +
  29 +type AdminUserFindOneQuery struct {
  30 + AdminUserId int64
  31 + AccountEqual string
  32 +}
  33 +
  34 +type AdminUserRepository interface {
  35 + // Save(*AdminUser) (*AdminUser, error)
  36 + // Remove(user *AdminUser) (*AdminUser, error)
  37 + FindOne(qureyOptions AdminUserFindOneQuery) (*AdminUser, error)
  38 + // Find(queryOptions AdminUserFindQuery) (int, []*AdminUser, error)
  39 +}
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +type PartnerInfoRepository interface {
  6 + Save(dm *PartnerInfo) (*PartnerInfo, error)
  7 + Remove(dm *PartnerInfo) (*PartnerInfo, error)
  8 + FindOne(queryOptions map[string]interface{}) (*PartnerInfo, error)
  9 + Find(queryOptions map[string]interface{}) (int64, []*PartnerInfo, error)
  10 +}
  11 +
  12 +type PartnerInfo struct {
  13 + // 合伙人ID
  14 + Id int64 `json:"id"`
  15 + // 合伙人姓名
  16 + PartnerName string `json:"partnerName"`
  17 + // 登录账号
  18 + Account string `json:"account"`
  19 + // 登录密码
  20 + Password string `json:"password"`
  21 + // 状态(1:启用或者0:禁用)
  22 + Status int `json:"status"`
  23 + // 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
  24 + PartnerCategory int `json:"partnerCategory"`
  25 +
  26 + //创建时间
  27 + CreateAt time.Time `json:"createAt"`
  28 + //更新时间
  29 + UpdateAt time.Time `json:"updateAt"`
  30 +
  31 + //关联业务员
  32 + Salesman []*Salesman `json:"salesman"`
  33 +}
  34 +
  35 +func (m *PartnerInfo) Identify() interface{} {
  36 + if m.Id == 0 {
  37 + return nil
  38 + }
  39 + return m.Id
  40 +}
  41 +
  42 +func (m *PartnerInfo) Update(data map[string]interface{}) error {
  43 + if partnerName, ok := data["partnerName"]; ok && partnerName != "" {
  44 + m.PartnerName = partnerName.(string)
  45 + }
  46 + if account, ok := data["account"]; ok && account != "" {
  47 + m.Account = account.(string)
  48 + }
  49 + if password, ok := data["account"]; ok && password != "" {
  50 + m.Password = password.(string)
  51 + }
  52 + if status, ok := data["status"]; ok && status != 0 {
  53 + m.Status = status.(int)
  54 + }
  55 + if partnerCategory, ok := data["partnerCategory"]; ok && partnerCategory != 0 {
  56 + m.PartnerCategory = partnerCategory.(int)
  57 + }
  58 + if salesman, ok := data["salesman"]; ok {
  59 + m.Salesman = salesman.([]*Salesman)
  60 + }
  61 + m.UpdateAt = time.Now()
  62 + return nil
  63 +}
  1 +package domain
  2 +
  3 +//关联业务员
  4 +type Salesman struct {
  5 + //Id int64 `json:"id"`
  6 + Name string `json:"name"`
  7 + Telephone string `json:"telephone"`
  8 +}
  1 +package dao
  2 +
  3 +//import (
  4 +// "fmt"
  5 +// "github.com/go-pg/pg/v10"
  6 +// pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  7 +// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
  8 +// "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg/models"
  9 +// "time"
  10 +//)
  11 +//
  12 +//type EmployeeDao struct {
  13 +// transactionContext *pgTransaction.TransactionContext
  14 +//}
  15 +//
  16 +//func (dao *EmployeeDao) BatchRemove(uids []int64) error {
  17 +// tx := dao.transactionContext.PgTx
  18 +// _, err := tx.QueryOne(
  19 +// pg.Scan(),
  20 +// "DELETE FROM employees WHERE uid IN (?)",
  21 +// pg.In(uids))
  22 +// return err
  23 +//}
  24 +//
  25 +//func (dao *EmployeeDao) BatchSetStatus(uids []int64, status int) error {
  26 +// tx := dao.transactionContext.PgTx
  27 +// _, err := tx.QueryOne(
  28 +// pg.Scan(),
  29 +// "UPDATE employees SET status=? WHERE uid IN (?)",
  30 +// status, pg.In(uids))
  31 +// return err
  32 +//}
  33 +//
  34 +//func (dao *EmployeeDao) ChangePrincipal(companyId int64, employeeAccount string) error {
  35 +// tx := dao.transactionContext.PgTx
  36 +// if _, err := tx.Query(
  37 +// pg.Scan(),
  38 +// "UPDATE employees SET is_principal=? WHERE company_id=?",
  39 +// false, companyId); err != nil {
  40 +// return err
  41 +// }
  42 +// if _, err := tx.QueryOne(
  43 +// pg.Scan(),
  44 +// "UPDATE employees SET is_principal=? WHERE company_id=? AND employee_account=?",
  45 +// true, companyId, employeeAccount); err != nil {
  46 +// return err
  47 +// }
  48 +// return nil
  49 +//}
  50 +//
  51 +//func (dao *EmployeeDao) TransferSuMoney(uid int64, suMoney float64) error {
  52 +// tx := dao.transactionContext.PgTx
  53 +// _, err := tx.QueryOne(
  54 +// pg.Scan(),
  55 +// "UPDATE employees SET su_money=su_money+? WHERE uid=?",
  56 +// suMoney, uid)
  57 +// return err
  58 +//}
  59 +//
  60 +//func (dao *EmployeeDao) CalculatePersonUnReadNotification(uid int64) (map[string]int, error) {
  61 +// var unReadSystemNotification int
  62 +// var unReadInteractionNotification int
  63 +// tx := dao.transactionContext.PgTx
  64 +// sentNotificationModel := new(models.SentNotification)
  65 +// if count, err := tx.Model(sentNotificationModel).Relation("Notification").
  66 +// Where(`sent_notification.receiver @> '{"uid":?}'`, uid).
  67 +// Where("notification.notification_type = ?", domain.NOTIFICATION_TYPE_SYSTEM).
  68 +// Where("sent_notification.is_read = ?", false).
  69 +// Count(); err != nil {
  70 +// return nil, err
  71 +// } else {
  72 +// unReadSystemNotification = count
  73 +// }
  74 +// if count, err := tx.Model(sentNotificationModel).Relation("Notification").
  75 +// Where(`sent_notification.receiver @> '{"uid":?}'`, uid).
  76 +// Where("notification.notification_type = ?", domain.NOTIFICATION_TYPE_INTERACTION).
  77 +// Where("sent_notification.is_read = ?", false).
  78 +// Count(); err != nil {
  79 +// return nil, err
  80 +// } else {
  81 +// unReadInteractionNotification = count
  82 +// }
  83 +// return map[string]int{
  84 +// "unReadSystemNotification": unReadSystemNotification,
  85 +// "unReadInteractionNotification": unReadInteractionNotification,
  86 +// }, nil
  87 +//}
  88 +//
  89 +//func (dao *EmployeeDao) CalculatePersonSuMoney(uid int64) (map[string]interface{}, error) {
  90 +// var incomeSuMoney float64
  91 +// var incomeSuMoneyOfYesterday float64
  92 +// tx := dao.transactionContext.PgTx
  93 +// suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
  94 +// yesterday := time.Now().AddDate(0, 0, -1)
  95 +// if err := tx.Model(suMoneyTransactionRecordModel).
  96 +// ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
  97 +// Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
  98 +// Where(`su_money_transaction_record.record_type = ?`, 2).
  99 +// Where(`su_money_transaction_record.create_time > ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, yesterday.Location())).
  100 +// Where(`su_money_transaction_record.create_time < ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 0, yesterday.Location())).
  101 +// Select(&incomeSuMoneyOfYesterday); err != nil {
  102 +// return nil, err
  103 +// }
  104 +// if err := tx.Model(suMoneyTransactionRecordModel).
  105 +// ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
  106 +// Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
  107 +// Where(`su_money_transaction_record.record_type = ?`, 2).
  108 +// Select(&incomeSuMoney); err != nil {
  109 +// return nil, err
  110 +// }
  111 +// return map[string]interface{}{
  112 +// "incomeSuMoney": incomeSuMoney,
  113 +// "incomeSuMoneyOfYesterday": incomeSuMoneyOfYesterday,
  114 +// }, nil
  115 +//}
  116 +//
  117 +//func (dao *EmployeeDao) CalculateSuMoneyTransactionRecord(uid int64, transactionStartTime time.Time, transactionEndTime time.Time) (map[string]interface{}, error) {
  118 +// var incomeSuMoney float64
  119 +// var expendSuMoney float64
  120 +// tx := dao.transactionContext.PgTx
  121 +// suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
  122 +// if err := tx.Model(suMoneyTransactionRecordModel).
  123 +// ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
  124 +// Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
  125 +// Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{2, 3})).
  126 +// Where(`su_money_transaction_record.create_time > ?`, transactionStartTime).
  127 +// Where(`su_money_transaction_record.create_time < ?`, transactionEndTime).
  128 +// Select(&incomeSuMoney); err != nil {
  129 +// return nil, err
  130 +// }
  131 +// if err := tx.Model(suMoneyTransactionRecordModel).
  132 +// ColumnExpr("sum(su_money_transaction_record.su_money) AS expend_su_money").
  133 +// Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
  134 +// Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{1, 4})).
  135 +// Where(`su_money_transaction_record.create_time > ?`, transactionStartTime).
  136 +// Where(`su_money_transaction_record.create_time < ?`, transactionEndTime).
  137 +// Select(&expendSuMoney); err != nil {
  138 +// return nil, err
  139 +// }
  140 +// return map[string]interface{}{
  141 +// "incomeSuMoney": incomeSuMoney,
  142 +// "expendSuMoney": expendSuMoney,
  143 +// }, nil
  144 +//}
  145 +//
  146 +//func NewEmployeeDao(transactionContext *pgTransaction.TransactionContext) (*EmployeeDao, error) {
  147 +// if transactionContext == nil {
  148 +// return nil, fmt.Errorf("transactionContext参数不能为nil")
  149 +// } else {
  150 +// return &EmployeeDao{
  151 +// transactionContext: transactionContext,
  152 +// }, nil
  153 +// }
  154 +//}
  1 +package pg
  2 +
  3 +import (
  4 + "context"
  5 + "fmt"
  6 +
  7 + "github.com/go-pg/pg/v10"
  8 + "github.com/go-pg/pg/v10/orm"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/log"
  12 +)
  13 +
  14 +var DB *pg.DB
  15 +
  16 +func init() {
  17 + DB = pg.Connect(&pg.Options{
  18 + User: constant.POSTGRESQL_USER,
  19 + Password: constant.POSTGRESQL_PASSWORD,
  20 + Database: constant.POSTGRESQL_DB_NAME,
  21 + Addr: fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
  22 + })
  23 + if !constant.DISABLE_SQL_GENERATE_PRINT {
  24 + DB.AddQueryHook(SqlGeneratePrintHook{})
  25 + }
  26 + if !constant.DISABLE_CREATE_TABLE {
  27 + for _, model := range []interface{}{
  28 + //(*models.Employee)(nil),
  29 + (*models.PartnerInfo)(nil),
  30 + } {
  31 + err := DB.CreateTable(model, &orm.CreateTableOptions{
  32 + Temp: false,
  33 + IfNotExists: true,
  34 + FKConstraints: true,
  35 + })
  36 + if err != nil {
  37 + panic(err)
  38 + }
  39 + }
  40 + }
  41 +}
  42 +
  43 +type SqlGeneratePrintHook struct{}
  44 +
  45 +func (hook SqlGeneratePrintHook) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) {
  46 + return c, nil
  47 +}
  48 +
  49 +func (hook SqlGeneratePrintHook) AfterQuery(c context.Context, q *pg.QueryEvent) error {
  50 + data, err := q.FormattedQuery()
  51 + log.PrintSql(data)
  52 + return err
  53 +}
  1 +package models
  2 +
  3 +import (
  4 + "context"
  5 + "time"
  6 +
  7 + "github.com/go-pg/pg/v10"
  8 +)
  9 +
  10 +type AdminUser struct {
  11 + tableName struct{} `pg:"admin_user"`
  12 + //id
  13 + Id int64 `pg:",pk"`
  14 + //用户账号
  15 + AdminAccount string `pg:",unique"`
  16 + //用户名称
  17 + AdminName string
  18 + //账号密码
  19 + Password string
  20 + //是否是默认账号
  21 + IsDefault bool `pg:",use_zero"`
  22 + //账号是否可用
  23 + IsUsable bool `json:"is_userable"`
  24 +
  25 + CreateAt time.Time
  26 + UpdateAt time.Time
  27 +}
  28 +
  29 +var _ pg.BeforeUpdateHook = (*AdminUser)(nil)
  30 +
  31 +func (user *AdminUser) BeforeUpdate(ctx context.Context) (context.Context, error) {
  32 + user.UpdateAt = time.Now()
  33 + return ctx, nil
  34 +}
  35 +
  36 +var _ pg.BeforeInsertHook = (*AdminUser)(nil)
  37 +
  38 +func (user *AdminUser) BeforeInsert(ctx context.Context) (context.Context, error) {
  39 + user.CreateAt = time.Now()
  40 + user.UpdateAt = time.Now()
  41 + return ctx, nil
  42 +}
  1 +package models
  2 +
  3 +import (
  4 + "time"
  5 +
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  7 +)
  8 +
  9 +type PartnerInfo struct {
  10 + tableName struct{} `pg:"partner_infos,alias:partner_info"`
  11 + // 合伙人ID
  12 + Id int64 `pg:",pk"`
  13 + // 合伙人姓名
  14 + PartnerName string
  15 + // 登录账号
  16 + Account string
  17 + // 登录密码
  18 + Password string
  19 + // 状态(1:启用或者0:禁用)
  20 + Status int `pg:",notnull,default:1"`
  21 + // 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
  22 + PartnerCategory int `pg:",notnull,default:1"`
  23 +
  24 + //创建时间
  25 + CreateAt time.Time
  26 + //更新时间
  27 + UpdateAt time.Time
  28 +
  29 + //关联业务员
  30 + Salesman []*domain.Salesman
  31 +}
  1 +package transaction
  2 +
  3 +import "github.com/go-pg/pg/v10"
  4 +
  5 +type TransactionContext struct {
  6 + PgDd *pg.DB
  7 + PgTx *pg.Tx
  8 +}
  9 +
  10 +func (transactionContext *TransactionContext) StartTransaction() error {
  11 + tx, err := transactionContext.PgDd.Begin()
  12 + if err != nil {
  13 + return err
  14 + }
  15 + transactionContext.PgTx = tx
  16 + return nil
  17 +}
  18 +
  19 +func (transactionContext *TransactionContext) CommitTransaction() error {
  20 + err := transactionContext.PgTx.Commit()
  21 + return err
  22 +}
  23 +
  24 +func (transactionContext *TransactionContext) RollbackTransaction() error {
  25 + err := transactionContext.PgTx.Rollback()
  26 + return err
  27 +}
  28 +
  29 +func NewPGTransactionContext(pgDd *pg.DB) *TransactionContext {
  30 + return &TransactionContext{
  31 + PgDd: pgDd,
  32 + }
  33 +}
  1 +package repository
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
  7 +)
  8 +
  9 +type AdminUserRepository struct {
  10 + transactionContext *transaction.TransactionContext
  11 +}
  12 +
  13 +var (
  14 + _ domain.AdminUserRepository = (*AdminUserRepository)(nil)
  15 +)
  16 +
  17 +func NewAdminUserRepository(transactionContext *transaction.TransactionContext) (*AdminUserRepository, error) {
  18 + if transactionContext == nil {
  19 + return nil, ERR_EMPTY_TC
  20 + }
  21 + return &AdminUserRepository{transactionContext: transactionContext}, nil
  22 +}
  23 +func (reponsitory AdminUserRepository) transformPgModelToDomainModel(adminuserModel *models.AdminUser) (domain.AdminUser, error) {
  24 + result := domain.AdminUser{}
  25 + return result, nil
  26 +}
  27 +
  28 +func (reponsitory AdminUserRepository) FindOne(queryOption domain.AdminUserFindOneQuery) (*domain.AdminUser, error) {
  29 + db := reponsitory.transactionContext.PgDd
  30 + adminuserModel := new(models.AdminUser)
  31 + query := db.Model(adminuserModel)
  32 +
  33 + if queryOption.AdminUserId > 0 {
  34 + query = query.Where("id=?", queryOption.AdminUserId)
  35 + }
  36 + if len(queryOption.AccountEqual) > 0 {
  37 + query = query.Where("admin_account=?", queryOption.AccountEqual)
  38 + }
  39 + err := query.First()
  40 + if err != nil {
  41 + return nil, err
  42 + }
  43 + adminUser, err := reponsitory.transformPgModelToDomainModel(adminuserModel)
  44 + return &adminUser, err
  45 +}
  1 +package repository
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
  7 +)
  8 +
  9 +type PartnerInfoRepository struct {
  10 + transactionContext *transaction.TransactionContext
  11 +}
  12 +
  13 +func (repository *PartnerInfoRepository) Save(dm *domain.PartnerInfo) (*domain.PartnerInfo, error) {
  14 + var (
  15 + err error
  16 + m = &models.PartnerInfo{}
  17 + tx = repository.transactionContext.PgTx
  18 + )
  19 + if err = GobModelTransform(m, dm); err != nil {
  20 + return nil, err
  21 + }
  22 + if dm.Identify() == nil {
  23 + if dm.Id, err = NewSnowflakeId(); err != nil {
  24 + return dm, err
  25 + }
  26 + m.Id = dm.Id
  27 + if err = tx.Insert(m); err != nil {
  28 + return nil, err
  29 + }
  30 + return dm, nil
  31 + }
  32 + if err = tx.Update(m); err != nil {
  33 + return nil, err
  34 + }
  35 + return dm, nil
  36 +}
  37 +
  38 +func (repository *PartnerInfoRepository) Remove(PartnerInfo *domain.PartnerInfo) (*domain.PartnerInfo, error) {
  39 + var (
  40 + tx = repository.transactionContext.PgTx
  41 + PartnerInfoModel = &models.PartnerInfo{Id: PartnerInfo.Identify().(int64)}
  42 + )
  43 + if _, err := tx.Model(PartnerInfoModel).Where("id = ?", PartnerInfo.Id).Delete(); err != nil {
  44 + return PartnerInfo, err
  45 + }
  46 + return PartnerInfo, nil
  47 +}
  48 +
  49 +func (repository *PartnerInfoRepository) FindOne(queryOptions map[string]interface{}) (*domain.PartnerInfo, error) {
  50 + tx := repository.transactionContext.PgTx
  51 + PartnerInfoModel := new(models.PartnerInfo)
  52 + query := NewQuery(tx.Model(PartnerInfoModel), queryOptions)
  53 + query.SetWhere("partner_info.id = ?", "id")
  54 + if err := query.First(); err != nil {
  55 + return nil, query.HandleError(err, "没有此合伙人")
  56 + }
  57 + if PartnerInfoModel.Id == 0 {
  58 + return nil, nil
  59 + }
  60 + return repository.transformPgModelToDomainModel(PartnerInfoModel)
  61 +}
  62 +
  63 +func (repository *PartnerInfoRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.PartnerInfo, error) {
  64 + tx := repository.transactionContext.PgTx
  65 + var PartnerInfoModels []*models.PartnerInfo
  66 + PartnerInfos := make([]*domain.PartnerInfo, 0)
  67 + query := NewQuery(tx.Model(&PartnerInfoModels), queryOptions)
  68 + query.
  69 + SetWhere("partner_info.account = ?", "account").
  70 + SetWhere(`partner_info.status = ?`, "status").
  71 + SetWhere(`partner_info.partner_category = ?`, "partnerCategory").
  72 + SetLimit().
  73 + SetOrder("partner_info.create_at", "sortByCreateTime").
  74 + SetOrder("partner_info.update_at", "sortByUpdateTime")
  75 + var err error
  76 + if query.AffectRow, err = query.SelectAndCount(); err != nil {
  77 + return 0, PartnerInfos, err
  78 + }
  79 + for _, PartnerInfoModel := range PartnerInfoModels {
  80 + if PartnerInfo, err := repository.transformPgModelToDomainModel(PartnerInfoModel); err != nil {
  81 + return 0, PartnerInfos, err
  82 + } else {
  83 + PartnerInfos = append(PartnerInfos, PartnerInfo)
  84 + }
  85 + }
  86 + return int64(query.AffectRow), PartnerInfos, nil
  87 +}
  88 +
  89 +func (repository *PartnerInfoRepository) transformPgModelToDomainModel(PartnerInfoModel *models.PartnerInfo) (*domain.PartnerInfo, error) {
  90 + m := &domain.PartnerInfo{}
  91 + err := GobModelTransform(m, PartnerInfoModel)
  92 + return m, err
  93 +}
  94 +
  95 +func NewPartnerInfoRepository(transactionContext *transaction.TransactionContext) (*PartnerInfoRepository, error) {
  96 + if transactionContext == nil {
  97 + return nil, ERR_EMPTY_TC
  98 + }
  99 + return &PartnerInfoRepository{transactionContext: transactionContext}, nil
  100 +}
  1 +package repository
  2 +
  3 +import (
  4 + "bytes"
  5 + "encoding/gob"
  6 + "fmt"
  7 + "github.com/go-pg/pg/v10/orm"
  8 + "github.com/linmadan/egglib-go/utils/snowflake"
  9 +)
  10 +
  11 +var (
  12 + ERR_EMPTY_TC = fmt.Errorf("transactionContext参数不能为nil")
  13 +)
  14 +
  15 +type Query struct {
  16 + *orm.Query
  17 + queryOptions map[string]interface{}
  18 + AffectRow int
  19 +}
  20 +
  21 +func NewQuery(query *orm.Query, queryOptions map[string]interface{}) *Query {
  22 + return &Query{
  23 + query,
  24 + queryOptions,
  25 + 0,
  26 + }
  27 +}
  28 +
  29 +func (query *Query) SetWhere(condition, key string) *Query {
  30 + if v, ok := query.queryOptions[key]; ok {
  31 + query.Where(condition, v)
  32 + }
  33 + return query
  34 +}
  35 +
  36 +func (query *Query) SetLimit() *Query {
  37 + if offset, ok := query.queryOptions["offset"]; ok {
  38 + offset := offset.(int)
  39 + if offset > -1 {
  40 + query.Offset(offset)
  41 + }
  42 + } else {
  43 + query.Offset(0)
  44 + }
  45 + if limit, ok := query.queryOptions["limit"]; ok {
  46 + limit := limit.(int)
  47 + if limit > -1 {
  48 + query.Limit(limit)
  49 + } else {
  50 + query.Limit(20)
  51 + }
  52 + }
  53 + return query
  54 +}
  55 +
  56 +func (query *Query) SetOrder(orderColumn string, key string) *Query {
  57 + //query.Order(condition...)
  58 + //return query
  59 + if v, ok := query.queryOptions[key]; ok {
  60 + query.Order(fmt.Sprintf("%v %v", orderColumn, v))
  61 + }
  62 + return query
  63 +}
  64 +
  65 +func (query *Query) HandleError(err error, errMsg string) error {
  66 + if err.Error() == "pg: no rows in result set" {
  67 + return fmt.Errorf(errMsg)
  68 + } else {
  69 + return err
  70 + }
  71 +}
  72 +
  73 +func NewSnowflakeId() (int64, error) {
  74 + IdWorker, err := snowflake.NewIdWorker(2)
  75 + if err != nil {
  76 + return 0, err
  77 + }
  78 + id, err := IdWorker.NextId()
  79 + return id, err
  80 +}
  81 +
  82 +//GobModelTransform 模型转换
  83 +func GobModelTransform(dst interface{}, src interface{}) error {
  84 + var data bytes.Buffer
  85 + enc := gob.NewEncoder(&data)
  86 + if err := enc.Encode(src); err != nil {
  87 + return err
  88 + }
  89 + dec := gob.NewDecoder(&data)
  90 + if err := dec.Decode(dst); err != nil {
  91 + return err
  92 + }
  93 + return nil
  94 +}
  1 +package log
  2 +
  3 +import (
  4 + "github.com/astaxie/beego"
  5 + "github.com/astaxie/beego/logs"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant"
  7 +)
  8 +
  9 +func init() {
  10 + logs.SetLevel(logLevel(constant.LOG_LEVEL))
  11 + if beego.BConfig.RunMode == "prod" {
  12 + logs.SetLogFuncCall(false)
  13 + } else {
  14 + logs.SetLogFuncCallDepth(3)
  15 + }
  16 +
  17 + logs.SetLogger("file", `{"filename":"log/partnermg.log"}`)
  18 +}
  19 +
  20 +//LogLevel ...
  21 +func logLevel(s string) (i int) {
  22 + switch s {
  23 + case "info":
  24 + i = logs.LevelInfo
  25 + case "debug":
  26 + i = logs.LevelDebug
  27 + case "warning":
  28 + i = logs.LevelWarning
  29 + case "error":
  30 + i = logs.LevelError
  31 + default:
  32 + i = logs.LevelDebug
  33 + }
  34 + return
  35 +}
  36 +
  37 +func PrintSql(bt []byte) {
  38 + logs.Debug(string(bt))
  39 +}
  1 +package beego
  2 +
  3 +import (
  4 + "github.com/astaxie/beego"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/middleware"
  6 + _ "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/routers"
  7 +)
  8 +
  9 +func init() {
  10 + beego.InsertFilter("/*", beego.BeforeRouter, middleware.AllowCors())
  11 + // beego.InsertFilter("/*", beego.BeforeExec, filters.CreateRequestBodyFilter())
  12 + // beego.InsertFilter("/*", beego.BeforeExec, log.CreateRequstLogFilter(Logger))
  13 + // beego.InsertFilter("/*", beego.AfterExec, log.CreateResponseLogFilter(Logger), false)
  14 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "errors"
  5 +
  6 + "github.com/astaxie/beego/logs"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  8 +)
  9 +
  10 +type AdminUserController struct {
  11 + BaseController
  12 +}
  13 +
  14 +////Prepare 重写 BaseController 的Prepare方法
  15 +func (c *AdminUserController) Prepare() {
  16 + c.BaseController.Prepare()
  17 + if ok := c.ValidJWTToken(); !ok {
  18 + return
  19 + }
  20 + if ok := c.ValidAdminPermission(domain.PERMINSSION_ADMIN_USER); !ok {
  21 + return
  22 + }
  23 +}
  24 +
  25 +func (c *AdminUserController) Demo() {
  26 + //用与适配前端定义的数据结构
  27 + type Paramer struct {
  28 + }
  29 + var (
  30 + param Paramer
  31 + err error
  32 + )
  33 + if err = c.BindJsonData(&param); err != nil {
  34 + logs.Error(err)
  35 + c.ResponseError(errors.New("json数据解析失败"))
  36 + return
  37 + }
  38 + //Paramer转换为application要求的数据结构
  39 + //业务逻辑处理
  40 +
  41 + c.ResponseData(nil)
  42 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "errors"
  6 + "fmt"
  7 + "io/ioutil"
  8 + "strconv"
  9 +
  10 + "github.com/astaxie/beego"
  11 + "github.com/astaxie/beego/logs"
  12 + "github.com/prometheus/common/log"
  13 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/lib"
  14 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/protocol"
  15 +)
  16 +
  17 +type BaseController struct {
  18 + beego.Controller
  19 +}
  20 +
  21 +func (controller BaseController) BindJsonData(v interface{}) error {
  22 + bodyData := controller.Ctx.Input.GetData("requestBody")
  23 + bodyByte, ok := bodyData.([]byte)
  24 + if !ok {
  25 + return errors.New("requestBody is not []byte")
  26 + }
  27 + return json.Unmarshal(bodyByte, v)
  28 +}
  29 +
  30 +func (controller BaseController) ResponseError(err error) {
  31 + controller.Data["json"] = protocol.ResponseData{
  32 + Code: "-1",
  33 + Msg: err.Error(),
  34 + Data: struct{}{},
  35 + }
  36 + controller.ServeJSON()
  37 + logs.Error(err)
  38 +}
  39 +
  40 +func (controller BaseController) ResponseData(data interface{}) {
  41 + if data == nil {
  42 + data = struct{}{}
  43 + }
  44 + controller.Data["json"] = protocol.ResponseData{
  45 + Code: "0",
  46 + Msg: "ok",
  47 + Data: data,
  48 + }
  49 + controller.ServeJSON()
  50 +}
  51 +
  52 +//Finish 重写 beego.Controller 的Finish 方法
  53 +func (controller *BaseController) Finish() {
  54 + strByte, _ := json.Marshal(controller.Data["json"])
  55 + length := len(strByte)
  56 + if length > 1500 {
  57 + logs.Info("<====Send to client: RspBodyData: %s......", string(strByte[:1500]))
  58 + } else {
  59 + logs.Info("<====Send to client: RspBodyData: %s......", string(strByte))
  60 + }
  61 +}
  62 +
  63 +////Prepare 重写 beego.Controller 的Prepare方法
  64 +func (controller *BaseController) Prepare() {
  65 + log.Info("====>Recv Request:%s Method:%s", controller.Ctx.Input.URI(), controller.Ctx.Input.Method())
  66 + if controller.Ctx.Input.IsPost() || controller.Ctx.Input.IsPut() {
  67 + bodyByte, _ := ioutil.ReadAll(controller.Ctx.Request.Body)
  68 + controller.Ctx.Input.SetData("requestBody", bodyByte)
  69 + controller.Ctx.Request.Body.Close()
  70 + if len(bodyByte) > 1000 {
  71 + log.Info("====>Recv data from client: BodyData:\n %s ...", string(bodyByte[0:1000]))
  72 + } else {
  73 + log.Info("====>Recv data from client: BodyData: \n %s", string(bodyByte))
  74 + }
  75 + }
  76 + return
  77 +}
  78 +
  79 +func (controller *BaseController) GetHeaderToken() string {
  80 + return controller.Ctx.Input.Header("Authorization")
  81 +}
  82 +
  83 +func (controller *BaseController) GetUserId() int {
  84 + idV := controller.Ctx.Input.GetData("admin_user_id")
  85 + uid, _ := strconv.Atoi(fmt.Sprint(idV))
  86 + return uid
  87 +}
  88 +
  89 +func (controller *BaseController) setUserId(id int) {
  90 + controller.Ctx.Input.SetData("admin_user_id", id)
  91 +}
  92 +
  93 +func (controller *BaseController) ValidJWTToken() bool {
  94 + headerToken := controller.GetHeaderToken()
  95 + mytoken := lib.NewMyToken(0)
  96 + err := mytoken.ValidJWTToken(headerToken)
  97 + if err != nil {
  98 + if mytoken.IsJwtErrorExpired(err) {
  99 + //token超时
  100 + controller.Data["json"] = protocol.ResponseData{
  101 + Code: "2",
  102 + Msg: "token过期,请重新登录",
  103 + Data: struct{}{},
  104 + }
  105 + controller.ServeJSON()
  106 + } else {
  107 + controller.Data["json"] = protocol.ResponseData{
  108 + Code: "-1",
  109 + Msg: "token校验失败",
  110 + Data: struct{}{},
  111 + }
  112 + controller.ServeJSON()
  113 + }
  114 + return false
  115 + }
  116 + controller.setUserId(mytoken.UID)
  117 + return true
  118 +}
  119 +
  120 +func (controller *BaseController) ValidAdminPermission(code string, excludeURL ...string) bool {
  121 + //排除掉的请求
  122 + reqUrl := controller.Ctx.Input.URL()
  123 + for i := range excludeURL {
  124 + if reqUrl == excludeURL[i] {
  125 + return true
  126 + }
  127 + }
  128 + //权限校验
  129 + //
  130 + var err error
  131 + if err != nil {
  132 + controller.Data["json"] = protocol.ResponseData{
  133 + Code: "-1",
  134 + Msg: "没有操作权限",
  135 + Data: struct{}{},
  136 + }
  137 + controller.ServeJSON()
  138 + }
  139 + return true
  140 +}
  1 +package controllers
  2 +
  3 +type PartnerInfoController struct {
  4 + BaseController
  5 +}
  6 +
  7 +//CreatePartnerInfo 创建合伙人
  8 +func (controller *PartnerInfoController) CreatePartnerInfo() {
  9 + // var (
  10 + // service = service.NewPartnerInfoService(nil)
  11 + // command = &command.CreatePartnerInfoCommand{}
  12 + // )
  13 + // controller.JsonUnmarshal(command)
  14 + // controller.HandlerResponse(service.CreatePartnerInfo(command))
  15 +}
  16 +
  17 +//UpdatePartnerInfo 更新合伙人
  18 +func (controller *PartnerInfoController) UpdatePartnerInfo() {
  19 + // var (
  20 + // service = service.NewPartnerInfoService(nil)
  21 + // command = &command.UpdatePartnerInfoCommand{}
  22 + // )
  23 + // controller.JsonUnmarshal(command)
  24 + // id, _ := controller.GetInt(":id")
  25 + // command.Id = id
  26 + // controller.HandlerResponse(service.UpdatePartnerInfo(command))
  27 +}
  28 +
  29 +//GetPartnerInfo 获取合伙人
  30 +func (controller *PartnerInfoController) GetPartnerInfo() {
  31 + // var (
  32 + // service = service.NewPartnerInfoService(nil)
  33 + // command = &query.GetPartnerInfoQuery{}
  34 + // )
  35 + // uid, _ := controller.GetInt(":id")
  36 + // command.Id = uid
  37 + // controller.HandlerResponse(service.GetPartnerInfo(command))
  38 +}
  39 +
  40 +//GetPartnerInfo 移除合伙人
  41 +func (controller *PartnerInfoController) RemovePartnerInfo() {
  42 + // var (
  43 + // service = service.NewPartnerInfoService(nil)
  44 + // command = &command.RemovePartnerInfoCommand{}
  45 + // )
  46 + // uid, _ := controller.GetInt(":id")
  47 + // command.Id = uid
  48 + // controller.HandlerResponse(service.RemovePartnerInfo(command))
  49 +}
  50 +
  51 +//ListPartnerInfo 合伙人列表
  52 +func (controller *PartnerInfoController) ListPartnerInfo() {
  53 + // var (
  54 + // service = service.NewPartnerInfoService(nil)
  55 + // command = &query.ListPartnerInfoQuery{}
  56 + // )
  57 + // command.PartnerCategory, _ = controller.GetInt("partnerCategory")
  58 + // command.Status, _ = controller.GetInt("status")
  59 + // command.SortByCreateTime = controller.GetString("sortByCreateTime")
  60 + // command.SortByUpdateTime = controller.GetString("sortByUpdateTime")
  61 + // command.Offset, command.Limit = controller.GetLimitInfo()
  62 + // controller.HandlerResponse(service.ListPartnerInfo(command))
  63 +}
  1 +package lib
  2 +
  3 +import (
  4 + "fmt"
  5 + "time"
  6 +
  7 + "github.com/dgrijalva/jwt-go"
  8 +)
  9 +
  10 +var (
  11 + key []byte = []byte("sx87sda0w7x7sd")
  12 +)
  13 +
  14 +//MyToken ...
  15 +type MyToken struct {
  16 + jwt.StandardClaims
  17 + UID int `json:"uid"` //管理员的id
  18 +}
  19 +
  20 +func NewMyToken(id int) *MyToken {
  21 + return &MyToken{UID: id}
  22 +}
  23 +
  24 +//CreateJWTToken ...
  25 +func (mytoken *MyToken) CreateJWTToken() (string, error) {
  26 + nowTime := time.Now().Unix()
  27 + mytoken.StandardClaims = jwt.StandardClaims{
  28 + NotBefore: nowTime,
  29 + IssuedAt: nowTime,
  30 + ExpiresAt: 60 * 60 * 3,
  31 + Issuer: "mmm_partnermg",
  32 + }
  33 +
  34 + token := jwt.NewWithClaims(jwt.SigningMethodHS256, mytoken)
  35 + return token.SignedString(key)
  36 +}
  37 +
  38 +//ValidJWTToken ...
  39 +func (mytoken *MyToken) ValidJWTToken(tokenString string) error {
  40 + token, err := jwt.ParseWithClaims(
  41 + tokenString,
  42 + &MyToken{},
  43 + func(token *jwt.Token) (interface{}, error) {
  44 + return key, nil
  45 + })
  46 + if err != nil {
  47 + return err
  48 + }
  49 + mytoken, ok := token.Claims.(*MyToken)
  50 + if ok && token.Valid {
  51 + // 验证成功,返回信息
  52 + return nil
  53 + }
  54 + // 验证失败
  55 + return fmt.Errorf("token Valid fail")
  56 +}
  57 +
  58 +func (mytoken *MyToken) IsJwtErrorExpired(err error) bool {
  59 + ve, ok := err.(*jwt.ValidationError)
  60 + if ok && ve.Errors == jwt.ValidationErrorExpired {
  61 + return true
  62 + }
  63 + return false
  64 +}
  1 +package middleware
  2 +
  3 +import (
  4 + "github.com/astaxie/beego/context"
  5 + "github.com/astaxie/beego/plugins/cors"
  6 +)
  7 +
  8 +func AllowCors() func(ctx *context.Context) {
  9 + fn := cors.Allow(&cors.Options{
  10 + //允许访问所有源
  11 + AllowAllOrigins: true,
  12 + //可选参数"GET", "POST", "PUT", "DELETE", "OPTIONS" (*为所有)
  13 + //其中Options跨域复杂请求预检
  14 + AllowMethods: []string{"*"},
  15 + //指的是允许的Header的种类
  16 + AllowHeaders: []string{"*"},
  17 + //公开的HTTP标头列表
  18 + ExposeHeaders: []string{"Content-Length"},
  19 + //如果设置,则允许共享身份验证凭据,例如cookie
  20 + AllowCredentials: true,
  21 + })
  22 + return fn
  23 +}
  1 +package middleware
  2 +
  3 +import (
  4 + "github.com/astaxie/beego/context"
  5 +)
  6 +
  7 +//PermissionCheck 根据权限编码检验请求是否可以执行
  8 +//permissionCode:权限编码
  9 +//excludeURL:跳过url
  10 +func AdminPermissionCheck(permissionCode string, excludeURL ...string) func(ctx *context.Context) {
  11 +
  12 + return func(ctx *context.Context) {
  13 + //根据code检查权限数据,并排除excludeUrl指定的url
  14 + //获取user 数据
  15 + }
  16 +}
  1 +package protocol
  2 +
  3 +type ResponseData struct {
  4 + Code string `json:"code"`
  5 + Msg string `json:"msg"`
  6 + Data interface{} `json:"data"`
  7 +}
  1 +package routers
  2 +
  3 +import (
  4 + "github.com/astaxie/beego"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/controllers"
  6 +)
  7 +
  8 +func init() {
  9 + adminRouter := beego.NewNamespace("/admin_user",
  10 + // 其余的路由
  11 + beego.NSRouter("/get", &controllers.AdminUserController{}, "POST:Demo"),
  12 + )
  13 + //...
  14 +
  15 + beego.AddNamespace(adminRouter)
  16 +}
  1 +package routers
  2 +
  3 +import (
  4 + "github.com/astaxie/beego"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/controllers"
  6 +)
  7 +
  8 +func init() {
  9 + beego.Router("/partnerInfos/", &controllers.PartnerInfoController{}, "Post:CreatePartnerInfo")
  10 + beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Put:UpdatePartnerInfo")
  11 + beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Get:GetPartnerInfo")
  12 + beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Delete:RemovePartnerInfo")
  13 + beego.Router("/partnerInfos/", &controllers.PartnerInfoController{}, "Get:ListPartnerInfo")
  14 +}
  1 +package routers
  2 +
  3 +import (
  4 + "github.com/astaxie/beego"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant"
  6 +)
  7 +
  8 +func init() {
  9 + beego.SetStaticPath("/log", constant.LOG_File)
  10 +}
  1 +package partnerInfo
  2 +
  3 +import (
  4 + "github.com/gavv/httpexpect"
  5 + . "github.com/onsi/ginkgo"
  6 + . "github.com/onsi/gomega"
  7 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  8 + "net/http"
  9 +)
  10 +
  11 +var _ = Describe("创建新合伙人", func() {
  12 + Describe("创建新合伙人", func() {
  13 + Context("创建新合伙人", func() {
  14 + It("返回合伙人数据", func() {
  15 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  16 + body := map[string]interface{}{
  17 + "partnerName": "employeeName",
  18 + "account": "account123",
  19 + "password": "password",
  20 + "status": 1,
  21 + "partnerCategory": 1,
  22 + //"createAt":time.Now(),
  23 + //"updateAt":time.Now(),
  24 + "salesman": []map[string]interface{}{
  25 + {"name": "name", "telephone": "18860183051"},
  26 + {"name2": "name", "telephone": "18860183052j"},
  27 + },
  28 + }
  29 + httpExpect.POST("/partnerInfos").
  30 + WithJSON(body).
  31 + Expect().
  32 + Status(http.StatusOK).
  33 + JSON().
  34 + Object().
  35 + ContainsKey("code").ValueEqual("code", 0).
  36 + ContainsKey("msg").ValueEqual("msg", "ok").
  37 + ContainsKey("data").Value("data").Object().
  38 + ContainsKey("id").ValueNotEqual("id", BeZero())
  39 + })
  40 + })
  41 + })
  42 + AfterEach(func() {
  43 + _, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
  44 + Expect(err).NotTo(HaveOccurred())
  45 + })
  46 +})
  1 +package partnerInfo
  2 +
  3 +import (
  4 + "github.com/gavv/httpexpect"
  5 + . "github.com/onsi/ginkgo"
  6 + . "github.com/onsi/gomega"
  7 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  8 + "net/http"
  9 +)
  10 +
  11 +var _ = Describe("删除合伙人", func() {
  12 + BeforeEach(func() {
  13 + _, 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"}]');`)
  14 + Expect(err).NotTo(HaveOccurred())
  15 + })
  16 + Describe("删除合伙人", func() {
  17 + Context("删除合伙人", func() {
  18 + It("删除合伙人数据", func() {
  19 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  20 + body := map[string]interface{}{}
  21 + httpExpect.DELETE("/partnerInfos/2929531956394199040").
  22 + WithJSON(body).
  23 + Expect().
  24 + Status(http.StatusOK).
  25 + JSON().
  26 + Object().
  27 + ContainsKey("code").ValueEqual("code", 0).
  28 + ContainsKey("msg").ValueEqual("msg", "ok").
  29 + ContainsKey("data").Value("data").Object().
  30 + ContainsKey("id").ValueNotEqual("id", BeZero())
  31 + })
  32 + })
  33 + })
  34 + AfterEach(func() {
  35 + _, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
  36 + Expect(err).NotTo(HaveOccurred())
  37 + })
  38 +})
  1 +package partnerInfo
  2 +
  3 +import (
  4 + "github.com/gavv/httpexpect"
  5 + . "github.com/onsi/ginkgo"
  6 + . "github.com/onsi/gomega"
  7 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  8 + "net/http"
  9 +)
  10 +
  11 +var _ = Describe("获取合伙人", func() {
  12 + BeforeEach(func() {
  13 + _, 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"}]');`)
  14 + Expect(err).NotTo(HaveOccurred())
  15 + })
  16 + Describe("获取合伙人", func() {
  17 + Context("获取合伙人", func() {
  18 + It("返回合伙人数据", func() {
  19 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  20 + body := map[string]interface{}{}
  21 + httpExpect.GET("/partnerInfos/2929531956394199040").
  22 + WithJSON(body).
  23 + Expect().
  24 + Status(http.StatusOK).
  25 + JSON().
  26 + Object().
  27 + ContainsKey("code").ValueEqual("code", 0).
  28 + ContainsKey("msg").ValueEqual("msg", "ok").
  29 + ContainsKey("data").Value("data").Object().
  30 + ContainsKey("id").ValueNotEqual("id", BeZero())
  31 + })
  32 + })
  33 + })
  34 + AfterEach(func() {
  35 + _, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
  36 + Expect(err).NotTo(HaveOccurred())
  37 + })
  38 +})
  1 +package partnerInfo
  2 +
  3 +import (
  4 + "github.com/gavv/httpexpect"
  5 + . "github.com/onsi/ginkgo"
  6 + . "github.com/onsi/gomega"
  7 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  8 + "net/http"
  9 +)
  10 +
  11 +var _ = Describe("获取合伙人列表", func() {
  12 + BeforeEach(func() {
  13 + _, 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"}]');`)
  14 + Expect(err).NotTo(HaveOccurred())
  15 + })
  16 + Describe("获取合伙人列表", func() {
  17 + Context("获取合伙人列表", func() {
  18 + It("获取合伙人列表", func() {
  19 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  20 + body := map[string]interface{}{}
  21 + httpExpect.GET("/partnerInfos").
  22 + WithQuery("partnerCategory", 1).
  23 + WithQuery("status", 1).
  24 + WithQuery("status", 1).
  25 + WithQuery("sortByCreateTime", "DESC").
  26 + WithQuery("sortByUpdateTime", "DESC").
  27 + WithQuery("offset", 0).
  28 + WithQuery("limit", 20).
  29 + WithJSON(body).
  30 + Expect().
  31 + Status(http.StatusOK).
  32 + JSON().
  33 + Object().
  34 + ContainsKey("code").ValueEqual("code", 0).
  35 + ContainsKey("msg").ValueEqual("msg", "ok").
  36 + ContainsKey("data").Value("data").Object().ContainsKey("partnerInfos")
  37 + })
  38 + })
  39 + })
  40 + AfterEach(func() {
  41 + _, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
  42 + Expect(err).NotTo(HaveOccurred())
  43 + })
  44 +})
  1 +package partnerInfo
  2 +
  3 +import (
  4 + "github.com/astaxie/beego"
  5 + . "github.com/onsi/ginkgo"
  6 + . "github.com/onsi/gomega"
  7 + "net/http"
  8 + "net/http/httptest"
  9 + "testing"
  10 +
  11 + _ "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  12 + _ "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego"
  13 +)
  14 +
  15 +func TestPartnerInfo(t *testing.T) {
  16 + RegisterFailHandler(Fail)
  17 + RunSpecs(t, "Beego Port Employee Correlations Test Case Suite")
  18 +}
  19 +
  20 +var handler http.Handler
  21 +var server *httptest.Server
  22 +
  23 +var _ = BeforeSuite(func() {
  24 + handler = beego.BeeApp.Handlers
  25 + server = httptest.NewServer(handler)
  26 +})
  27 +
  28 +var _ = AfterSuite(func() {
  29 + server.Close()
  30 +})
  1 +package partnerInfo
  2 +
  3 +import (
  4 + "github.com/gavv/httpexpect"
  5 + . "github.com/onsi/ginkgo"
  6 + . "github.com/onsi/gomega"
  7 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  8 + "net/http"
  9 +)
  10 +
  11 +var _ = Describe("创建新合伙人", func() {
  12 + BeforeEach(func() {
  13 + _, 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"}]');`)
  14 + Expect(err).NotTo(HaveOccurred())
  15 + })
  16 + Describe("创建新合伙人", func() {
  17 + Context("创建新合伙人", func() {
  18 + It("返回合伙人数据", func() {
  19 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  20 + body := map[string]interface{}{
  21 + "partnerName": "employeeName",
  22 + "account": "account123",
  23 + "password": "password",
  24 + "status": 1,
  25 + "partnerCategory": 1,
  26 + "salesman": []map[string]interface{}{
  27 + {"name": "name", "telephone": "18860183051"},
  28 + {"name2": "name", "telephone": "18860183052j"},
  29 + },
  30 + }
  31 + httpExpect.PUT("/partnerInfos/2929531956394199040").
  32 + WithJSON(body).
  33 + Expect().
  34 + Status(http.StatusOK).
  35 + JSON().
  36 + Object().
  37 + ContainsKey("code").ValueEqual("code", 0).
  38 + ContainsKey("msg").ValueEqual("msg", "ok").
  39 + ContainsKey("data").Value("data").Object().
  40 + ContainsKey("id").ValueNotEqual("id", BeZero())
  41 + })
  42 + })
  43 + })
  44 + AfterEach(func() {
  45 + _, err := pG.DB.Exec("DELETE FROM partner_infos WHERE true")
  46 + Expect(err).NotTo(HaveOccurred())
  47 + })
  48 +})