作者 唐旭辉

Merge branch 'dev' of http://gitlab.fjmaimaimai.com/mmm-go/partnermg into dev

正在显示 76 个修改的文件 包含 3549 行增加201 行删除

要显示太多修改。

为保证性能只显示 76 of 76+ 个文件。

1 -# 服务端工作交接事项  
2 -## 合伙人管理后台项目 1 +# 合伙人管理后台项目
3 2
4 -### 代码以及文档 3 +## 代码以及文档
5 - [代码地址](http://gitlab.fjmaimaimai.com/mmm-go/partnermg.git) 4 - [代码地址](http://gitlab.fjmaimaimai.com/mmm-go/partnermg.git)
6 - [项目原型svn](svn://218.106.157.184/repo/项目文件/项目【合伙人】) 5 - [项目原型svn](svn://218.106.157.184/repo/项目文件/项目【合伙人】)
7 - [yapi-合伙人前端](http://47.97.5.102:36666/project/209/interface/api) 6 - [yapi-合伙人前端](http://47.97.5.102:36666/project/209/interface/api)
@@ -15,7 +14,10 @@ @@ -15,7 +14,10 @@
15 服务端测试环境地址:http://mmm-partnermg-test.fjmaimaimai.com 14 服务端测试环境地址:http://mmm-partnermg-test.fjmaimaimai.com
16 服务端正式环境地址:https://public-interface.fjmaimaimai.com/mmm-partnermg 15 服务端正式环境地址:https://public-interface.fjmaimaimai.com/mmm-partnermg
17 ``` 16 ```
18 -### 项目整体 17 +## 系统架构图
  18 +![diagram](http://gitlab.fjmaimaimai.com/chenzhiying/img-folder/raw/master/diagram.png)
  19 +
  20 +## 项目整体
19 - 项目使用框架 21 - 项目使用框架
20 - http框架:beego 22 - http框架:beego
21 - orm框架:go-pg 23 - orm框架:go-pg
@@ -57,7 +59,56 @@ @@ -57,7 +59,56 @@
57 │ └─consumer kafka消息订阅 59 │ └─consumer kafka消息订阅
58 └─vendor 60 └─vendor
59 ``` 61 ```
60 -### 系统对接的外部数据 62 +
  63 +## 领域驱动设计-战略建模
  64 +### 领域
  65 +
  66 +### 限界上下文
  67 +
  68 +### 上下文映射
  69 +
  70 +## 领域驱动设计-战术建模
  71 +### 实体
  72 +实发订单实体:OrderBase
  73 +
  74 +栏目设置实体:ColumnSetting
  75 +
  76 +合伙人实体:Partner
  77 +
  78 +用户实体:User
  79 +
  80 +公司实体:Company
  81 +
  82 +管理员实体:AdminUser
  83 +
  84 +### 值对象
  85 +
  86 +
  87 +### 聚合根
  88 +
  89 +### 领域服务
  90 +
  91 +### 领域事件
  92 +
  93 +## 领域驱动设计工程实现
  94 +### 模块
  95 +
  96 +### 领域对象
  97 +
  98 +### 资源库
  99 +
  100 +### 防腐层
  101 +
  102 +### 领域服务
  103 +
  104 +### 数据流转
  105 +![avatar](http://gitlab.fjmaimaimai.com/chenzhiying/img-folder/raw/master/dto.png)
  106 +### 上下文集成
  107 +
  108 +### 分离领域
  109 +![avatar](http://gitlab.fjmaimaimai.com/chenzhiying/img-folder/raw/master/dispatch.png)
  110 +
  111 +## 系统对接的外部数据
61 112
62 1. 外部数据来源,接收企业平台发送过来的数据。目前接收的是公司和员工的数据 113 1. 外部数据来源,接收企业平台发送过来的数据。目前接收的是公司和员工的数据
63 主要内容在文件夹 114 主要内容在文件夹
@@ -78,11 +129,43 @@ @@ -78,11 +129,43 @@
78 主要内容在 129 主要内容在
79 partnermg/pkg/infrastructure/serviceGateway 130 partnermg/pkg/infrastructure/serviceGateway
80 131
81 -### 系统入口 132 +## 系统入口
82 - [测试环境--企业平台网站地址](https://enterprise-platform-dev.fjmaimaimai.com) 133 - [测试环境--企业平台网站地址](https://enterprise-platform-dev.fjmaimaimai.com)
83 - [开发环境--企业平台网站地址](https://enterprise-platform-local.fjmaimaimai.com) 134 - [开发环境--企业平台网站地址](https://enterprise-platform-local.fjmaimaimai.com)
84 - 天联共创后台自身没有独立的登录入口,需要经过企业平台进行跳转登录 135 - 天联共创后台自身没有独立的登录入口,需要经过企业平台进行跳转登录
85 136
  137 +## 标准产品组工具使用
  138 +- 设置全局变量(替换YOUR-USER-PATH为你真实的项目路径)
  139 +
  140 + 1.生成路径(项目生成路径):/YOUR-USER-PATH/GolandProjects/
  141 +
  142 + 2.eggs根目录路径(领域描述语言DSL文档路径生成或引用路径):/YOUR-USER-PATH/GolandProjects/partnermg/document/
  143 +
  144 + 3.egg名称(通常为项目名称,同样是DSL文件夹名称):partnermg
  145 +
  146 +- 应用描述语言生成
  147 +
  148 + 1.应用描述语言egg脚手架生成
  149 +
  150 + 2.生成属性(Attribute)
  151 +
  152 + 3.生成模式(Schema)
  153 +
  154 + 4.生成服务(Service)
  155 +
  156 + 5.生成接口(Api)
  157 +
  158 +- 具体工程生成
  159 +
  160 + 1.生成接口文档(OpenApi)
  161 +
  162 + 2.生成项目代码脚手架
  163 +
  164 + 3.生成领域模型
  165 +
  166 + 4.生成应用服务
  167 +
  168 + 5.生成Http协议接口
86 169
87 ## 建议 170 ## 建议
88 1. vendor 目前作用是存放依赖,加快在容器中的构建速度。 171 1. vendor 目前作用是存放依赖,加快在容器中的构建速度。
@@ -52,10 +52,12 @@ spec: @@ -52,10 +52,12 @@ spec:
52 ports: 52 ports:
53 - containerPort: 8082 53 - containerPort: 8082
54 - containerPort: 443 54 - containerPort: 443
55 - volumeMounts:  
56 - - mountPath: /opt/logs  
57 - name: accesslogs 55 +# volumeMounts:
  56 +# - mountPath: /opt/logs
  57 +# name: accesslogs
58 env: 58 env:
  59 + - name: HTTP_PORT
  60 + value: "8082"
59 - name: POSTGRESQL_DB_NAME 61 - name: POSTGRESQL_DB_NAME
60 value: "partner_dev" 62 value: "partner_dev"
61 - name: POSTGRESQL_USER 63 - name: POSTGRESQL_USER
@@ -92,6 +94,6 @@ spec: @@ -92,6 +94,6 @@ spec:
92 value: "[partnermg_dev]" 94 value: "[partnermg_dev]"
93 - name: APP_NAME 95 - name: APP_NAME
94 value: "" 96 value: ""
95 - volumes:  
96 - - name: accesslogs  
97 - emptyDir: {} 97 +# volumes:
  98 +# - name: accesslogs
  99 +# emptyDir: {}
@@ -53,6 +53,8 @@ spec: @@ -53,6 +53,8 @@ spec:
53 - mountPath: /opt/logs 53 - mountPath: /opt/logs
54 name: accesslogs 54 name: accesslogs
55 env: 55 env:
  56 + - name: HTTP_PORT
  57 + value: "8082"
56 - name: POSTGRESQL_DB_NAME 58 - name: POSTGRESQL_DB_NAME
57 value: "partner" 59 value: "partner"
58 - name: POSTGRESQL_USER 60 - name: POSTGRESQL_USER
@@ -49,10 +49,12 @@ spec: @@ -49,10 +49,12 @@ spec:
49 ports: 49 ports:
50 - containerPort: 8082 50 - containerPort: 8082
51 - containerPort: 443 51 - containerPort: 443
52 - volumeMounts:  
53 - - mountPath: /opt/logs  
54 - name: accesslogs 52 +# volumeMounts:
  53 +# - mountPath: /opt/logs
  54 +# name: accesslogs
55 env: 55 env:
  56 + - name: HTTP_PORT
  57 + value: "8082"
56 - name: POSTGRESQL_DB_NAME 58 - name: POSTGRESQL_DB_NAME
57 value: "partner_test" 59 value: "partner_test"
58 - name: POSTGRESQL_USER 60 - name: POSTGRESQL_USER
@@ -89,6 +91,6 @@ spec: @@ -89,6 +91,6 @@ spec:
89 value: "[partnermg_test]" 91 value: "[partnermg_test]"
90 - name: APP_NAME 92 - name: APP_NAME
91 value: "partnermg" 93 value: "partnermg"
92 - volumes:  
93 - - name: accesslogs  
94 - emptyDir: {} 94 +# volumes:
  95 +# - name: accesslogs
  96 +# emptyDir: {}
  1 +swagger: "2.0"
  2 +info:
  3 + title: ""
  4 + description: 合伙人后管平台
  5 + contact:
  6 + name: SteveChan
  7 + email: steve.d.chan@qq.com
  8 + home: ""
  9 + version: 0.0.1
  10 +consumes:
  11 +- application/json
  12 +- application/xml
  13 +produces:
  14 +- application/json
  15 +- application/xml
  16 +paths:
  17 + /column-settings:
  18 + get:
  19 + tags:
  20 + - column_setting
  21 + summary: 返回栏目设置增删改查列表
  22 + description: 返回栏目设置增删改查列表
  23 + operationId: column_setting#listColumnSetting
  24 + parameters:
  25 + - name: offset
  26 + in: query
  27 + description: 查询偏离量
  28 + required: false
  29 + type: integer
  30 + - name: limit
  31 + in: query
  32 + description: 查询限制
  33 + required: false
  34 + type: integer
  35 + responses:
  36 + "200":
  37 + description: OK response.
  38 + schema:
  39 + $ref: '#/definitions/ColumnSettingListColumnSettingResponseBody'
  40 + schemes:
  41 + - http
  42 + post:
  43 + tags:
  44 + - column_setting
  45 + summary: 重置栏目设置
  46 + description: 重置栏目设置
  47 + operationId: column_setting#resetColumn
  48 + responses:
  49 + "200":
  50 + description: OK response.
  51 + schema:
  52 + $ref: '#/definitions/ColumnSettingResetColumnResponseBody'
  53 + schemes:
  54 + - http
  55 + /column-settings/{columnSettingId}:
  56 + get:
  57 + tags:
  58 + - column_setting
  59 + summary: 返回栏目设置增删改查
  60 + description: 返回栏目设置增删改查
  61 + operationId: column_setting#getColumnSetting
  62 + parameters:
  63 + - name: columnSettingId
  64 + in: path
  65 + description: 栏目设置id
  66 + required: true
  67 + type: integer
  68 + responses:
  69 + "200":
  70 + description: OK response.
  71 + schema:
  72 + $ref: '#/definitions/ColumnSettingGetColumnSettingResponseBody'
  73 + schemes:
  74 + - http
  75 + put:
  76 + tags:
  77 + - column_setting
  78 + summary: 更新栏目设置增删改查
  79 + description: 更新栏目设置增删改查
  80 + operationId: column_setting#updateColumnSetting
  81 + parameters:
  82 + - name: columnSettingId
  83 + in: path
  84 + description: 栏目设置id
  85 + required: true
  86 + type: integer
  87 + responses:
  88 + "200":
  89 + description: OK response.
  90 + schema:
  91 + $ref: '#/definitions/ColumnSettingUpdateColumnSettingResponseBody'
  92 + schemes:
  93 + - http
  94 + delete:
  95 + tags:
  96 + - column_setting
  97 + summary: 移除栏目设置增删改查
  98 + description: 移除栏目设置增删改查
  99 + operationId: column_setting#removeColumnSetting
  100 + parameters:
  101 + - name: columnSettingId
  102 + in: path
  103 + description: 栏目设置id
  104 + required: true
  105 + type: integer
  106 + responses:
  107 + "200":
  108 + description: OK response.
  109 + schema:
  110 + $ref: '#/definitions/ColumnSettingRemoveColumnSettingResponseBody'
  111 + schemes:
  112 + - http
  113 +definitions:
  114 + ColumnSettingCreateColumnSettingRequestBody:
  115 + title: ColumnSettingCreateColumnSettingRequestBody
  116 + type: object
  117 + properties:
  118 + description:
  119 + type: string
  120 + description: 栏目设置描述
  121 + required:
  122 + - description
  123 + userName:
  124 + type: string
  125 + description: 栏目设置关联用户名称
  126 + required:
  127 + - userName
  128 + ColumnSettingCreateColumnSettingResponseBody:
  129 + title: 'Mediatype identifier: ColumnSettingCreateColumnSettingResponseBody'
  130 + type: object
  131 + properties:
  132 + column_setting:
  133 + $ref: '#/definitions/column_settingResponseBody'
  134 + ColumnSettingGetColumnSettingResponseBody:
  135 + title: 'Mediatype identifier: ColumnSettingGetColumnSettingResponseBody'
  136 + type: object
  137 + properties:
  138 + column_setting:
  139 + $ref: '#/definitions/column_settingResponseBody'
  140 + ColumnSettingListColumnSettingResponseBody:
  141 + title: 'Mediatype identifier: ColumnSettingListColumnSettingResponseBody'
  142 + type: object
  143 + properties:
  144 + column_setting:
  145 + $ref: '#/definitions/column_settingResponseBody'
  146 + count:
  147 + type: integer
  148 + description: 匹配数目
  149 + required:
  150 + - count
  151 + ColumnSettingRemoveColumnSettingResponseBody:
  152 + title: 'Mediatype identifier: ColumnSettingRemoveColumnSettingResponseBody'
  153 + type: object
  154 + properties:
  155 + column_setting:
  156 + $ref: '#/definitions/column_settingResponseBody'
  157 + ColumnSettingResetColumnResponseBody:
  158 + title: 'Mediatype identifier: ColumnSettingResetColumnResponseBody'
  159 + type: object
  160 + properties:
  161 + column_setting:
  162 + $ref: '#/definitions/column_settingResponseBody'
  163 + ColumnSettingUpdateColumnSettingResponseBody:
  164 + title: 'Mediatype identifier: ColumnSettingUpdateColumnSettingResponseBody'
  165 + type: object
  166 + properties:
  167 + column_setting:
  168 + $ref: '#/definitions/column_settingResponseBody'
  169 + column_settingResponseBody:
  170 + title: column_settingResponseBody
  171 + type: object
  172 + properties:
  173 + columnSettingId:
  174 + type: integer
  175 + description: 栏目设置id
  176 + required:
  177 + - columnSettingId
  178 + companyId:
  179 + type: integer
  180 + description: 栏目设置关联用户公司id
  181 + required:
  182 + - companyId
  183 + createdAt:
  184 + type: string
  185 + description: 栏目设置创建时间
  186 + required:
  187 + - createdAt
  188 + description:
  189 + type: string
  190 + description: 栏目设置描述
  191 + required:
  192 + - description
  193 + key:
  194 + type: string
  195 + description: 栏目设置模块名称
  196 + required:
  197 + - key
  198 + uid:
  199 + type: integer
  200 + description: 栏目设置关联用户uid
  201 + required:
  202 + - uid
  203 + updatedAt:
  204 + type: string
  205 + description: 栏目设置更新时间
  206 + required:
  207 + - updatedAt
  208 + userName:
  209 + type: string
  210 + description: 栏目设置关联用户名称
  211 + required:
  212 + - userName
  213 + value:
  214 + type: array
  215 + items:
  216 + $ref: '#/definitions/columnResponseBody'
  217 + description: 栏目数组
  218 + description: 栏目设置
  219 + columnResponseBody:
  220 + title: columnResponseBody
  221 + type: object
  222 + properties:
  223 + columnId:
  224 + type: string
  225 + description: 列标记
  226 + required:
  227 + - columnId
  228 + paramCn:
  229 + type: string
  230 + description: 列标记中文
  231 + required:
  232 + - paramCn
  233 + paramFix:
  234 + type: integer
  235 + description: 列标记是否固定,1:固定,2:不固定
  236 + required:
  237 + - paramFix
  238 + description: 栏目项
  1 +version: v1
  2 +kind: HttpApi
  3 +metadata:
  4 + service: column_setting
  5 + path: /column-settings
  6 + endpoints:
  7 + - method: createColumnSetting
  8 + route:
  9 + post: /
  10 + - method: updateColumnSetting
  11 + route:
  12 + put: /{columnSettingId}
  13 + - method: getColumnSetting
  14 + route:
  15 + get: /{columnSettingId}
  16 + - method: removeColumnSetting
  17 + route:
  18 + delete: /{columnSettingId}
  19 + - method: resetColumn
  20 + route:
  21 + post: /
  22 + - method: listColumnSetting
  23 + route:
  24 + get: /
  25 + params:
  26 + - name: offset
  27 + - name: limit
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: columnId
  5 + description: 列标记
  6 + type:
  7 + primitive: string
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: paramCn
  5 + description: 列标记中文
  6 + type:
  7 + primitive: string
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: paramFix
  5 + description: 列标记是否固定,1:固定,2:不固定
  6 + type:
  7 + primitive: int
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: columnSettingId
  5 + description: 栏目设置id
  6 + type:
  7 + primitive: int64
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: companyId
  5 + description: 栏目设置关联用户公司id
  6 + type:
  7 + primitive: int32
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: createdAt
  5 + description: 栏目设置创建时间
  6 + type:
  7 + primitive: datetime
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: description
  5 + description: 栏目设置描述
  6 + type:
  7 + primitive: string
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: invalidValue
  5 + description: 无效的栏目数组
  6 + type:
  7 + array: column
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: key
  5 + description: 栏目设置模块名称
  6 + type:
  7 + primitive: string
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: uid
  5 + description: 栏目设置关联用户uid
  6 + type:
  7 + primitive: int64
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: updatedAt
  5 + description: 栏目设置更新时间
  6 + type:
  7 + primitive: datetime
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: userName
  5 + description: 栏目设置关联用户名称
  6 + type:
  7 + primitive: string
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: value
  5 + description: 栏目值对象数组
  6 + type:
  7 + array: column
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: count
  5 + description: 匹配数目
  6 + type:
  7 + primitive: int64
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: limit
  5 + description: 查询限制
  6 + type:
  7 + primitive: int
  1 +version: v1
  2 +kind: Attribute
  3 +metadata:
  4 + name: offset
  5 + description: 查询偏离量
  6 + type:
  7 + primitive: int
  1 +version: v1
  2 +kind: Project
  3 +metadata:
  4 + name: project
  5 + description: 合伙人后管平台
  6 + version: 0.0.1
  7 + repository: gitlab.fjmaimaimai.com/mmm-go/partnermg
  8 + contact:
  9 + name: SteveChan
  10 + email: steve.d.chan@qq.com
  1 +version: v1
  2 +kind: Schema
  3 +metadata:
  4 + name: column
  5 + description: 栏目项
  6 + attributes:
  7 + - ref: columnId
  8 + required: true
  9 + - ref: paramCn
  10 + required: true
  11 + - ref: paramFix
  12 + required: true
  1 +version: v1
  2 +kind: Schema
  3 +metadata:
  4 + name: column_setting
  5 + description: 栏目设置
  6 + attributes:
  7 + - ref: columnSettingId
  8 + required: true
  9 + - ref: companyId
  10 + required: true
  11 + - ref: createdAt
  12 + required: true
  13 + - ref: description
  14 + required: true
  15 + - ref: key
  16 + required: true
  17 + - ref: uid
  18 + required: true
  19 + - ref: updatedAt
  20 + required: true
  21 + - ref: userName
  22 + required: true
  23 + - name: value
  24 + description: 栏目数组
  25 + type:
  26 + array: column
  27 + - name: invalidValue
  28 + description: 无效栏目数组
  29 + type:
  30 + array: column
  1 +version: v1
  2 +kind: Method
  3 +metadata:
  4 + name: createColumnSetting
  5 + type: command
  6 + description: 创建栏目设置增删改查
  7 + payload:
  8 + - ref: description
  9 + required: true
  10 + - ref: userName
  11 + required: true
  12 + result:
  13 + - name: column_setting
  14 + type:
  15 + schema: column_setting
  1 +version: v1
  2 +kind: Method
  3 +metadata:
  4 + name: getColumnSetting
  5 + type: query
  6 + description: 返回栏目设置增删改查
  7 + payload:
  8 + - ref: columnSettingId
  9 + required: true
  10 + result:
  11 + - name: column_setting
  12 + type:
  13 + schema: column_setting
  1 +version: v1
  2 +kind: Method
  3 +metadata:
  4 + name: listColumnSetting
  5 + type: query
  6 + description: 返回栏目设置增删改查列表
  7 + payload:
  8 + - ref: offset
  9 + required: true
  10 + - ref: limit
  11 + required: true
  12 + result:
  13 + - ref: count
  14 + required: true
  15 + - name: column_setting
  16 + type:
  17 + schema: column_setting
  1 +version: v1
  2 +kind: Method
  3 +metadata:
  4 + name: removeColumnSetting
  5 + type: command
  6 + description: 移除栏目设置增删改查
  7 + payload:
  8 + - ref: columnSettingId
  9 + required: true
  10 + result:
  11 + - name: column_setting
  12 + type:
  13 + schema: column_setting
  1 +version: v1
  2 +kind: Method
  3 +metadata:
  4 + name: resetColumn
  5 + type: command
  6 + description: 重置栏目设置
  7 + result:
  8 + - name: column_setting
  9 + type:
  10 + schema: column_setting
  1 +version: v1
  2 +kind: Method
  3 +metadata:
  4 + name: updateColumnSetting
  5 + type: command
  6 + description: 更新栏目设置增删改查
  7 + payload:
  8 + - ref: columnSettingId
  9 + required: true
  10 + result:
  11 + - name: column_setting
  12 + type:
  13 + schema: column_setting
  1 +version: v1
  2 +kind: Service
  3 +metadata:
  4 + name: column_setting
  5 + description: 栏目设置
@@ -13,17 +13,17 @@ require ( @@ -13,17 +13,17 @@ require (
13 github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect 13 github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
14 github.com/fatih/structs v1.1.0 // indirect 14 github.com/fatih/structs v1.1.0 // indirect
15 github.com/gavv/httpexpect v2.0.0+incompatible 15 github.com/gavv/httpexpect v2.0.0+incompatible
  16 + github.com/go-pg/pg v8.0.6+incompatible
16 github.com/go-pg/pg/v10 v10.7.3 17 github.com/go-pg/pg/v10 v10.7.3
17 github.com/google/go-querystring v1.0.0 // indirect 18 github.com/google/go-querystring v1.0.0 // indirect
18 github.com/gorilla/websocket v1.4.2 // indirect 19 github.com/gorilla/websocket v1.4.2 // indirect
19 github.com/imkira/go-interpol v1.1.0 // indirect 20 github.com/imkira/go-interpol v1.1.0 // indirect
20 github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect 21 github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
21 - github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9 22 + github.com/linmadan/egglib-go v0.0.0-20201125083542-25358a549edb
22 github.com/mattn/go-colorable v0.1.6 // indirect 23 github.com/mattn/go-colorable v0.1.6 // indirect
23 github.com/moul/http2curl v1.0.0 // indirect 24 github.com/moul/http2curl v1.0.0 // indirect
24 github.com/onsi/ginkgo v1.14.2 25 github.com/onsi/ginkgo v1.14.2
25 github.com/onsi/gomega v1.10.3 26 github.com/onsi/gomega v1.10.3
26 - github.com/sclevine/agouti v3.0.0+incompatible // indirect  
27 github.com/sergi/go-diff v1.1.0 // indirect 27 github.com/sergi/go-diff v1.1.0 // indirect
28 github.com/shopspring/decimal v1.2.0 28 github.com/shopspring/decimal v1.2.0
29 github.com/smartystreets/goconvey v1.6.4 // indirect 29 github.com/smartystreets/goconvey v1.6.4 // indirect
  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 CreateColumnSettingCommand struct {
  11 + // 公司id
  12 + CompanyId int `json:"companyId"`
  13 + // 用户uid
  14 + Uid int64 `json:"uid"`
  15 + // 栏目设置描述
  16 + Description string `json:"description"`
  17 + // 栏目设置关联用户名称
  18 + UserName string `json:"userName"`
  19 + // 默认栏目设置
  20 + Value []domain.Column `json:"value"`
  21 + // 无效栏目设置爱
  22 + InvalidValue []domain.Column `json:"invalidValue"`
  23 + // 模块键值
  24 + Key string `json:"key"`
  25 +}
  26 +
  27 +//func (createColumnSettingCommand *CreateColumnSettingCommand) Valid(validation *validation.Validation) {
  28 +// _ = validation.SetError("CustomValid", "未实现的自定义认证")
  29 +//}
  30 +
  31 +func (createColumnSettingCommand *CreateColumnSettingCommand) ValidateCommand() error {
  32 + valid := validation.Validation{}
  33 + b, err := valid.Valid(createColumnSettingCommand)
  34 + if err != nil {
  35 + return err
  36 + }
  37 + if !b {
  38 + for _, validErr := range valid.Errors {
  39 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  40 + }
  41 + }
  42 + return nil
  43 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/astaxie/beego/validation"
  7 +)
  8 +
  9 +type RemoveColumnSettingCommand struct {
  10 + // 栏目设置id
  11 + ColumnSettingId int64 `json:"columnSettingId"`
  12 + // 用户uid
  13 + Uid int64 `json:"uid"`
  14 + // 公司id
  15 + CompanyId int `json:"companyId"`
  16 +}
  17 +
  18 +//func (removeColumnSettingCommand *RemoveColumnSettingCommand) Valid(validation *validation.Validation) {
  19 +// validation.SetError("CustomValid", "未实现的自定义认证")
  20 +//}
  21 +
  22 +func (removeColumnSettingCommand *RemoveColumnSettingCommand) ValidateCommand() error {
  23 + valid := validation.Validation{}
  24 + b, err := valid.Valid(removeColumnSettingCommand)
  25 + if err != nil {
  26 + return err
  27 + }
  28 + if !b {
  29 + for _, validErr := range valid.Errors {
  30 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  31 + }
  32 + }
  33 + return nil
  34 +}
  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 ResetColumnCommand struct {
  11 + // 公司id
  12 + CompanyId int `json:"companyId"`
  13 + // 用户uid
  14 + Uid int64 `json:"uid"`
  15 + // 默认栏目
  16 + Value []domain.Column `json:"value"`
  17 + // 默认无效栏目
  18 + InvalidValue []domain.Column `json:"invalidValue"`
  19 +}
  20 +
  21 +//func (resetColumnCommand *ResetColumnCommand) Valid(validation *validation.Validation) {
  22 +// _ = validation.SetError("CustomValid", "未实现的自定义认证")
  23 +//}
  24 +
  25 +func (resetColumnCommand *ResetColumnCommand) ValidateCommand() error {
  26 + valid := validation.Validation{}
  27 + b, err := valid.Valid(resetColumnCommand)
  28 + if err != nil {
  29 + return err
  30 + }
  31 + if !b {
  32 + for _, validErr := range valid.Errors {
  33 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  34 + }
  35 + }
  36 + return nil
  37 +}
  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 UpdateColumnSettingCommand struct {
  11 + // 栏目设置id
  12 + ColumnSettingId int64 `json:"columnSettingId"`
  13 + // 公司id
  14 + CompanyId int `json:"companyId"`
  15 + // 用户uid
  16 + Uid int64 `json:"uid"`
  17 + // 选中的栏目
  18 + Selected []domain.Column `json:"selected"`
  19 + // 未选中的栏目
  20 + UnSelected []domain.Column `json:"unselected"`
  21 + // 栏目设置
  22 + Value []domain.Column `json:"value"`
  23 + // 无效栏目设置
  24 + InvalidValue []domain.Column `json:"invalidValue"`
  25 + // 栏目
  26 + OrderBaseColumns OrderBaseColumns `json:"orderBaseColumns"`
  27 +}
  28 +
  29 +type OrderBaseColumns struct {
  30 + // 选中的栏目
  31 + Selected []domain.Column `json:"selected"`
  32 + // 未选中的栏目
  33 + UnSelected []domain.Column `json:"unselected"`
  34 +}
  35 +
  36 +//func (updateColumnSettingCommand *UpdateColumnSettingCommand) Valid(validation *validation.Validation) {
  37 +// _ = validation.SetError("CustomValid", "未实现的自定义认证")
  38 +//}
  39 +
  40 +func (updateColumnSettingCommand *UpdateColumnSettingCommand) ValidateCommand() error {
  41 + valid := validation.Validation{}
  42 + b, err := valid.Valid(updateColumnSettingCommand)
  43 + if err != nil {
  44 + return err
  45 + }
  46 + if !b {
  47 + for _, validErr := range valid.Errors {
  48 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  49 + }
  50 + }
  51 + return nil
  52 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/astaxie/beego/validation"
  7 +)
  8 +
  9 +type GetColumnSettingQuery struct {
  10 + // 栏目设置id
  11 + ColumnSettingId int64 `json:"columnSettingId"`
  12 + // 公司id
  13 + CompanyId int `json:"companyId"`
  14 + // 用户uid
  15 + Uid int64 `json:"uid"`
  16 +}
  17 +
  18 +//func (getColumnSettingQuery *GetColumnSettingQuery) Valid(validation *validation.Validation) {
  19 +// _ = validation.SetError("CustomValid", "未实现的自定义认证")
  20 +//}
  21 +
  22 +func (getColumnSettingQuery *GetColumnSettingQuery) ValidateQuery() error {
  23 + valid := validation.Validation{}
  24 + b, err := valid.Valid(getColumnSettingQuery)
  25 + if err != nil {
  26 + return err
  27 + }
  28 + if !b {
  29 + for _, validErr := range valid.Errors {
  30 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  31 + }
  32 + }
  33 + return nil
  34 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/astaxie/beego/validation"
  7 +)
  8 +
  9 +type ListColumnSettingQuery struct {
  10 + // 查询偏离量
  11 + Offset int `json:"offset" valid:"Required"`
  12 + // 查询限制
  13 + Limit int `json:"limit" valid:"Required"`
  14 +}
  15 +
  16 +//func (listColumnSettingQuery *ListColumnSettingQuery) Valid(validation *validation.Validation) {
  17 +// _ = validation.SetError("CustomValid", "未实现的自定义认证")
  18 +//}
  19 +
  20 +func (listColumnSettingQuery *ListColumnSettingQuery) ValidateQuery() error {
  21 + valid := validation.Validation{}
  22 + b, err := valid.Valid(listColumnSettingQuery)
  23 + if err != nil {
  24 + return err
  25 + }
  26 + if !b {
  27 + for _, validErr := range valid.Errors {
  28 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  29 + }
  30 + }
  31 + return nil
  32 +}
  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/columnSetting/command"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/columnSetting/query"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  12 + "strconv"
  13 + "time"
  14 +)
  15 +
  16 +// 栏目设置
  17 +type ColumnSettingService struct {
  18 +}
  19 +
  20 +/**
  21 + * @Author SteveChan
  22 + * @Description //新增用户时,初始化栏目设置
  23 + * @Date 23:13 2021/1/26
  24 + * @Param
  25 + * @return
  26 + **/
  27 +func (columnSettingService *ColumnSettingService) CreateColumnSetting(createColumnSettingCommand *command.CreateColumnSettingCommand) (interface{}, error) {
  28 + if err := createColumnSettingCommand.ValidateCommand(); err != nil {
  29 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  30 + }
  31 + transactionContext, err := factory.CreateTransactionContext(nil)
  32 + if err != nil {
  33 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  34 + }
  35 + if errStart := transactionContext.StartTransaction(); errStart != nil {
  36 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errStart.Error())
  37 + }
  38 + defer func() {
  39 + _ = transactionContext.RollbackTransaction()
  40 + }()
  41 + newColumnSetting := &domain.ColumnSetting{
  42 + Description: createColumnSettingCommand.Description,
  43 + UserName: createColumnSettingCommand.UserName,
  44 + CompanyId: createColumnSettingCommand.CompanyId,
  45 + Uid: createColumnSettingCommand.Uid,
  46 + Key: constant.ORDER_BASE, // 订单栏目模块名称
  47 + Value: domain.DefaultColumns, // 栏目值数组,创建用户时使用默认栏目设置
  48 + InvalidValue: domain.DefaultInvalidColumns, // 初始化无效栏目数组
  49 + CreatedAt: time.Now(),
  50 + UpdatedAt: time.Now(),
  51 + }
  52 + var columnSettingRepository domain.ColumnSettingRepository
  53 + if value, errFac := factory.CreateColumnSettingRepository(map[string]interface{}{
  54 + "transactionContext": transactionContext,
  55 + }); errFac != nil {
  56 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errFac.Error())
  57 + } else {
  58 + columnSettingRepository = value
  59 + }
  60 + if columnSettingSaved, errSaved := columnSettingRepository.Save(newColumnSetting); errSaved != nil {
  61 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errSaved.Error())
  62 + } else {
  63 + if errCommit := transactionContext.CommitTransaction(); errCommit != nil {
  64 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errCommit.Error())
  65 + }
  66 + return columnSettingSaved, nil
  67 + }
  68 +}
  69 +
  70 +/**
  71 + * @Author SteveChan
  72 + * @Description // 返回栏目设置
  73 + * @Date 23:14 2021/1/26
  74 + * @Param
  75 + * @return
  76 + **/
  77 +func (columnSettingService *ColumnSettingService) GetColumnSetting(getColumnSettingQuery *query.GetColumnSettingQuery) (interface{}, error) {
  78 + if err := getColumnSettingQuery.ValidateQuery(); err != nil {
  79 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  80 + }
  81 + transactionContext, err := factory.CreateTransactionContext(nil)
  82 + if err != nil {
  83 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  84 + }
  85 + if err := transactionContext.StartTransaction(); err != nil {
  86 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  87 + }
  88 + defer func() {
  89 + _ = transactionContext.RollbackTransaction()
  90 + }()
  91 + var columnSettingRepository domain.ColumnSettingRepository
  92 + if value, errFact := factory.CreateColumnSettingRepository(map[string]interface{}{
  93 + "transactionContext": transactionContext,
  94 + }); errFact != nil {
  95 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errFact.Error())
  96 + } else {
  97 + columnSettingRepository = value
  98 + }
  99 + columnSettingFound, err := columnSettingRepository.FindOne(map[string]interface{}{"uid": getColumnSettingQuery.Uid, "companyId": getColumnSettingQuery.CompanyId})
  100 + if err != nil {
  101 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  102 + }
  103 + if columnSettingFound == nil {
  104 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", strconv.FormatInt(getColumnSettingQuery.Uid, 10)))
  105 + } else {
  106 + if errCommit := transactionContext.CommitTransaction(); errCommit != nil {
  107 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errCommit.Error())
  108 + }
  109 +
  110 + // 数据mapper
  111 + orderBaseColumns := map[string]interface{}{
  112 + "orderBaseColumns": map[string]interface{}{
  113 + "selected": columnSettingFound.Value,
  114 + "unselected": columnSettingFound.InvalidValue,
  115 + },
  116 + }
  117 +
  118 + return orderBaseColumns, nil
  119 + }
  120 +}
  121 +
  122 +// 返回栏目设置增删改查列表
  123 +func (columnSettingService *ColumnSettingService) ListColumnSetting(listColumnSettingQuery *query.ListColumnSettingQuery) (interface{}, error) {
  124 + if err := listColumnSettingQuery.ValidateQuery(); err != nil {
  125 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  126 + }
  127 + transactionContext, err := factory.CreateTransactionContext(nil)
  128 + if err != nil {
  129 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  130 + }
  131 + if err := transactionContext.StartTransaction(); err != nil {
  132 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  133 + }
  134 + defer func() {
  135 + transactionContext.RollbackTransaction()
  136 + }()
  137 + var columnSettingRepository domain.ColumnSettingRepository
  138 + if value, err := factory.CreateColumnSettingRepository(map[string]interface{}{
  139 + "transactionContext": transactionContext,
  140 + }); err != nil {
  141 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  142 + } else {
  143 + columnSettingRepository = value
  144 + }
  145 + if count, columnSettings, err := columnSettingRepository.Find(tool_funs.SimpleStructToMap(listColumnSettingQuery)); err != nil {
  146 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  147 + } else {
  148 + if err := transactionContext.CommitTransaction(); err != nil {
  149 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  150 + }
  151 + return map[string]interface{}{
  152 + "count": count,
  153 + "column_settings": columnSettings,
  154 + }, nil
  155 + }
  156 +}
  157 +
  158 +/**
  159 + * @Author SteveChan
  160 + * @Description // 删除用户时移除栏目设置
  161 + * @Date 23:14 2021/1/26
  162 + * @Param
  163 + * @return
  164 + **/
  165 +func (columnSettingService *ColumnSettingService) RemoveColumnSetting(removeColumnSettingCommand *command.RemoveColumnSettingCommand) (interface{}, error) {
  166 + if err := removeColumnSettingCommand.ValidateCommand(); err != nil {
  167 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  168 + }
  169 + transactionContext, err := factory.CreateTransactionContext(nil)
  170 + if err != nil {
  171 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  172 + }
  173 + if errSt := transactionContext.StartTransaction(); errSt != nil {
  174 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errSt.Error())
  175 + }
  176 + defer func() {
  177 + _ = transactionContext.RollbackTransaction()
  178 + }()
  179 + var columnSettingRepository domain.ColumnSettingRepository
  180 + if value, errFac := factory.CreateColumnSettingRepository(map[string]interface{}{
  181 + "transactionContext": transactionContext,
  182 + }); errFac != nil {
  183 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errFac.Error())
  184 + } else {
  185 + columnSettingRepository = value
  186 + }
  187 + columnSettingFound, err := columnSettingRepository.FindOne(map[string]interface{}{"uid": removeColumnSettingCommand.Uid, "companyId": removeColumnSettingCommand.CompanyId})
  188 + if err != nil {
  189 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  190 + }
  191 + if columnSettingFound == nil {
  192 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", strconv.FormatInt(removeColumnSettingCommand.Uid, 10)))
  193 + }
  194 + if columnSettingRemoved, _, errRm := columnSettingRepository.Remove(columnSettingFound, nil); errRm != nil {
  195 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errRm.Error())
  196 + } else {
  197 + if errTr := transactionContext.CommitTransaction(); errTr != nil {
  198 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errRm.Error())
  199 + }
  200 +
  201 + // 数据mapper
  202 + orderBaseColumns := map[string]interface{}{
  203 + "orderBaseColumns": map[string]interface{}{
  204 + "selected": columnSettingRemoved.Value,
  205 + "unselected": columnSettingRemoved.InvalidValue,
  206 + },
  207 + }
  208 +
  209 + return orderBaseColumns, nil
  210 + }
  211 +}
  212 +
  213 +/**
  214 + * @Author SteveChan
  215 + * @Description // 重置栏目设置
  216 + * @Date 23:15 2021/1/26
  217 + * @Param
  218 + * @return
  219 + **/
  220 +func (columnSettingService *ColumnSettingService) ResetColumn(resetColumnCommand *command.ResetColumnCommand) (interface{}, error) {
  221 + if err := resetColumnCommand.ValidateCommand(); err != nil {
  222 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  223 + }
  224 + transactionContext, err := factory.CreateTransactionContext(nil)
  225 + if err != nil {
  226 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  227 + }
  228 + if errStart := transactionContext.StartTransaction(); errStart != nil {
  229 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errStart.Error())
  230 + }
  231 + defer func() {
  232 + _ = transactionContext.RollbackTransaction()
  233 + }()
  234 +
  235 + var columnSettingRepository domain.ColumnSettingRepository
  236 + if value, errFact := factory.CreateColumnSettingRepository(map[string]interface{}{
  237 + "transactionContext": transactionContext,
  238 + }); errFact != nil {
  239 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errFact.Error())
  240 + } else {
  241 + columnSettingRepository = value
  242 + }
  243 + columnSettingFound, err := columnSettingRepository.FindOne(map[string]interface{}{"uid": resetColumnCommand.Uid, "companyId": resetColumnCommand.CompanyId})
  244 + if err != nil {
  245 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  246 + }
  247 + if columnSettingFound == nil {
  248 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", strconv.FormatInt(resetColumnCommand.Uid, 10)))
  249 + }
  250 + if errUpdated := columnSettingFound.Update(tool_funs.SimpleStructToMap(resetColumnCommand)); errUpdated != nil {
  251 + return nil, application.ThrowError(application.BUSINESS_ERROR, errUpdated.Error())
  252 + }
  253 + if columnSettingSaved, errSaved := columnSettingRepository.Save(columnSettingFound); errSaved != nil {
  254 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errSaved.Error())
  255 + } else {
  256 + if errCommit := transactionContext.CommitTransaction(); errCommit != nil {
  257 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errCommit.Error())
  258 + }
  259 +
  260 + // 数据mapper
  261 + orderBaseColumns := map[string]interface{}{
  262 + "orderBaseColumns": map[string]interface{}{
  263 + "selected": columnSettingSaved.Value,
  264 + "unselected": columnSettingSaved.InvalidValue,
  265 + },
  266 + }
  267 +
  268 + return orderBaseColumns, nil
  269 + }
  270 +}
  271 +
  272 +/**
  273 + * @Author SteveChan
  274 + * @Description // 更新栏目设置
  275 + * @Date 23:15 2021/1/26
  276 + * @Param
  277 + * @return
  278 + **/
  279 +func (columnSettingService *ColumnSettingService) UpdateColumnSetting(updateColumnSettingCommand *command.UpdateColumnSettingCommand) (interface{}, error) {
  280 + if err := updateColumnSettingCommand.ValidateCommand(); err != nil {
  281 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  282 + }
  283 + transactionContext, err := factory.CreateTransactionContext(nil)
  284 + if err != nil {
  285 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  286 + }
  287 + if errStart := transactionContext.StartTransaction(); errStart != nil {
  288 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errStart.Error())
  289 + }
  290 + defer func() {
  291 + _ = transactionContext.RollbackTransaction()
  292 + }()
  293 + var columnSettingRepository domain.ColumnSettingRepository
  294 + if value, errFact := factory.CreateColumnSettingRepository(map[string]interface{}{
  295 + "transactionContext": transactionContext,
  296 + }); errFact != nil {
  297 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errFact.Error())
  298 + } else {
  299 + columnSettingRepository = value
  300 + }
  301 + updateColumnSettingCommand.Value = updateColumnSettingCommand.Selected
  302 + updateColumnSettingCommand.InvalidValue = updateColumnSettingCommand.UnSelected
  303 + columnSetting, err := columnSettingRepository.FindOne(map[string]interface{}{"uid": updateColumnSettingCommand.Uid, "companyId": updateColumnSettingCommand.CompanyId})
  304 + if err != nil {
  305 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  306 + }
  307 + if columnSetting == nil {
  308 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", strconv.FormatInt(updateColumnSettingCommand.Uid, 10)))
  309 + }
  310 + if errUpdated := columnSetting.Update(tool_funs.SimpleStructToMap(updateColumnSettingCommand)); errUpdated != nil {
  311 + return nil, application.ThrowError(application.BUSINESS_ERROR, errUpdated.Error())
  312 + }
  313 + if columnSettingSaved, errSaved := columnSettingRepository.Save(columnSetting); errSaved != nil {
  314 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, errSaved.Error())
  315 + } else {
  316 + if errCommit := transactionContext.CommitTransaction(); errCommit != nil {
  317 + return nil, application.ThrowError(application.TRANSACTION_ERROR, errCommit.Error())
  318 + }
  319 +
  320 + // 数据mapper
  321 + orderBaseColumns := map[string]interface{}{
  322 + "orderBaseColumns": map[string]interface{}{
  323 + "selected": columnSettingSaved.Value,
  324 + "unselected": columnSettingSaved.InvalidValue,
  325 + },
  326 + }
  327 +
  328 + return orderBaseColumns, nil
  329 + }
  330 +}
  331 +
  332 +func NewColumnSettingService(options map[string]interface{}) *ColumnSettingService {
  333 + newColumnSettingService := &ColumnSettingService{}
  334 + return newColumnSettingService
  335 +}
@@ -104,3 +104,11 @@ func CreateOrderLogRepository(options map[string]interface{}) (domain.OrderLogRe @@ -104,3 +104,11 @@ func CreateOrderLogRepository(options map[string]interface{}) (domain.OrderLogRe
104 } 104 }
105 return repository.NewOrderLogRepository(transactionContext) 105 return repository.NewOrderLogRepository(transactionContext)
106 } 106 }
  107 +
  108 +func CreateColumnSettingRepository(options map[string]interface{}) (domain.ColumnSettingRepository, error) {
  109 + var transactionContext *transaction.TransactionContext
  110 + if value, ok := options["transactionContext"]; ok {
  111 + transactionContext = value.(*transaction.TransactionContext)
  112 + }
  113 + return repository.NewColumnSettingRepository(transactionContext)
  114 +}
1 package command 1 package command
2 2
3 -import "errors" 3 +import (
  4 + "errors"
  5 + "time"
  6 +)
4 7
5 //创建订单 8 //创建订单
6 type CreateOrderCommand struct { 9 type CreateOrderCommand struct {
@@ -32,6 +35,8 @@ type CreateOrderCommand struct { @@ -32,6 +35,8 @@ type CreateOrderCommand struct {
32 Code string `json:"code"` 35 Code string `json:"code"`
33 //合伙人类型名称-错误信息返回 36 //合伙人类型名称-错误信息返回
34 PartnerCategoryName string `json:"partnerCategoryName"` 37 PartnerCategoryName string `json:"partnerCategoryName"`
  38 + //销售日期
  39 + SaleDate time.Time `json:"saleDate"`
35 } 40 }
36 41
37 func (postData *CreateOrderCommand) Valid() error { 42 func (postData *CreateOrderCommand) Valid() error {
1 package command 1 package command
2 2
  3 +import "time"
  4 +
3 //UpdateOrderPurposeCommand 更新订单单 5 //UpdateOrderPurposeCommand 更新订单单
4 type UpdateOrderCommand struct { 6 type UpdateOrderCommand struct {
5 Id int64 `json:"id"` 7 Id int64 `json:"id"`
@@ -21,6 +23,8 @@ type UpdateOrderCommand struct { @@ -21,6 +23,8 @@ type UpdateOrderCommand struct {
21 Goods []OrderGoodData `json:"goods"` 23 Goods []OrderGoodData `json:"goods"`
22 //公司id 24 //公司id
23 CompanyId int64 `json:"companyId"` 25 CompanyId int64 `json:"companyId"`
24 - // 合伙人类型 26 + //合伙人类型
25 PartnerCategory int64 `json:"partner_category"` 27 PartnerCategory int64 `json:"partner_category"`
  28 + //销售日期
  29 + SaleDate time.Time `json:"saleDate"`
26 } 30 }
@@ -8,7 +8,7 @@ package query @@ -8,7 +8,7 @@ package query
8 8
9 /** 9 /**
10 * @Author SteveChan 10 * @Author SteveChan
11 - * @Description //TODO 查询合伙人id 11 + * @Description // 查询合伙人id
12 * @Date 23:18 2021/1/6 12 * @Date 23:18 2021/1/6
13 **/ 13 **/
14 type GetPartnerIdQuery struct { 14 type GetPartnerIdQuery struct {
@@ -8,7 +8,7 @@ package query @@ -8,7 +8,7 @@ package query
8 8
9 /** 9 /**
10 * @Author SteveChan 10 * @Author SteveChan
11 - * @Description //TODO 查询产品id 11 + * @Description //查询产品id
12 * @Date 23:18 2021/1/6 12 * @Date 23:18 2021/1/6
13 **/ 13 **/
14 type GetProductIdQuery struct { 14 type GetProductIdQuery struct {
@@ -16,10 +16,14 @@ type ListOrderBaseQuery struct { @@ -16,10 +16,14 @@ type ListOrderBaseQuery struct {
16 DeliveryCode string `json:"deliveryCode"` 16 DeliveryCode string `json:"deliveryCode"`
17 //公司id 17 //公司id
18 CompanyId int64 `json:"companyId"` 18 CompanyId int64 `json:"companyId"`
  19 + //用户uid
  20 + Uid int64 `json:"uid"`
19 //订单类型 21 //订单类型
20 OrderType int `json:"orderType"` 22 OrderType int `json:"orderType"`
21 //合伙人分类 23 //合伙人分类
22 PartnerCategory int `json:"partnerCategory"` 24 PartnerCategory int `json:"partnerCategory"`
  25 + //合伙人类型名称
  26 + PartnerCategoryName string `json:"partnerCategoryName"`
23 //更新时间开始 27 //更新时间开始
24 UpdateTimeBegin string `json:"updateTimeBegin"` 28 UpdateTimeBegin string `json:"updateTimeBegin"`
25 //更新时间截止 29 //更新时间截止
@@ -28,4 +32,8 @@ type ListOrderBaseQuery struct { @@ -28,4 +32,8 @@ type ListOrderBaseQuery struct {
28 CreateTimeBegin string `json:"createTimeBegin"` 32 CreateTimeBegin string `json:"createTimeBegin"`
29 //创建时间截止 33 //创建时间截止
30 CreateTimeEnd string `json:"createTimeEnd"` 34 CreateTimeEnd string `json:"createTimeEnd"`
  35 + //销售时间开始
  36 + SaleDateBegin string `json:"saleDateBegin"`
  37 + //销售时间结束
  38 + SaleDateEnd string `json:"sateDateEnd"`
31 } 39 }
  1 +/**
  2 + @author: stevechan
  3 + @date: 2021/1/27
  4 + @note:
  5 +**/
  6 +
  7 +package query
  8 +
  9 +type ListOrderForExcelQuery struct {
  10 + Type string `json:"type"` // 操作类型 ORDER_BASE
  11 + Where Where `json:"where"` // 导出条件
  12 + IDS []int `json:"ids"` // 勾选id
  13 +}
  14 +
  15 +type Where struct {
  16 + PartnerName string `json:"partnerName"` // 合伙人姓名
  17 + OrderCode string `json:"orderCode"` // 订单号
  18 + DeliveryCode string `json:"deliveryCode"` // 发货单号
  19 + PartnerCategory int `json:"partnerCategory"` // 合伙人类型
  20 + PartnerCategoryName string `json:"partnerCategoryName"` // 合伙人类型名称
  21 + UpdateTime []string `json:"updateTime"` // 更新时间
  22 + CreateTime []string `json:"createTime"` // 创建时间
  23 + SaleDate []string `json:"saleDate"` // 销售日期
  24 +}
@@ -2,6 +2,9 @@ package service @@ -2,6 +2,9 @@ package service
2 2
3 import ( 3 import (
4 "fmt" 4 "fmt"
  5 + "github.com/linmadan/egglib-go/core/application"
  6 + "strconv"
  7 + "time"
5 8
6 "github.com/astaxie/beego/logs" 9 "github.com/astaxie/beego/logs"
7 10
@@ -62,9 +65,11 @@ func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrder @@ -62,9 +65,11 @@ func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrder
62 listOrderQuery.PartnerName, // 合伙人姓名 65 listOrderQuery.PartnerName, // 合伙人姓名
63 listOrderQuery.OrderCode, // 订单号 66 listOrderQuery.OrderCode, // 订单号
64 listOrderQuery.DeliveryCode, // 发货单号 67 listOrderQuery.DeliveryCode, // 发货单号
65 - [2]string{listOrderQuery.UpdateTimeBegin, listOrderQuery.UpdateTimeEnd},  
66 - [2]string{listOrderQuery.CreateTimeBegin, listOrderQuery.CreateTimeEnd}, 68 + [2]string{listOrderQuery.UpdateTimeBegin, listOrderQuery.UpdateTimeEnd}, // 订单创建时间
  69 + [2]string{listOrderQuery.CreateTimeBegin, listOrderQuery.CreateTimeEnd}, // 订单更新时间
  70 + [2]string{listOrderQuery.SaleDateBegin, listOrderQuery.SaleDateEnd}, // 销售日期
67 listOrderQuery.PartnerCategory, 71 listOrderQuery.PartnerCategory,
  72 + listOrderQuery.PartnerCategoryName,
68 listOrderQuery.Limit, listOrderQuery.Offset, 73 listOrderQuery.Limit, listOrderQuery.Offset,
69 ) 74 )
70 if err != nil { 75 if err != nil {
@@ -94,6 +99,7 @@ func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrder @@ -94,6 +99,7 @@ func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrder
94 "index": listIndex, 99 "index": listIndex,
95 "createTime": orders[i].CreateTime.Local().Format("2006-01-02 15:04:05"), 100 "createTime": orders[i].CreateTime.Local().Format("2006-01-02 15:04:05"),
96 "updateTime": orders[i].UpdateTime.Local().Format("2006-01-02 15:04:05"), 101 "updateTime": orders[i].UpdateTime.Local().Format("2006-01-02 15:04:05"),
  102 + "saleDate": orders[i].SaleDate.Local().Format("2006-01-02 15:04:05"),
97 "buyer": orders[i].Buyer.BuyerName, 103 "buyer": orders[i].Buyer.BuyerName,
98 "id": fmt.Sprint(orders[i].Id), 104 "id": fmt.Sprint(orders[i].Id),
99 "orderId": orders[i].OrderCode, 105 "orderId": orders[i].OrderCode,
@@ -188,7 +194,13 @@ func (service OrderInfoService) GetOrderDetail(getOrderQuery query.GetOrderQuery @@ -188,7 +194,13 @@ func (service OrderInfoService) GetOrderDetail(getOrderQuery query.GetOrderQuery
188 return order, nil 194 return order, nil
189 } 195 }
190 196
191 -//CreateNewOrder 创建订单 197 +/**
  198 + * @Author SteveChan
  199 + * @Description // 创建订单,增加销售日期
  200 + * @Date 11:57 2021/1/26
  201 + * @Param
  202 + * @return
  203 + **/
192 func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (*domain.OrderBase, error) { 204 func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (*domain.OrderBase, error) {
193 var ( 205 var (
194 transactionContext, _ = factory.CreateTransactionContext(nil) 206 transactionContext, _ = factory.CreateTransactionContext(nil)
@@ -255,7 +267,8 @@ func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) ( @@ -255,7 +267,8 @@ func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (
255 goodMap[goodname] = 1 267 goodMap[goodname] = 1
256 } 268 }
257 newOrder := &domain.OrderBase{ 269 newOrder := &domain.OrderBase{
258 - OrderType: cmd.OrderType, OrderCode: cmd.OrderCode, 270 + OrderType: cmd.OrderType,
  271 + OrderCode: cmd.OrderCode,
259 DeliveryCode: cmd.DeliveryCode, 272 DeliveryCode: cmd.DeliveryCode,
260 Buyer: domain.Buyer{ 273 Buyer: domain.Buyer{
261 BuyerName: cmd.BuyerName, 274 BuyerName: cmd.BuyerName,
@@ -263,6 +276,7 @@ func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) ( @@ -263,6 +276,7 @@ func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (
263 RegionInfo: domain.RegionInfo{ 276 RegionInfo: domain.RegionInfo{
264 RegionName: cmd.OrderRegion, 277 RegionName: cmd.OrderRegion,
265 }, 278 },
  279 + SaleDate: cmd.SaleDate,
266 PartnerId: cmd.PartnerId, 280 PartnerId: cmd.PartnerId,
267 PartnerInfo: partnerData.Partner, 281 PartnerInfo: partnerData.Partner,
268 SalesmanBonusPercent: cmd.SalesmanBonusPercent, 282 SalesmanBonusPercent: cmd.SalesmanBonusPercent,
@@ -277,15 +291,15 @@ func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) ( @@ -277,15 +291,15 @@ func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (
277 var cmdPartnerCategoryOk bool 291 var cmdPartnerCategoryOk bool
278 for _, v := range partnerData.PartnerCategoryInfos { 292 for _, v := range partnerData.PartnerCategoryInfos {
279 if v.Id == cmd.PartnerCategory { 293 if v.Id == cmd.PartnerCategory {
280 - _, categorys, err := categoryRepository.Find(domain.PartnerCategoryFindQuery{ 294 + _, categories, err := categoryRepository.Find(domain.PartnerCategoryFindQuery{
281 Ids: []int64{v.Id}, 295 Ids: []int64{v.Id},
282 }) 296 })
283 if err != nil { 297 if err != nil {
284 e := fmt.Sprintf("获取合伙人分类数据失败:%s", err) 298 e := fmt.Sprintf("获取合伙人分类数据失败:%s", err)
285 return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e) 299 return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
286 } 300 }
287 - if len(categorys) > 0 {  
288 - newOrder.PartnerCategory = categorys[0] 301 + if len(categories) > 0 {
  302 + newOrder.PartnerCategory = categories[0]
289 cmdPartnerCategoryOk = true 303 cmdPartnerCategoryOk = true
290 } 304 }
291 break 305 break
@@ -393,6 +407,28 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand) @@ -393,6 +407,28 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand)
393 transactionContext.RollbackTransaction() 407 transactionContext.RollbackTransaction()
394 }() 408 }()
395 409
  410 + // 获取合伙人类型
  411 + var PartnerCategoryRepository domain.PartnerCategoryRepository
  412 + if PartnerCategoryRepository, err = factory.CreatePartnerCategoryRepository(map[string]interface{}{
  413 + "transactionContext": transactionContext,
  414 + }); err != nil {
  415 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  416 + }
  417 + var partnerCategories []domain.PartnerCategory
  418 + _, partnerCategories, err = PartnerCategoryRepository.Find(domain.PartnerCategoryFindQuery{
  419 + Ids: []int64{},
  420 + })
  421 + if err != nil {
  422 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("检索合伙人类型数据失败"))
  423 + }
  424 + partnerCategoryMap := map[int64]interface{}{}
  425 + if len(partnerCategories) > 0 {
  426 + for _, partnerCategory := range partnerCategories {
  427 + partnerCategoryMap[partnerCategory.Id] = partnerCategory.Name
  428 + }
  429 + }
  430 +
  431 + // 获取合伙人数据
396 var PartnerInfoRepository domain.PartnerInfoRepository 432 var PartnerInfoRepository domain.PartnerInfoRepository
397 if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{ 433 if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
398 "transactionContext": transactionContext, 434 "transactionContext": transactionContext,
@@ -500,6 +536,7 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand) @@ -500,6 +536,7 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand)
500 var cmdPartnerCategoryOk bool 536 var cmdPartnerCategoryOk bool
501 for _, v := range partnerData.PartnerCategoryInfos { 537 for _, v := range partnerData.PartnerCategoryInfos {
502 if v.Id == cmd.PartnerCategory { 538 if v.Id == cmd.PartnerCategory {
  539 + v.Name = partnerCategoryMap[v.Id].(string)
503 oldOrderData.PartnerCategory = v 540 oldOrderData.PartnerCategory = v
504 cmdPartnerCategoryOk = true 541 cmdPartnerCategoryOk = true
505 } 542 }
@@ -511,6 +548,7 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand) @@ -511,6 +548,7 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand)
511 oldOrderData.DeliveryCode = cmd.DeliveryCode 548 oldOrderData.DeliveryCode = cmd.DeliveryCode
512 oldOrderData.Buyer.BuyerName = cmd.BuyerName 549 oldOrderData.Buyer.BuyerName = cmd.BuyerName
513 oldOrderData.RegionInfo.RegionName = cmd.OrderRegion 550 oldOrderData.RegionInfo.RegionName = cmd.OrderRegion
  551 + oldOrderData.SaleDate = cmd.SaleDate
514 oldOrderData.PartnerId = cmd.PartnerId 552 oldOrderData.PartnerId = cmd.PartnerId
515 oldOrderData.PartnerInfo = partnerData.Partner 553 oldOrderData.PartnerInfo = partnerData.Partner
516 oldOrderData.SalesmanBonusPercent = cmd.SalesmanBonusPercent 554 oldOrderData.SalesmanBonusPercent = cmd.SalesmanBonusPercent
@@ -519,7 +557,6 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand) @@ -519,7 +557,6 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand)
519 if err != nil { 557 if err != nil {
520 return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err)) 558 return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
521 } 559 }
522 -  
523 err = orderBaseRepository.Save(oldOrderData) 560 err = orderBaseRepository.Save(oldOrderData)
524 if err != nil { 561 if err != nil {
525 return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err)) 562 return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
@@ -883,7 +920,7 @@ func (service OrderInfoService) ListOrderBonusForExcel(listOrderQuery query.List @@ -883,7 +920,7 @@ func (service OrderInfoService) ListOrderBonusForExcel(listOrderQuery query.List
883 920
884 /** 921 /**
885 * @Author SteveChan 922 * @Author SteveChan
886 - * @Description // 导出订单数据 923 + * @Description //根据栏目设置,导出订单数据
887 * @Date 22:05 2021/1/10 924 * @Date 22:05 2021/1/10
888 * @Param 925 * @Param
889 * @return 926 * @return
@@ -897,7 +934,7 @@ func (service OrderInfoService) ListOrderForExcel(listOrderQuery query.ListOrder @@ -897,7 +934,7 @@ func (service OrderInfoService) ListOrderForExcel(listOrderQuery query.ListOrder
897 return nil, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error()) 934 return nil, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
898 } 935 }
899 defer func() { 936 defer func() {
900 - transactionContext.RollbackTransaction() 937 + _ = transactionContext.RollbackTransaction()
901 }() 938 }()
902 939
903 var ( 940 var (
@@ -916,61 +953,105 @@ func (service OrderInfoService) ListOrderForExcel(listOrderQuery query.ListOrder @@ -916,61 +953,105 @@ func (service OrderInfoService) ListOrderForExcel(listOrderQuery query.ListOrder
916 listOrderQuery.DeliveryCode, // 发货单号 953 listOrderQuery.DeliveryCode, // 发货单号
917 [2]string{listOrderQuery.UpdateTimeBegin, listOrderQuery.UpdateTimeEnd}, 954 [2]string{listOrderQuery.UpdateTimeBegin, listOrderQuery.UpdateTimeEnd},
918 [2]string{listOrderQuery.CreateTimeBegin, listOrderQuery.CreateTimeEnd}, 955 [2]string{listOrderQuery.CreateTimeBegin, listOrderQuery.CreateTimeEnd},
  956 + [2]string{listOrderQuery.SaleDateBegin, listOrderQuery.SaleDateEnd},
919 listOrderQuery.PartnerCategory, 957 listOrderQuery.PartnerCategory,
  958 + listOrderQuery.PartnerCategoryName,
920 ) 959 )
921 if err != nil { 960 if err != nil {
922 return nil, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) 961 return nil, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
923 } 962 }
  963 +
  964 + // 获取栏目设置
  965 + var columnSettingRepository domain.ColumnSettingRepository
  966 + if value, errFact := factory.CreateColumnSettingRepository(map[string]interface{}{
  967 + "transactionContext": transactionContext,
  968 + }); errFact != nil {
  969 + return nil, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  970 + } else {
  971 + columnSettingRepository = value
  972 + }
  973 + columnSettingFound, err := columnSettingRepository.FindOne(map[string]interface{}{"uid": listOrderQuery.Uid, "companyId": listOrderQuery.CompanyId})
  974 + if err != nil {
  975 + return nil, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  976 + }
  977 + if columnSettingFound == nil {
  978 + return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", strconv.FormatInt(listOrderQuery.Uid, 10)))
  979 + }
  980 +
924 err = transactionContext.CommitTransaction() 981 err = transactionContext.CommitTransaction()
925 if err != nil { 982 if err != nil {
926 return nil, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) 983 return nil, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
927 } 984 }
928 var resultMaps []map[string]string 985 var resultMaps []map[string]string
929 for i := range ordersData { 986 for i := range ordersData {
  987 + t, _ := time.ParseInLocation("2006-01-02 15:04:05", ordersData[i].SaleDate, time.Local)
930 m := map[string]string{ 988 m := map[string]string{
931 - "num": fmt.Sprint(i + 1),  
932 - "order_code": ordersData[i].OrderCode,  
933 - "delivery_code": ordersData[i].DeliveryCode,  
934 - "partner_name": ordersData[i].PartnerName,  
935 - "update_time": ordersData[i].UpdateTime,  
936 - "create_time": ordersData[i].CreateTime,  
937 - "plan_order_count": fmt.Sprint(ordersData[i].PlanOrderCount),  
938 - "use_order_count": "",  
939 - "region_name": fmt.Sprint(ordersData[i].RegionName),  
940 - "plan_order_amount": fmt.Sprintf("%10.2f", ordersData[i].PlanOrderAmount),  
941 - "use_order_amount": "",  
942 - "partner_category": ordersData[i].PartnerCategory,  
943 - "buyer_name": ordersData[i].BuyerName, 989 + //"num": fmt.Sprint(i + 1),
  990 + //"order_code": ordersData[i].OrderCode,
  991 + //"delivery_code": ordersData[i].DeliveryCode,
  992 + //"partner_name": ordersData[i].PartnerName,
  993 + //"update_time": ordersData[i].UpdateTime,
  994 + //"create_time": ordersData[i].CreateTime,
  995 + //"sale_date": ordersData[i].SaleDate,
  996 + //"plan_order_count": fmt.Sprint(ordersData[i].PlanOrderCount),
  997 + //"use_order_count": "",
  998 + //"region_name": fmt.Sprint(ordersData[i].RegionName),
  999 + //"plan_order_amount": fmt.Sprintf("%10.2f", ordersData[i].PlanOrderAmount),
  1000 + //"use_order_amount": "",
  1001 + //"partner_category": ordersData[i].PartnerCategory,
  1002 + //"buyer_name": ordersData[i].BuyerName,
  1003 + "index": fmt.Sprint(i + 1),
  1004 + "orderId": ordersData[i].OrderCode,
  1005 + "shipmentsId": ordersData[i].DeliveryCode,
  1006 + "partner": ordersData[i].PartnerName,
  1007 + "update_time": ordersData[i].UpdateTime,
  1008 + "create_time": ordersData[i].CreateTime,
  1009 + "saleDate": t.Format("2006-01-02"),
  1010 + "orderNum": fmt.Sprint(ordersData[i].PlanOrderCount),
  1011 + "quantityControl": "",
  1012 + "orderDist": fmt.Sprint(ordersData[i].RegionName),
  1013 + "orderPrice": fmt.Sprintf("%10.2f", ordersData[i].PlanOrderAmount),
  1014 + "priceControl": "",
  1015 + "partnerCategory": ordersData[i].PartnerCategory,
  1016 + "buyer": ordersData[i].BuyerName,
944 } 1017 }
945 if ordersData[i].UseOrderCount >= 0 { 1018 if ordersData[i].UseOrderCount >= 0 {
946 - m["use_order_count"] = fmt.Sprint(ordersData[i].UseOrderCount) 1019 + m["quantityControl"] = fmt.Sprint(ordersData[i].UseOrderCount)
947 } 1020 }
948 if ordersData[i].UseOrderAmount >= 0 { 1021 if ordersData[i].UseOrderAmount >= 0 {
949 - m["use_order_amount"] = fmt.Sprintf("%10.2f", ordersData[i].UseOrderAmount) 1022 + m["priceControl"] = fmt.Sprintf("%10.2f", ordersData[i].UseOrderAmount)
950 } 1023 }
951 resultMaps = append(resultMaps, m) 1024 resultMaps = append(resultMaps, m)
952 } 1025 }
953 - column := [][2]string{  
954 - [2]string{"num", "序号"},  
955 - [2]string{"order_code", "订单号"},  
956 - [2]string{"delivery_code", "发货单号"},  
957 - [2]string{"create_time", "创建时间"},  
958 - [2]string{"update_time", "更新时间"},  
959 - [2]string{"plan_order_count", "订单数量"},  
960 - [2]string{"use_order_count", "数量调整"},  
961 - [2]string{"plan_order_amount", "订单金额"},  
962 - [2]string{"use_order_amount", "金额调整"},  
963 - [2]string{"region_name", "订单区域"},  
964 - [2]string{"partner_category", "合伙人类型"},  
965 - [2]string{"buyer_name", "客户"},  
966 - [2]string{"partner_name", "合伙人"}, 1026 +
  1027 + //column := [][2]string{
  1028 + // [2]string{"num", "序号"},
  1029 + // [2]string{"order_code", "订单号"},
  1030 + // [2]string{"delivery_code", "发货单号"},
  1031 + // [2]string{"create_time", "创建时间"},
  1032 + // [2]string{"update_time", "更新时间"},
  1033 + // [2]string{"sale_date", "销售时间"},
  1034 + // [2]string{"plan_order_count", "订单数量"},
  1035 + // [2]string{"use_order_count", "数量调整"},
  1036 + // [2]string{"plan_order_amount", "订单金额"},
  1037 + // [2]string{"use_order_amount", "金额调整"},
  1038 + // [2]string{"region_name", "订单区域"},
  1039 + // [2]string{"partner_category", "合伙人类型"},
  1040 + // [2]string{"buyer_name", "客户"},
  1041 + // [2]string{"partner_name", "合伙人"},
  1042 + //}
  1043 +
  1044 + var column [][2]string
  1045 + for _, columnValue := range columnSettingFound.Value {
  1046 + column = append(column, [2]string{columnValue.Id, columnValue.ParamCn})
967 } 1047 }
  1048 +
968 return resultMaps, column, nil 1049 return resultMaps, column, nil
969 } 1050 }
970 1051
971 /** 1052 /**
972 * @Author SteveChan 1053 * @Author SteveChan
973 - * @Description //TODO 批量导入创建订单 1054 + * @Description // 批量导入创建订单,增加销售时间
974 * @Date 11:00 2021/1/7 1055 * @Date 11:00 2021/1/7
975 * @Param 1056 * @Param
976 * @return 1057 * @return
@@ -1122,6 +1203,7 @@ func (service OrderInfoService) CreateNewOrderByImport(createOrderCommands []*co @@ -1122,6 +1203,7 @@ func (service OrderInfoService) CreateNewOrderByImport(createOrderCommands []*co
1122 PartnerInfo: partnerData.Partner, 1203 PartnerInfo: partnerData.Partner,
1123 SalesmanBonusPercent: cmd.SalesmanBonusPercent, 1204 SalesmanBonusPercent: cmd.SalesmanBonusPercent,
1124 CompanyId: cmd.CompanyId, 1205 CompanyId: cmd.CompanyId,
  1206 + SaleDate: cmd.SaleDate,
1125 } 1207 }
1126 1208
1127 // 批量校验合伙人分类数据 1209 // 批量校验合伙人分类数据
@@ -85,6 +85,13 @@ func (s SyncOrderService) SyncOrderFromBestshop(cmd command.CreateOrderFromBests @@ -85,6 +85,13 @@ func (s SyncOrderService) SyncOrderFromBestshop(cmd command.CreateOrderFromBests
85 return err 85 return err
86 } 86 }
87 87
  88 +/**
  89 + * @Author SteveChan
  90 + * @Description //同步小程序订单,增加销售时间
  91 + * @Date 23:53 2021/1/26
  92 + * @Param
  93 + * @return
  94 + **/
88 func (s SyncOrderService) CreateOrderFromBestshop(cmd command.CreateOrderFromBestshop) error { 95 func (s SyncOrderService) CreateOrderFromBestshop(cmd command.CreateOrderFromBestshop) error {
89 var ( 96 var (
90 transactionContext, _ = factory.CreateTransactionContext(nil) 97 transactionContext, _ = factory.CreateTransactionContext(nil)
@@ -258,6 +265,8 @@ func (s SyncOrderService) copyOrderBestshopToOrderBase(orderBestshop *domain.Ord @@ -258,6 +265,8 @@ func (s SyncOrderService) copyOrderBestshopToOrderBase(orderBestshop *domain.Ord
258 // 默认设定为事业合伙人订单 265 // 默认设定为事业合伙人订单
259 orderbase.PartnerCategory = domain.PartnerCategory{Id: 1, Name: "事业合伙人"} 266 orderbase.PartnerCategory = domain.PartnerCategory{Id: 1, Name: "事业合伙人"}
260 orderbase.Compute() 267 orderbase.Compute()
  268 + // 销售日期
  269 + //orderbase.SaleDate = orderBestshop.CreateTime
261 err = orderBaseRepository.Save(&orderbase) 270 err = orderBaseRepository.Save(&orderbase)
262 if err != nil { 271 if err != nil {
263 e := fmt.Sprintf("添加order_base数据失败%s", err) 272 e := fmt.Sprintf("添加order_base数据失败%s", err)
@@ -4,6 +4,7 @@ import ( @@ -4,6 +4,7 @@ import (
4 "encoding/json" 4 "encoding/json"
5 "errors" 5 "errors"
6 "fmt" 6 "fmt"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant"
7 "time" 8 "time"
8 9
9 "github.com/astaxie/beego/logs" 10 "github.com/astaxie/beego/logs"
@@ -85,6 +86,13 @@ func NewSyncEmployeeService(option map[string]interface{}) *SyncEmployeeService @@ -85,6 +86,13 @@ func NewSyncEmployeeService(option map[string]interface{}) *SyncEmployeeService
85 86
86 var _ SyncAction = (*SyncEmployeeService)(nil) 87 var _ SyncAction = (*SyncEmployeeService)(nil)
87 88
  89 +/**
  90 + * @Author SteveChan
  91 + * @Description //TODO 新增、导入用户初始化栏目设置
  92 + * @Date 23:54 2021/1/26
  93 + * @Param
  94 + * @return
  95 + **/
88 func (service SyncEmployeeService) DoAction(action string, byteData []byte) error { 96 func (service SyncEmployeeService) DoAction(action string, byteData []byte) error {
89 switch action { 97 switch action {
90 case "add": 98 case "add":
@@ -157,6 +165,13 @@ func (service SyncEmployeeService) DoAction(action string, byteData []byte) erro @@ -157,6 +165,13 @@ func (service SyncEmployeeService) DoAction(action string, byteData []byte) erro
157 } 165 }
158 } 166 }
159 167
  168 +/**
  169 + * @Author SteveChan
  170 + * @Description //TODO 初始化栏目设置
  171 + * @Date 00:07 2021/1/27
  172 + * @Param
  173 + * @return
  174 + **/
160 //addEmployeeData 添加用户 175 //addEmployeeData 添加用户
161 func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error { 176 func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error {
162 var ( 177 var (
@@ -167,7 +182,7 @@ func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error { @@ -167,7 +182,7 @@ func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error {
167 return err 182 return err
168 } 183 }
169 defer func() { 184 defer func() {
170 - transactionContext.RollbackTransaction() 185 + _ = transactionContext.RollbackTransaction()
171 }() 186 }()
172 var usersRepository domain.UsersRepository 187 var usersRepository domain.UsersRepository
173 if usersRepository, err = factory.CreateUsersRepository(map[string]interface{}{ 188 if usersRepository, err = factory.CreateUsersRepository(map[string]interface{}{
@@ -175,6 +190,12 @@ func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error { @@ -175,6 +190,12 @@ func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error {
175 }); err != nil { 190 }); err != nil {
176 return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) 191 return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
177 } 192 }
  193 + var columnSettingRepository domain.ColumnSettingRepository
  194 + if columnSettingRepository, err = factory.CreateColumnSettingRepository(map[string]interface{}{
  195 + "transactionContext": transactionContext,
  196 + }); err != nil {
  197 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  198 + }
178 for i := range datas { 199 for i := range datas {
179 data := datas[i] 200 data := datas[i]
180 newUser := domain.Users{ 201 newUser := domain.Users{
@@ -202,7 +223,24 @@ func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error { @@ -202,7 +223,24 @@ func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error {
202 if err = usersRepository.Add(&newUser); err != nil { 223 if err = usersRepository.Add(&newUser); err != nil {
203 return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) 224 return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
204 } 225 }
  226 +
  227 + // 初始化栏目设置
  228 + newColumnSetting := &domain.ColumnSetting{
  229 + Description: "订单管理栏目设置",
  230 + UserName: data.Name,
  231 + CompanyId: int(data.CompanyId),
  232 + Uid: data.Id,
  233 + Key: constant.ORDER_BASE, // 订单栏目模块名称
  234 + Value: domain.DefaultColumns, // 栏目值数组,创建用户时使用默认栏目设置
  235 + InvalidValue: domain.DefaultInvalidColumns, // 初始化无效栏目数组
  236 + CreatedAt: time.Now(),
  237 + UpdatedAt: time.Now(),
  238 + }
  239 + if _, err = columnSettingRepository.Save(newColumnSetting); err != nil {
  240 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  241 + }
205 } 242 }
  243 +
206 err = transactionContext.CommitTransaction() 244 err = transactionContext.CommitTransaction()
207 return err 245 return err
208 } 246 }
@@ -303,7 +341,7 @@ func (service SyncEmployeeService) deleteEmployeeData(data DeleteUserData) error @@ -303,7 +341,7 @@ func (service SyncEmployeeService) deleteEmployeeData(data DeleteUserData) error
303 return err 341 return err
304 } 342 }
305 defer func() { 343 defer func() {
306 - transactionContext.RollbackTransaction() 344 + _ = transactionContext.RollbackTransaction()
307 }() 345 }()
308 var usersRepository domain.UsersRepository 346 var usersRepository domain.UsersRepository
309 if usersRepository, err = factory.CreateUsersRepository(map[string]interface{}{ 347 if usersRepository, err = factory.CreateUsersRepository(map[string]interface{}{
@@ -314,6 +352,25 @@ func (service SyncEmployeeService) deleteEmployeeData(data DeleteUserData) error @@ -314,6 +352,25 @@ func (service SyncEmployeeService) deleteEmployeeData(data DeleteUserData) error
314 if err = usersRepository.Remove(data.Ids); err != nil { 352 if err = usersRepository.Remove(data.Ids); err != nil {
315 return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) 353 return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
316 } 354 }
  355 + // TODO 删除栏目设置
  356 + var columnSettingRepository domain.ColumnSettingRepository
  357 + if value, errFac := factory.CreateColumnSettingRepository(map[string]interface{}{
  358 + "transactionContext": transactionContext,
  359 + }); errFac != nil {
  360 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  361 + } else {
  362 + columnSettingRepository = value
  363 + }
  364 + _, columnSettingsFound, err := columnSettingRepository.Find(map[string]interface{}{"ids": data.Ids, "companyId": data.CompanyId})
  365 + if err != nil {
  366 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  367 + }
  368 + if len(columnSettingsFound) == 0 {
  369 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  370 + }
  371 + if _, _, errRm := columnSettingRepository.Remove(nil, columnSettingsFound); errRm != nil {
  372 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, errRm.Error())
  373 + }
317 err = transactionContext.CommitTransaction() 374 err = transactionContext.CommitTransaction()
318 return err 375 return err
319 } 376 }
@@ -328,7 +385,7 @@ func (service SyncEmployeeService) updateUsersStatus(data ForbidAllowUserData) e @@ -328,7 +385,7 @@ func (service SyncEmployeeService) updateUsersStatus(data ForbidAllowUserData) e
328 return err 385 return err
329 } 386 }
330 defer func() { 387 defer func() {
331 - transactionContext.RollbackTransaction() 388 + _ = transactionContext.RollbackTransaction()
332 }() 389 }()
333 var uDao *dao.UsersDao 390 var uDao *dao.UsersDao
334 if uDao, err = factory.CreateUsersDao(map[string]interface{}{ 391 if uDao, err = factory.CreateUsersDao(map[string]interface{}{
@@ -16,11 +16,15 @@ var ( @@ -16,11 +16,15 @@ var (
16 UCENTER_CHECK_ALT = "rsF0pL!6DwjBO735" 16 UCENTER_CHECK_ALT = "rsF0pL!6DwjBO735"
17 ) 17 )
18 18
  19 +// 栏目常量设置
  20 +var ORDER_BASE = "order_base" // 订单管理栏目
  21 +
19 var ( 22 var (
20 BUSINESS_ADMIN_HOST = "http://suplus-business-admin-test.fjmaimaimai.com" //企业平台的地址 23 BUSINESS_ADMIN_HOST = "http://suplus-business-admin-test.fjmaimaimai.com" //企业平台的地址
21 ) 24 )
22 25
23 -var EXCEL_COLUMN = 12 26 +// 导入excel文件列总数
  27 +var EXCEL_COLUMN = 13
24 28
25 func init() { 29 func init() {
26 if os.Getenv("LOG_LEVEL") != "" { 30 if os.Getenv("LOG_LEVEL") != "" {
@@ -4,10 +4,10 @@ import "os" @@ -4,10 +4,10 @@ import "os"
4 4
5 var POSTGRESQL_DB_NAME = "partner_test" 5 var POSTGRESQL_DB_NAME = "partner_test"
6 var POSTGRESQL_USER = "postgres" 6 var POSTGRESQL_USER = "postgres"
7 -var POSTGRESQL_PASSWORD = "1993618jack" // eagle1010  
8 -var POSTGRESQL_HOST = "127.0.0.1" // 114.55.200.59  
9 -var POSTGRESQL_PORT = "5432" // 31543  
10 -var DISABLE_CREATE_TABLE = true 7 +var POSTGRESQL_PASSWORD = "1993618jack" // eagle1010 1993618jack
  8 +var POSTGRESQL_HOST = "127.0.0.1" // 114.55.200.59 127.0.0.1
  9 +var POSTGRESQL_PORT = "5432" // 31543 5432
  10 +var DISABLE_CREATE_TABLE = false
11 var DISABLE_SQL_GENERATE_PRINT = false 11 var DISABLE_SQL_GENERATE_PRINT = false
12 12
13 func init() { 13 func init() {
  1 +/**
  2 + @author: stevechan
  3 + @date: 2021/1/26
  4 + @note:
  5 +**/
  6 +
  7 +package domain
  8 +
  9 +// 栏目项值对象
  10 +type Column struct {
  11 + // 列标记
  12 + Id string `json:"id"`
  13 + // 列标记中文
  14 + ParamCn string `json:"paramCn"`
  15 + // 列标记是否固定,1:固定,2:不固定
  16 + ParamFix int `json:"paramFix"`
  17 +}
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +// 默认选中栏目
  6 +var DefaultColumns = []Column{
  7 + {
  8 + Id: "index",
  9 + ParamCn: "序号",
  10 + ParamFix: 1,
  11 + }, {
  12 + Id: "orderId",
  13 + ParamCn: "订单号",
  14 + ParamFix: 1,
  15 + }, {
  16 + Id: "shipmentsId",
  17 + ParamCn: "发货单号",
  18 + ParamFix: 2,
  19 + }, {
  20 + Id: "saleDate",
  21 + ParamCn: "销售日期",
  22 + ParamFix: 2,
  23 + }, {
  24 + Id: "orderNum",
  25 + ParamCn: "订单数量",
  26 + ParamFix: 2,
  27 + }, {
  28 + Id: "quantityControl",
  29 + ParamCn: "数量调整",
  30 + ParamFix: 2,
  31 + }, {
  32 + Id: "orderPrice",
  33 + ParamCn: "订单金额",
  34 + ParamFix: 2,
  35 + }, {
  36 + Id: "priceControl",
  37 + ParamCn: "金额调整",
  38 + ParamFix: 2,
  39 + }, {
  40 + Id: "orderDist",
  41 + ParamCn: "订单区域",
  42 + ParamFix: 2,
  43 + }, {
  44 + Id: "partnerCategory",
  45 + ParamCn: "合伙人类型",
  46 + ParamFix: 2,
  47 + }, {
  48 + Id: "buyer",
  49 + ParamCn: "客户",
  50 + ParamFix: 2,
  51 + }, {
  52 + Id: "partner",
  53 + ParamCn: "合伙人",
  54 + ParamFix: 2,
  55 + },
  56 +}
  57 +
  58 +// 默认未选中栏目
  59 +var DefaultInvalidColumns = []Column{
  60 + {
  61 + Id: "updateTime",
  62 + ParamCn: "更新时间",
  63 + ParamFix: 2,
  64 + }, {
  65 + Id: "createTime",
  66 + ParamCn: "创建时间",
  67 + ParamFix: 2,
  68 + },
  69 +}
  70 +
  71 +// 栏目设置
  72 +type ColumnSetting struct {
  73 + // 栏目设置id
  74 + Id int64 `json:"id"`
  75 + // 栏目设置关联用户公司id
  76 + CompanyId int `json:"companyId"`
  77 + // 栏目设置创建时间
  78 + CreatedAt time.Time `json:"createdAt"`
  79 + // 栏目设置描述
  80 + Description string `json:"description"`
  81 + // 栏目设置模块名称
  82 + Key string `json:"key"`
  83 + // 栏目设置关联用户uid
  84 + Uid int64 `json:"uid"`
  85 + // 栏目设置更新时间
  86 + UpdatedAt time.Time `json:"updatedAt"`
  87 + // 栏目设置关联用户名称
  88 + UserName string `json:"userName"`
  89 + // 有效栏目数组
  90 + Value []Column `json:"value"`
  91 + // 无效栏目数组
  92 + InvalidValue []Column `json:"invalidValue"`
  93 +}
  94 +
  95 +type ColumnSettingRepository interface {
  96 + Save(columnSetting *ColumnSetting) (*ColumnSetting, error)
  97 + Remove(columnSetting *ColumnSetting, columnSettings []*ColumnSetting) (*ColumnSetting, []*ColumnSetting, error)
  98 + FindOne(queryOptions map[string]interface{}) (*ColumnSetting, error)
  99 + Find(queryOptions map[string]interface{}) (int64, []*ColumnSetting, error)
  100 +}
  101 +
  102 +func (columnSetting *ColumnSetting) Identify() interface{} {
  103 + if columnSetting.Id == 0 {
  104 + return nil
  105 + }
  106 + return columnSetting.Id
  107 +}
  108 +
  109 +func (columnSetting *ColumnSetting) Update(data map[string]interface{}) error {
  110 + if companyId, ok := data["companyId"]; ok {
  111 + columnSetting.CompanyId = companyId.(int)
  112 + }
  113 + if createdAt, ok := data["createdAt"]; ok {
  114 + columnSetting.CreatedAt = createdAt.(time.Time)
  115 + }
  116 + if description, ok := data["description"]; ok {
  117 + columnSetting.Description = description.(string)
  118 + }
  119 + if key, ok := data["key"]; ok {
  120 + columnSetting.Key = key.(string)
  121 + }
  122 + if uid, ok := data["uid"]; ok {
  123 + columnSetting.Uid = uid.(int64)
  124 + }
  125 + if updatedAt, ok := data["updatedAt"]; ok {
  126 + columnSetting.UpdatedAt = updatedAt.(time.Time)
  127 + }
  128 + if userName, ok := data["userName"]; ok {
  129 + columnSetting.UserName = userName.(string)
  130 + }
  131 + if value, ok := data["value"]; ok {
  132 + columnSetting.Value = value.([]Column)
  133 + }
  134 + if invalidValue, ok := data["invalidValue"]; ok {
  135 + columnSetting.InvalidValue = invalidValue.([]Column)
  136 + }
  137 + return nil
  138 +}
@@ -90,7 +90,8 @@ type OrderBase struct { @@ -90,7 +90,8 @@ type OrderBase struct {
90 //订单区域信息 90 //订单区域信息
91 RegionInfo RegionInfo `json:"regionInfo"` 91 RegionInfo RegionInfo `json:"regionInfo"`
92 //订单对应的合伙人 92 //订单对应的合伙人
93 - PartnerId int64 `json:"partnerId"` 93 + PartnerId int64 `json:"partnerId"`
  94 + //合伙人信息
94 PartnerInfo Partner `json:"partnerInfo"` 95 PartnerInfo Partner `json:"partnerInfo"`
95 //业务员抽成比例 96 //业务员抽成比例
96 SalesmanBonusPercent float64 `json:"salesmanBonusPercent"` 97 SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
@@ -116,6 +117,8 @@ type OrderBase struct { @@ -116,6 +117,8 @@ type OrderBase struct {
116 Remark OrderBaseRemark `json:"remark"` 117 Remark OrderBaseRemark `json:"remark"`
117 //合伙人类型 118 //合伙人类型
118 PartnerCategory PartnerCategory `json:"partnerCategory"` 119 PartnerCategory PartnerCategory `json:"partnerCategory"`
  120 + //销售日期
  121 + SaleDate time.Time `json:"saleDate"`
119 } 122 }
120 123
121 //GetCurrentPartnerBonus 获取当前合伙人应收分红 124 //GetCurrentPartnerBonus 获取当前合伙人应收分红
@@ -327,7 +330,7 @@ type GoodErrInfo struct { @@ -327,7 +330,7 @@ type GoodErrInfo struct {
327 330
328 type OrderBaseRepository interface { 331 type OrderBaseRepository interface {
329 Save(order *OrderBase) error 332 Save(order *OrderBase) error
330 - FindOne(qureyOptions OrderBaseFindOneQuery) (*OrderBase, error) 333 + FindOne(queryOptions OrderBaseFindOneQuery) (*OrderBase, error)
331 Find(queryOptions OrderBaseFindQuery) ([]OrderBase, int, error) 334 Find(queryOptions OrderBaseFindQuery) ([]OrderBase, int, error)
332 Remove(id int64, companyId int64) error 335 Remove(id int64, companyId int64) error
333 } 336 }
@@ -21,7 +21,7 @@ type OrderBestShop struct { @@ -21,7 +21,7 @@ type OrderBestShop struct {
21 BuyerAddress string `json:"buyerAddress"` 21 BuyerAddress string `json:"buyerAddress"`
22 //买家备注 22 //买家备注
23 BuyerRemark string `json:"buyerRemark"` 23 BuyerRemark string `json:"buyerRemark"`
24 - // 24 + //客户id
25 BuyerId int64 `json:"buyerId"` 25 BuyerId int64 `json:"buyerId"`
26 //商品总数 26 //商品总数
27 OrderCount int `json:"orderCount"` 27 OrderCount int `json:"orderCount"`
@@ -30,12 +30,16 @@ type OrderBestShop struct { @@ -30,12 +30,16 @@ type OrderBestShop struct {
30 //发货时间 30 //发货时间
31 DeliveryTime string `json:"deliveryTime"` 31 DeliveryTime string `json:"deliveryTime"`
32 //创建时间 32 //创建时间
33 - CreateTime time.Time `json:"createTime"`  
34 - PartnerId int64 `json:"partnerId"`  
35 - Goods []OrderGoodBestShop `json:"goods"` 33 + CreateTime time.Time `json:"createTime"`
  34 + //合伙人id
  35 + PartnerId int64 `json:"partnerId"`
  36 + //订单产品
  37 + Goods []OrderGoodBestShop `json:"goods"`
36 //是否将数据同步到 order_base ,order_good 38 //是否将数据同步到 order_base ,order_good
37 - IsCopy bool `json:"isCopy"`  
38 - CompanyId int64 `json:"companyId"` 39 + IsCopy bool `json:"isCopy"`
  40 + //公司id
  41 + CompanyId int64 `json:"companyId"`
  42 + //订单区域
39 OrderArea string `json:"orderArea"` 43 OrderArea string `json:"orderArea"`
40 } 44 }
41 45
@@ -55,6 +59,7 @@ func (order OrderBestShop) CopyToOrderBase(o *OrderBase) { @@ -55,6 +59,7 @@ func (order OrderBestShop) CopyToOrderBase(o *OrderBase) {
55 o.OrderCompute.PlanOrderAmount = order.OrderAmount 59 o.OrderCompute.PlanOrderAmount = order.OrderAmount
56 o.OrderCompute.PlanOrderCount = order.OrderCount 60 o.OrderCompute.PlanOrderCount = order.OrderCount
57 o.DeliveryTime, _ = time.Parse("2006-01-02 15:04:05", order.DeliveryTime) 61 o.DeliveryTime, _ = time.Parse("2006-01-02 15:04:05", order.DeliveryTime)
  62 + o.SaleDate = order.CreateTime
58 o.RegionInfo.RegionName = order.OrderArea 63 o.RegionInfo.RegionName = order.OrderArea
59 return 64 return
60 } 65 }
@@ -191,7 +191,7 @@ func (dao OrderBaseDao) OrderBonusListForExcel(companyId int64, orderType int, p @@ -191,7 +191,7 @@ func (dao OrderBaseDao) OrderBonusListForExcel(companyId int64, orderType int, p
191 //@param updateTime 订单更新时间范围"[开始时间,结束时间]",时间格式"2006-01-02 15:04:05+07" 191 //@param updateTime 订单更新时间范围"[开始时间,结束时间]",时间格式"2006-01-02 15:04:05+07"
192 //@param createTime 订单的创建时间范围"[开始时间,结束时间]" 时间格式"2006-01-02 15:04:05+07" 192 //@param createTime 订单的创建时间范围"[开始时间,结束时间]" 时间格式"2006-01-02 15:04:05+07"
193 func (dao OrderBaseDao) OrderListByCondition(companyId int64, orderType int, partnerName string, orderCode string, deliveryCode string, 193 func (dao OrderBaseDao) OrderListByCondition(companyId int64, orderType int, partnerName string, orderCode string, deliveryCode string,
194 - updateTime [2]string, createTime [2]string, partnerCategory int, limit, offset int) ([]models.OrderBase, int, error) { 194 + updateTime [2]string, createTime [2]string, saleDate [2]string, partnerCategory int, partnerCategoryName string, limit, offset int) ([]models.OrderBase, int, error) {
195 tx := dao.transactionContext.GetDB() 195 tx := dao.transactionContext.GetDB()
196 var orders []models.OrderBase 196 var orders []models.OrderBase
197 query := tx.Model(&orders).Where("order_base.company_id=?", companyId) 197 query := tx.Model(&orders).Where("order_base.company_id=?", companyId)
@@ -203,6 +203,9 @@ func (dao OrderBaseDao) OrderListByCondition(companyId int64, orderType int, par @@ -203,6 +203,9 @@ func (dao OrderBaseDao) OrderListByCondition(companyId int64, orderType int, par
203 if partnerCategory > 0 { 203 if partnerCategory > 0 {
204 query = query.Where(`order_base.partner_category@>'{"id":?}'`, partnerCategory) 204 query = query.Where(`order_base.partner_category@>'{"id":?}'`, partnerCategory)
205 } 205 }
  206 + if partnerCategoryName != "" {
  207 + query = query.Where(`order_base.partner_category->>'name' like ?`, "%"+partnerCategoryName+"%")
  208 + }
206 if len(updateTime[0]) > 0 { 209 if len(updateTime[0]) > 0 {
207 query = query.Where(`order_base.update_time>=?`, updateTime[0]) 210 query = query.Where(`order_base.update_time>=?`, updateTime[0])
208 } 211 }
@@ -215,6 +218,12 @@ func (dao OrderBaseDao) OrderListByCondition(companyId int64, orderType int, par @@ -215,6 +218,12 @@ func (dao OrderBaseDao) OrderListByCondition(companyId int64, orderType int, par
215 if len(createTime[1]) > 0 { 218 if len(createTime[1]) > 0 {
216 query = query.Where(`order_base.create_time<=?`, createTime[1]) 219 query = query.Where(`order_base.create_time<=?`, createTime[1])
217 } 220 }
  221 + if len(saleDate[0]) > 0 {
  222 + query = query.Where(`order_base.sale_date>=?`, saleDate[0])
  223 + }
  224 + if len(saleDate[1]) > 0 {
  225 + query = query.Where(`order_base.sale_date<=?`, saleDate[1])
  226 + }
218 if len(partnerName) > 0 { 227 if len(partnerName) > 0 {
219 query = query.Join("LEFT JOIN partner_info as p ON order_base.partner_id=p.id"). 228 query = query.Join("LEFT JOIN partner_info as p ON order_base.partner_id=p.id").
220 Where("p.partner_name like ? ", "%"+partnerName+"%") 229 Where("p.partner_name like ? ", "%"+partnerName+"%")
@@ -249,6 +258,7 @@ type CustomOrderListForExcel struct { @@ -249,6 +258,7 @@ type CustomOrderListForExcel struct {
249 DeliveryCode string //发货编号 258 DeliveryCode string //发货编号
250 UpdateTime string //更新时间 259 UpdateTime string //更新时间
251 CreateTime string //创建时间 260 CreateTime string //创建时间
  261 + SaleDate string // 销售时间
252 PlanOrderCount int64 //货品总数 262 PlanOrderCount int64 //货品总数
253 UseOrderCount int64 //货品总数调整 263 UseOrderCount int64 //货品总数调整
254 RegionName string //订单区域 264 RegionName string //订单区域
@@ -259,6 +269,13 @@ type CustomOrderListForExcel struct { @@ -259,6 +269,13 @@ type CustomOrderListForExcel struct {
259 PartnerName string //合伙人 269 PartnerName string //合伙人
260 } 270 }
261 271
  272 +/**
  273 + * @Author SteveChan
  274 + * @Description // 导出到excel
  275 + * @Date 23:45 2021/1/26
  276 + * @Param
  277 + * @return
  278 + **/
262 //OrderListForExcel 获取实际订单列表用于excel导出 279 //OrderListForExcel 获取实际订单列表用于excel导出
263 //@param companyId 公司id 280 //@param companyId 公司id
264 //@param orderType 订单类型 281 //@param orderType 订单类型
@@ -267,12 +284,13 @@ type CustomOrderListForExcel struct { @@ -267,12 +284,13 @@ type CustomOrderListForExcel struct {
267 //@param updateTime 订单更新时间范围"[开始时间,结束时间]",时间格式"2006-01-02 15:04:05+07" 284 //@param updateTime 订单更新时间范围"[开始时间,结束时间]",时间格式"2006-01-02 15:04:05+07"
268 //@param createTime 订单的创建时间范围"[开始时间,结束时间]" 时间格式"2006-01-02 15:04:05+07" 285 //@param createTime 订单的创建时间范围"[开始时间,结束时间]" 时间格式"2006-01-02 15:04:05+07"
269 func (dao OrderBaseDao) OrderListForExcel(companyId int64, partnerName string, orderCode string, deliveryCode string, 286 func (dao OrderBaseDao) OrderListForExcel(companyId int64, partnerName string, orderCode string, deliveryCode string,
270 - updateTime [2]string, createTime [2]string, partnerCategory int) ( 287 + updateTime [2]string, createTime [2]string, saleDate [2]string, partnerCategory int, partnerCategoryName string) (
271 result []CustomOrderListForExcel, err error) { 288 result []CustomOrderListForExcel, err error) {
272 sqlstr := ` 289 sqlstr := `
273 SELECT t1.order_code,t1.delivery_code 290 SELECT t1.order_code,t1.delivery_code
274 ,to_char(t1.create_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS create_time 291 ,to_char(t1.create_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS create_time
275 ,to_char(t1.update_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS update_time 292 ,to_char(t1.update_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS update_time
  293 + ,to_char(t1.sale_date AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS sale_date
276 ,t1.plan_order_count,t1.use_order_count,t1.plan_order_amount,t1.use_order_amount 294 ,t1.plan_order_count,t1.use_order_count,t1.plan_order_amount,t1.use_order_amount
277 ,t1.region_info->'regionName' AS region_name,t1.buyer->'buyerName' AS buyer_name 295 ,t1.region_info->'regionName' AS region_name,t1.buyer->'buyerName' AS buyer_name
278 ,t1.partner_category->'name' AS partner_category 296 ,t1.partner_category->'name' AS partner_category
@@ -306,17 +324,18 @@ func (dao OrderBaseDao) OrderListForExcel(companyId int64, partnerName string, o @@ -306,17 +324,18 @@ func (dao OrderBaseDao) OrderListForExcel(companyId int64, partnerName string, o
306 params = append(params, partnerCategory) 324 params = append(params, partnerCategory)
307 sqlstr += ` AND t1.partner_category@>'{"id":?}' ` 325 sqlstr += ` AND t1.partner_category@>'{"id":?}' `
308 } 326 }
309 - 327 + if len(partnerCategoryName) > 0 {
  328 + params = append(params, partnerCategoryName)
  329 + sqlstr += ` AND t1.partner_category->> 'name' like ?`
  330 + }
310 if len(updateTime[0]) > 0 { 331 if len(updateTime[0]) > 0 {
311 params = append(params, updateTime[0]) 332 params = append(params, updateTime[0])
312 sqlstr += ` AND t1.update_time>=? ` 333 sqlstr += ` AND t1.update_time>=? `
313 } 334 }
314 -  
315 if len(updateTime[1]) > 0 { 335 if len(updateTime[1]) > 0 {
316 params = append(params, updateTime[1]) 336 params = append(params, updateTime[1])
317 sqlstr += ` AND t1.update_time<=? ` 337 sqlstr += ` AND t1.update_time<=? `
318 } 338 }
319 -  
320 if len(createTime[0]) > 0 { 339 if len(createTime[0]) > 0 {
321 params = append(params, createTime[0]) 340 params = append(params, createTime[0])
322 sqlstr += ` AND t1.create_time>=? ` 341 sqlstr += ` AND t1.create_time>=? `
@@ -325,6 +344,14 @@ func (dao OrderBaseDao) OrderListForExcel(companyId int64, partnerName string, o @@ -325,6 +344,14 @@ func (dao OrderBaseDao) OrderListForExcel(companyId int64, partnerName string, o
325 params = append(params, createTime[1]) 344 params = append(params, createTime[1])
326 sqlstr += ` AND t1.create_time<=? ` 345 sqlstr += ` AND t1.create_time<=? `
327 } 346 }
  347 + if len(saleDate[0]) > 0 {
  348 + params = append(params, saleDate[0])
  349 + sqlstr += ` AND t1.sale_date>=? `
  350 + }
  351 + if len(saleDate[1]) > 0 {
  352 + params = append(params, saleDate[1])
  353 + sqlstr += ` AND t1.sale_date<=? `
  354 + }
328 sqlstr += ` ORDER BY t1.create_time DESC limit 10000 ` 355 sqlstr += ` ORDER BY t1.create_time DESC limit 10000 `
329 tx := dao.transactionContext.GetDB() 356 tx := dao.transactionContext.GetDB()
330 _, err = tx.Query(&result, sqlstr, params...) 357 _, err = tx.Query(&result, sqlstr, params...)
@@ -5,7 +5,9 @@ import ( @@ -5,7 +5,9 @@ import (
5 "fmt" 5 "fmt"
6 6
7 "github.com/go-pg/pg/v10" 7 "github.com/go-pg/pg/v10"
  8 + "github.com/go-pg/pg/v10/orm"
8 "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant" 9 "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
9 "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/log" 11 "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/log"
10 ) 12 )
11 13
@@ -21,6 +23,31 @@ func init() { @@ -21,6 +23,31 @@ func init() {
21 if !constant.DISABLE_SQL_GENERATE_PRINT { 23 if !constant.DISABLE_SQL_GENERATE_PRINT {
22 DB.AddQueryHook(SqlGeneratePrintHook{}) 24 DB.AddQueryHook(SqlGeneratePrintHook{})
23 } 25 }
  26 + if !constant.DISABLE_CREATE_TABLE {
  27 + for _, model := range []interface{}{
  28 + &models.ColumnSetting{},
  29 + &models.AdminPermission{},
  30 + &models.BusinessBonus{},
  31 + &models.Company{},
  32 + &models.OrderBase{},
  33 + &models.OrderBestshop{},
  34 + &models.OrderGood{},
  35 + &models.OrderGoodBestshop{},
  36 + &models.OrderLog{},
  37 + &models.PartnerCategoryInfo{},
  38 + &models.PartnerInfo{},
  39 + &models.Users{},
  40 + } {
  41 + err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
  42 + Temp: false,
  43 + IfNotExists: true,
  44 + FKConstraints: true,
  45 + })
  46 + if err != nil {
  47 + panic(err)
  48 + }
  49 + }
  50 + }
24 } 51 }
25 52
26 type SqlGeneratePrintHook struct{} 53 type SqlGeneratePrintHook struct{}
  1 +package models
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  5 + "time"
  6 +)
  7 +
  8 +type ColumnSetting struct {
  9 + // 栏目设置id
  10 + Id int64
  11 + // 栏目设置关联用户公司id
  12 + CompanyId int
  13 + // 栏目设置创建时间
  14 + CreatedAt time.Time
  15 + // 栏目设置描述
  16 + Description string
  17 + // 栏目设置模块名称
  18 + Key string
  19 + // 栏目设置关联用户uid
  20 + Uid int64
  21 + // 栏目设置更新时间
  22 + UpdatedAt time.Time
  23 + // 栏目设置关联用户名称
  24 + UserName string
  25 + // 栏目数组
  26 + Value []domain.Column `pg:",array"`
  27 + // 无效栏目数组
  28 + InvalidValue []domain.Column `pg:",array"`
  29 +}
@@ -45,6 +45,8 @@ type OrderBase struct { @@ -45,6 +45,8 @@ type OrderBase struct {
45 DeliveryTime time.Time 45 DeliveryTime time.Time
46 //更新时间 46 //更新时间
47 UpdateTime time.Time 47 UpdateTime time.Time
  48 + //销售时间
  49 + SaleDate time.Time
48 //合伙人应收分红 50 //合伙人应收分红
49 PlanPartnerBonus float64 `pg:",use_zero"` 51 PlanPartnerBonus float64 `pg:",use_zero"`
50 //调整后的合伙人应收分红 (初始值=-1); 52 //调整后的合伙人应收分红 (初始值=-1);
@@ -62,7 +64,8 @@ type OrderBase struct { @@ -62,7 +64,8 @@ type OrderBase struct {
62 IsDisable int `pg:",use_zero"` 64 IsDisable int `pg:",use_zero"`
63 //分红支付状态 65 //分红支付状态
64 BonusStatus int 66 BonusStatus int
65 - CompanyId int64 67 + //公司id
  68 + CompanyId int64
66 //数据来源 69 //数据来源
67 DataFrom domain.OrderDataFrom `` 70 DataFrom domain.OrderDataFrom ``
68 //备注 71 //备注
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/go-pg/pg"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  7 +
  8 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
  10 +)
  11 +
  12 +type ColumnSettingRepository struct {
  13 + transactionContext *transaction.TransactionContext
  14 +}
  15 +
  16 +//func (repository *ColumnSettingRepository) nextIdentify() (int64, error) {
  17 +// return 0, nil
  18 +//}
  19 +
  20 +func (repository *ColumnSettingRepository) Save(columnSetting *domain.ColumnSetting) (*domain.ColumnSetting, error) {
  21 + tx := repository.transactionContext.PgTx
  22 +
  23 + columnSettingModel := &models.ColumnSetting{
  24 + Id: columnSetting.Id,
  25 + CompanyId: columnSetting.CompanyId,
  26 + CreatedAt: columnSetting.CreatedAt,
  27 + Description: columnSetting.Description,
  28 + Key: columnSetting.Key,
  29 + Uid: columnSetting.Uid,
  30 + UpdatedAt: columnSetting.UpdatedAt,
  31 + UserName: columnSetting.UserName,
  32 + Value: columnSetting.Value,
  33 + InvalidValue: columnSetting.InvalidValue,
  34 + }
  35 +
  36 + if columnSetting.Identify() == nil {
  37 + _, err := tx.Model(columnSettingModel).Insert()
  38 + if err != nil {
  39 + return nil, err
  40 + }
  41 + //_, err := repository.nextIdentify()
  42 + //if err != nil {
  43 + // return columnSetting, err
  44 + //}
  45 + //if _, errInsert := tx.QueryOne(
  46 + // pg.Scan(&columnSetting.Id, &columnSetting.CompanyId, &columnSetting.CreatedAt, &columnSetting.Description, &columnSetting.Key, &columnSetting.Uid, &columnSetting.UpdatedAt, &columnSetting.UserName, pg.Array(&columnSetting.Value), pg.Array(&columnSetting.InvalidValue)),
  47 + // "INSERT INTO column_settings (company_id, created_at, description, key, uid, updated_at, user_name, value, invalid_value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, company_id, created_at, description, key, uid, updated_at, user_name, value, invalid_value",
  48 + // columnSetting.CompanyId, columnSetting.CreatedAt, columnSetting.Description, columnSetting.Key, columnSetting.Uid, columnSetting.UpdatedAt, columnSetting.UserName, pg.Array(columnSetting.Value), pg.Array(columnSetting.InvalidValue)); errInsert != nil {
  49 + // return columnSetting, errInsert
  50 + //}
  51 + } else {
  52 + //if _, errUpdate := tx.QueryOne(
  53 + // pg.Scan(&columnSetting.Id, &columnSetting.CompanyId, &columnSetting.CreatedAt, &columnSetting.Description, &columnSetting.Key, &columnSetting.Uid, &columnSetting.UpdatedAt, &columnSetting.UserName, pg.Array(&columnSetting.Value), pg.Array(&columnSetting.InvalidValue)),
  54 + // "UPDATE column_settings SET company_id=?, created_at=?, description=?, key=?, uid=?, updated_at=?, user_name=?, value=?, invalid_value=? WHERE id=? RETURNING id, company_id, created_at, description, key, uid, updated_at, user_name, value, invalid_value",
  55 + // columnSetting.CompanyId, columnSetting.CreatedAt, columnSetting.Description, columnSetting.Key, columnSetting.Uid, columnSetting.UpdatedAt, columnSetting.UserName, pg.Array(columnSetting.Value), pg.Array(columnSetting.InvalidValue), columnSetting.Identify()); errUpdate != nil {
  56 + // return columnSetting, errUpdate
  57 + //}
  58 + _, err := tx.Model(columnSettingModel).WherePK().
  59 + Column("company_id", "created_at", "description", "key", "uid", "updated_at", "user_name", "value", "invalid_value").Update()
  60 + if err != nil {
  61 + return nil, err
  62 + }
  63 + }
  64 + return columnSetting, nil
  65 +}
  66 +
  67 +func (repository *ColumnSettingRepository) Remove(columnSetting *domain.ColumnSetting, columnSettings []*domain.ColumnSetting) (*domain.ColumnSetting, []*domain.ColumnSetting, error) {
  68 + tx := repository.transactionContext.PgTx
  69 +
  70 + if columnSetting != nil {
  71 + // 单个删除
  72 + columnSettingModel := new(models.ColumnSetting)
  73 + columnSettingModel.Id = columnSetting.Identify().(int64)
  74 + if _, err := tx.Model(columnSettingModel).WherePK().Delete(); err != nil {
  75 + return columnSetting, nil, err
  76 + }
  77 + }
  78 +
  79 + // 批量删除
  80 + if len(columnSettings) > 0 {
  81 + var columnSettingModels []*models.ColumnSetting
  82 + for _, setting := range columnSettings {
  83 + columnSettingModels = append(columnSettingModels, &models.ColumnSetting{
  84 + Id: setting.Identify().(int64),
  85 + })
  86 + }
  87 + if _, err := tx.Model(columnSettingModels).WherePK().Delete(); err != nil {
  88 + return nil, columnSettings, err
  89 + }
  90 + }
  91 + return columnSetting, columnSettings, nil
  92 +}
  93 +
  94 +func (repository *ColumnSettingRepository) FindOne(queryOptions map[string]interface{}) (*domain.ColumnSetting, error) {
  95 + tx := repository.transactionContext.PgTx
  96 + columnSettingModel := new(models.ColumnSetting)
  97 + query := tx.Model(columnSettingModel)
  98 + if columnSettingId, ok := queryOptions["column_settingId"]; ok {
  99 + query = query.Where("column_setting.id = ?", columnSettingId)
  100 + }
  101 + if uid, ok := queryOptions["uid"]; ok {
  102 + query = query.Where("column_setting.uid = ?", uid)
  103 + }
  104 + if companyId, ok := queryOptions["companyId"]; ok {
  105 + query = query.Where("column_setting.company_id = ?", companyId)
  106 + }
  107 + if err := query.First(); err != nil {
  108 + if err.Error() == "pg: no rows in result set" {
  109 + return nil, fmt.Errorf("没有此资源")
  110 + } else {
  111 + return nil, err
  112 + }
  113 + }
  114 + if columnSettingModel.Id == 0 {
  115 + return nil, nil
  116 + } else {
  117 + return repository.transformPgModelToDomainModel(columnSettingModel)
  118 + }
  119 +}
  120 +
  121 +func (repository *ColumnSettingRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ColumnSetting, error) {
  122 + tx := repository.transactionContext.PgTx
  123 + var columnSettingModels []*models.ColumnSetting
  124 + columnSettings := make([]*domain.ColumnSetting, 0)
  125 + query := tx.Model(&columnSettingModels)
  126 + if ids, ok := queryOptions["ids"]; ok {
  127 + query = query.Where("column_setting.uid IN (?)", pg.In(ids.(int64)))
  128 + }
  129 + if uid, ok := queryOptions["uid"]; ok {
  130 + query = query.Where("column_setting.uid = ?", uid)
  131 + }
  132 + if companyId, ok := queryOptions["companyId"]; ok {
  133 + query = query.Where("column_setting.company_id = ?", companyId)
  134 + }
  135 + if offset, ok := queryOptions["offset"]; ok {
  136 + queryOffset := offset.(int)
  137 + if queryOffset > -1 {
  138 + query = query.Offset(queryOffset)
  139 + }
  140 + } else {
  141 + query = query.Offset(0)
  142 + }
  143 + if limit, ok := queryOptions["limit"]; ok {
  144 + queryLimit := limit.(int)
  145 + if queryLimit > -1 {
  146 + query = query.Limit(queryLimit)
  147 + }
  148 + } else {
  149 + query = query.Limit(20)
  150 + }
  151 + if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
  152 + return 0, columnSettings, err
  153 + } else {
  154 + for _, columnSettingModel := range columnSettingModels {
  155 + if columnSetting, errTrans := repository.transformPgModelToDomainModel(columnSettingModel); errTrans != nil {
  156 + return 0, columnSettings, errTrans
  157 + } else {
  158 + columnSettings = append(columnSettings, columnSetting)
  159 + }
  160 + }
  161 + return int64(count), columnSettings, nil
  162 + }
  163 +}
  164 +
  165 +func (repository *ColumnSettingRepository) transformPgModelToDomainModel(columnSettingModel *models.ColumnSetting) (*domain.ColumnSetting, error) {
  166 + return &domain.ColumnSetting{
  167 + Id: columnSettingModel.Id,
  168 + CompanyId: columnSettingModel.CompanyId,
  169 + CreatedAt: columnSettingModel.CreatedAt,
  170 + Description: columnSettingModel.Description,
  171 + Key: columnSettingModel.Key,
  172 + Uid: columnSettingModel.Uid,
  173 + UpdatedAt: columnSettingModel.UpdatedAt,
  174 + UserName: columnSettingModel.UserName,
  175 + Value: columnSettingModel.Value, // 有效栏目设置
  176 + InvalidValue: columnSettingModel.InvalidValue, // 无效栏目设置
  177 + }, nil
  178 +}
  179 +
  180 +func NewColumnSettingRepository(transactionContext *transaction.TransactionContext) (*ColumnSettingRepository, error) {
  181 + if transactionContext == nil {
  182 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  183 + } else {
  184 + return &ColumnSettingRepository{
  185 + transactionContext: transactionContext,
  186 + }, nil
  187 + }
  188 +}
@@ -23,12 +23,13 @@ func NewOrderBaseRepository(transactionContext *transaction.TransactionContext) @@ -23,12 +23,13 @@ func NewOrderBaseRepository(transactionContext *transaction.TransactionContext)
23 return &OrderBaseRepository{transactionContext: transactionContext}, nil 23 return &OrderBaseRepository{transactionContext: transactionContext}, nil
24 } 24 }
25 25
26 -func (reponsitory OrderBaseRepository) transformPgModelToDomainModel(orderModel *models.OrderBase) (order domain.OrderBase, err error) { 26 +func (repository OrderBaseRepository) transformPgModelToDomainModel(orderModel *models.OrderBase) (order domain.OrderBase, err error) {
27 order = domain.OrderBase{ 27 order = domain.OrderBase{
28 Id: orderModel.Id, OrderType: orderModel.OrderType, OrderCode: orderModel.OrderCode, 28 Id: orderModel.Id, OrderType: orderModel.OrderType, OrderCode: orderModel.OrderCode,
29 DeliveryCode: orderModel.DeliveryCode, Buyer: orderModel.Buyer, RegionInfo: orderModel.RegionInfo, 29 DeliveryCode: orderModel.DeliveryCode, Buyer: orderModel.Buyer, RegionInfo: orderModel.RegionInfo,
30 PartnerId: orderModel.PartnerId, SalesmanBonusPercent: orderModel.SalesmanBonusPercent, 30 PartnerId: orderModel.PartnerId, SalesmanBonusPercent: orderModel.SalesmanBonusPercent,
31 CreateTime: orderModel.CreateTime, DeliveryTime: orderModel.DeliveryTime, UpdateTime: orderModel.UpdateTime, 31 CreateTime: orderModel.CreateTime, DeliveryTime: orderModel.DeliveryTime, UpdateTime: orderModel.UpdateTime,
  32 + SaleDate: orderModel.SaleDate,
32 IsDisable: orderModel.IsDisable, 33 IsDisable: orderModel.IsDisable,
33 OrderCompute: domain.OrderCompute{ 34 OrderCompute: domain.OrderCompute{
34 PlanPartnerBonus: orderModel.PlanPartnerBonus, UsePartnerBonus: orderModel.UsePartnerBonus, 35 PlanPartnerBonus: orderModel.PlanPartnerBonus, UsePartnerBonus: orderModel.UsePartnerBonus,
@@ -55,19 +56,37 @@ func (repository OrderBaseRepository) Save(orderInfo *domain.OrderBase) error { @@ -55,19 +56,37 @@ func (repository OrderBaseRepository) Save(orderInfo *domain.OrderBase) error {
55 tx = repository.transactionContext.PgTx 56 tx = repository.transactionContext.PgTx
56 ) 57 )
57 m := &models.OrderBase{ 58 m := &models.OrderBase{
58 - Id: orderInfo.Id, OrderType: orderInfo.OrderType, OrderCode: orderInfo.OrderCode,  
59 - DeliveryCode: orderInfo.DeliveryCode, Buyer: orderInfo.Buyer, RegionInfo: orderInfo.RegionInfo,  
60 - PartnerId: orderInfo.PartnerId, SalesmanBonusPercent: orderInfo.SalesmanBonusPercent,  
61 - SalesmanBonus: orderInfo.OrderCompute.SalesmanBonus, PlanOrderCount: orderInfo.OrderCompute.PlanOrderCount,  
62 - PlanOrderAmount: orderInfo.OrderCompute.PlanOrderAmount, UseOrderCount: orderInfo.OrderCompute.UseOrderCount,  
63 - UseOrderAmount: orderInfo.OrderCompute.UseOrderAmount, DeliveryTime: orderInfo.DeliveryTime,  
64 - PlanPartnerBonus: orderInfo.OrderCompute.PlanPartnerBonus, UsePartnerBonus: orderInfo.OrderCompute.UsePartnerBonus,  
65 - PartnerBonusHas: orderInfo.OrderCompute.PartnerBonusHas, PartnerBonusNot: orderInfo.OrderCompute.PartnerBonusNot,  
66 - PartnerBonusExpense: orderInfo.OrderCompute.PartnerBonusExpense, IsDisable: orderInfo.IsDisable,  
67 - CreateTime: orderInfo.CreateTime, BonusStatus: orderInfo.BonusStatus,  
68 - CompanyId: orderInfo.CompanyId, DataFrom: orderInfo.DataFrom,  
69 - Remark: orderInfo.Remark, PartnerCategory: orderInfo.PartnerCategory,  
70 - } 59 + Id: orderInfo.Id,
  60 + OrderType: orderInfo.OrderType,
  61 + OrderCode: orderInfo.OrderCode,
  62 + DeliveryCode: orderInfo.DeliveryCode,
  63 + Buyer: orderInfo.Buyer,
  64 + RegionInfo: orderInfo.RegionInfo,
  65 + PartnerId: orderInfo.PartnerId,
  66 + SalesmanBonusPercent: orderInfo.SalesmanBonusPercent,
  67 + SalesmanBonus: orderInfo.OrderCompute.SalesmanBonus,
  68 + PlanOrderCount: orderInfo.OrderCompute.PlanOrderCount,
  69 + PlanOrderAmount: orderInfo.OrderCompute.PlanOrderAmount,
  70 + UseOrderCount: orderInfo.OrderCompute.UseOrderCount,
  71 + UseOrderAmount: orderInfo.OrderCompute.UseOrderAmount,
  72 + DeliveryTime: orderInfo.DeliveryTime,
  73 + PlanPartnerBonus: orderInfo.OrderCompute.PlanPartnerBonus,
  74 + UsePartnerBonus: orderInfo.OrderCompute.UsePartnerBonus,
  75 + PartnerBonusHas: orderInfo.OrderCompute.PartnerBonusHas,
  76 + PartnerBonusNot: orderInfo.OrderCompute.PartnerBonusNot,
  77 + PartnerBonusExpense: orderInfo.OrderCompute.PartnerBonusExpense,
  78 + IsDisable: orderInfo.IsDisable,
  79 + CreateTime: orderInfo.CreateTime,
  80 + SaleDate: orderInfo.SaleDate,
  81 + BonusStatus: orderInfo.BonusStatus,
  82 + CompanyId: orderInfo.CompanyId,
  83 + DataFrom: orderInfo.DataFrom,
  84 + Remark: orderInfo.Remark,
  85 + PartnerCategory: orderInfo.PartnerCategory,
  86 + }
  87 + //if m.OrderType > 2 { // TODO 非平台自建订单,默认销售日期取订单创建日期
  88 + // m.SaleDate = orderInfo.CreateTime
  89 + //}
71 if m.Id == 0 { 90 if m.Id == 0 {
72 _, err = tx.Model(m). 91 _, err = tx.Model(m).
73 Returning("*"). 92 Returning("*").
@@ -75,6 +94,7 @@ func (repository OrderBaseRepository) Save(orderInfo *domain.OrderBase) error { @@ -75,6 +94,7 @@ func (repository OrderBaseRepository) Save(orderInfo *domain.OrderBase) error {
75 orderInfo.Id = m.Id 94 orderInfo.Id = m.Id
76 orderInfo.CreateTime = m.CreateTime 95 orderInfo.CreateTime = m.CreateTime
77 orderInfo.UpdateTime = m.UpdateTime 96 orderInfo.UpdateTime = m.UpdateTime
  97 + orderInfo.SaleDate = m.CreateTime
78 } else { 98 } else {
79 _, err = tx.Model(m). 99 _, err = tx.Model(m).
80 WherePK(). 100 WherePK().
@@ -131,16 +151,16 @@ func (repository OrderBaseRepository) Find(queryOption domain.OrderBaseFindQuery @@ -131,16 +151,16 @@ func (repository OrderBaseRepository) Find(queryOption domain.OrderBaseFindQuery
131 return ordersReturn, count, nil 151 return ordersReturn, count, nil
132 } 152 }
133 153
134 -func (repository OrderBaseRepository) FindOne(qureyOptions domain.OrderBaseFindOneQuery) (*domain.OrderBase, error) { 154 +func (repository OrderBaseRepository) FindOne(queryOptions domain.OrderBaseFindOneQuery) (*domain.OrderBase, error) {
135 var ( 155 var (
136 err error 156 err error
137 tx = repository.transactionContext.PgDd 157 tx = repository.transactionContext.PgDd
138 ) 158 )
139 m := new(models.OrderBase) 159 m := new(models.OrderBase)
140 query := tx.Model(m). 160 query := tx.Model(m).
141 - Where("id=?", qureyOptions.OrderId)  
142 - if qureyOptions.CompanyId > 0 {  
143 - query = query.Where("company_id=?", qureyOptions.CompanyId) 161 + Where("id=?", queryOptions.OrderId)
  162 + if queryOptions.CompanyId > 0 {
  163 + query = query.Where("company_id=?", queryOptions.CompanyId)
144 } 164 }
145 err = query.First() 165 err = query.First()
146 if err != nil { 166 if err != nil {
  1 +package controllers
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "errors"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  7 +
  8 + "github.com/astaxie/beego/logs"
  9 +
  10 + "github.com/linmadan/egglib-go/web/beego/utils"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/columnSetting/command"
  12 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/columnSetting/query"
  13 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/columnSetting/service"
  14 +)
  15 +
  16 +type ColumnSettingController struct {
  17 + BaseController
  18 +}
  19 +
  20 +////Prepare 重写 BaseController 的Prepare方法
  21 +func (controller *ColumnSettingController) Prepare() {
  22 + controller.BaseController.Prepare()
  23 + if ok := controller.ValidJWTToken(); !ok {
  24 + return
  25 + }
  26 + if ok := controller.ValidAdminPermission(domain.PERMINSSION_PARTNER); !ok {
  27 + return
  28 + }
  29 +}
  30 +
  31 +func (controller *ColumnSettingController) CreateColumnSetting() {
  32 + columnSettingService := service.NewColumnSettingService(nil)
  33 + createColumnSettingCommand := &command.CreateColumnSettingCommand{}
  34 + //_ = json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), createColumnSettingCommand)
  35 + if err := controller.BindJsonData(&createColumnSettingCommand); err != nil {
  36 + logs.Error(err)
  37 + controller.ResponseError(errors.New("json数据解析失败"))
  38 + return
  39 + }
  40 + companyId := controller.GetUserCompany()
  41 + uid := controller.GetUserId()
  42 + createColumnSettingCommand.CompanyId = int(companyId)
  43 + createColumnSettingCommand.Uid = uid
  44 + data, err := columnSettingService.CreateColumnSetting(createColumnSettingCommand)
  45 + var response utils.JsonResponse
  46 + if err != nil {
  47 + response = utils.ResponseError(controller.Ctx, err)
  48 + } else {
  49 + response = utils.ResponseData(controller.Ctx, data)
  50 + }
  51 + controller.Data["json"] = response
  52 + controller.ServeJSON()
  53 +}
  54 +
  55 +/**
  56 + * @Author SteveChan
  57 + * @Description // 更新栏目设置
  58 + * @Date 22:52 2021/1/26
  59 + * @Param
  60 + * @return
  61 + **/
  62 +func (controller *ColumnSettingController) UpdateColumnSetting() {
  63 + columnSettingService := service.NewColumnSettingService(nil)
  64 + updateColumnSettingCommand := &command.UpdateColumnSettingCommand{}
  65 + //_ = json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), updateColumnSettingCommand)
  66 + if err := controller.BindJsonData(&updateColumnSettingCommand); err != nil {
  67 + logs.Error(err)
  68 + controller.ResponseError(errors.New("json数据解析失败"))
  69 + return
  70 + }
  71 + //columnSettingId, _ := controller.GetInt64(":columnSettingId")
  72 + companyId := controller.GetUserCompany()
  73 + uid := controller.GetUserId()
  74 + //updateColumnSettingCommand.ColumnSettingId = columnSettingId
  75 + updateColumnSettingCommand.CompanyId = int(companyId)
  76 + updateColumnSettingCommand.Uid = uid
  77 + updateColumnSettingCommand.Selected = updateColumnSettingCommand.OrderBaseColumns.Selected
  78 + updateColumnSettingCommand.UnSelected = updateColumnSettingCommand.OrderBaseColumns.UnSelected
  79 + data, err := columnSettingService.UpdateColumnSetting(updateColumnSettingCommand)
  80 + var response utils.JsonResponse
  81 + if err != nil {
  82 + response = utils.ResponseError(controller.Ctx, err)
  83 + } else {
  84 + response = utils.ResponseData(controller.Ctx, data)
  85 + }
  86 + controller.Data["json"] = response
  87 + controller.ServeJSON()
  88 +}
  89 +
  90 +/**
  91 + * @Author SteveChan
  92 + * @Description // 获取栏目设置
  93 + * @Date 22:53 2021/1/26
  94 + * @Param
  95 + * @return
  96 + **/
  97 +func (controller *ColumnSettingController) GetColumnSetting() {
  98 + columnSettingService := service.NewColumnSettingService(nil)
  99 + getColumnSettingQuery := &query.GetColumnSettingQuery{}
  100 + //columnSettingId, _ := controller.GetInt64(":columnSettingId")
  101 + companyId := controller.GetUserCompany() // 公司id
  102 + uid := controller.GetUserId() // 用户id
  103 + //getColumnSettingQuery.ColumnSettingId = columnSettingId
  104 + getColumnSettingQuery.CompanyId = int(companyId)
  105 + getColumnSettingQuery.Uid = uid
  106 + data, err := columnSettingService.GetColumnSetting(getColumnSettingQuery)
  107 + var response utils.JsonResponse
  108 + if err != nil {
  109 + response = utils.ResponseError(controller.Ctx, err)
  110 + } else {
  111 + response = utils.ResponseData(controller.Ctx, data)
  112 + }
  113 + controller.Data["json"] = response
  114 + controller.ServeJSON()
  115 +}
  116 +
  117 +func (controller *ColumnSettingController) RemoveColumnSetting() {
  118 + columnSettingService := service.NewColumnSettingService(nil)
  119 + removeColumnSettingCommand := &command.RemoveColumnSettingCommand{}
  120 + _ = json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), removeColumnSettingCommand)
  121 + columnSettingId, _ := controller.GetInt64(":columnSettingId")
  122 + removeColumnSettingCommand.ColumnSettingId = columnSettingId
  123 + data, err := columnSettingService.RemoveColumnSetting(removeColumnSettingCommand)
  124 + var response utils.JsonResponse
  125 + if err != nil {
  126 + response = utils.ResponseError(controller.Ctx, err)
  127 + } else {
  128 + response = utils.ResponseData(controller.Ctx, data)
  129 + }
  130 + controller.Data["json"] = response
  131 + controller.ServeJSON()
  132 +}
  133 +
  134 +/**
  135 + * @Author SteveChan
  136 + * @Description // 重置栏目设置
  137 + * @Date 22:52 2021/1/26
  138 + * @Param
  139 + * @return
  140 + **/
  141 +func (controller *ColumnSettingController) ResetColumn() {
  142 + columnSettingService := service.NewColumnSettingService(nil)
  143 + resetColumnCommand := &command.ResetColumnCommand{}
  144 + companyId := controller.GetUserCompany()
  145 + uid := controller.GetUserId()
  146 + //_ = json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), resetColumnCommand)
  147 + resetColumnCommand.CompanyId = int(companyId)
  148 + resetColumnCommand.Uid = uid
  149 + resetColumnCommand.Value = domain.DefaultColumns // 还原默认栏目设置
  150 + resetColumnCommand.InvalidValue = domain.DefaultInvalidColumns // 还原默认无效栏目
  151 + data, err := columnSettingService.ResetColumn(resetColumnCommand)
  152 + var response utils.JsonResponse
  153 + if err != nil {
  154 + response = utils.ResponseError(controller.Ctx, err)
  155 + } else {
  156 + response = utils.ResponseData(controller.Ctx, data)
  157 + }
  158 + controller.Data["json"] = response
  159 + controller.ServeJSON()
  160 +}
  161 +
  162 +/**
  163 + * @Author SteveChan
  164 + * @Description // 获取栏目列表
  165 + * @Date 14:03 2021/2/1
  166 + * @Param
  167 + * @return
  168 + **/
  169 +func (controller *ColumnSettingController) ListColumnSetting() {
  170 + columnSettingService := service.NewColumnSettingService(nil)
  171 + listColumnSettingQuery := &query.ListColumnSettingQuery{}
  172 + offset, _ := controller.GetInt("offset")
  173 + listColumnSettingQuery.Offset = offset
  174 + limit, _ := controller.GetInt("limit")
  175 + listColumnSettingQuery.Limit = limit
  176 + data, err := columnSettingService.ListColumnSetting(listColumnSettingQuery)
  177 + var response utils.JsonResponse
  178 + if err != nil {
  179 + response = utils.ResponseError(controller.Ctx, err)
  180 + } else {
  181 + response = utils.ResponseData(controller.Ctx, data)
  182 + }
  183 + controller.Data["json"] = response
  184 + controller.ServeJSON()
  185 +}
  186 +
  187 +/**
  188 + * @Author SteveChan
  189 + * @Description //返回默认栏目设置
  190 + * @Date 14:06 2021/2/1
  191 + * @Param
  192 + * @return
  193 + **/
  194 +func (controller *ColumnSettingController) ListDefaultColumnSetting() {
  195 + data := map[string]interface{}{
  196 + "orderBaseColumns": map[string]interface{}{
  197 + "selected": domain.DefaultColumns,
  198 + "unselected": domain.DefaultInvalidColumns,
  199 + },
  200 + }
  201 + var response utils.JsonResponse
  202 + response = utils.ResponseData(controller.Ctx, data)
  203 + controller.Data["json"] = response
  204 + controller.ServeJSON()
  205 +}
@@ -160,15 +160,16 @@ func (postData *postOrderPurposeDelivery) Valid() error { @@ -160,15 +160,16 @@ func (postData *postOrderPurposeDelivery) Valid() error {
160 **/ 160 **/
161 func (c *OrderInfoController) PageListOrderReal() { 161 func (c *OrderInfoController) PageListOrderReal() {
162 type Parameter struct { 162 type Parameter struct {
163 - //SearchText string `json:"searchText"`  
164 - PartnerName string `json:"partnerName"` // 合伙人姓名  
165 - OrderCode string `json:"orderCode"` // 订单号  
166 - DeliveryCode string `json:"deliveryCode"` // 发货单号  
167 - PartnerCategory int `json:"PartnerCategory"`  
168 - PageSize int `json:"pageSize"`  
169 - PageNumber int `json:"pageNumber"`  
170 - UpdateTime []string `json:"updateTime"`  
171 - CreateTime []string `json:"createTime"` 163 + PartnerName string `json:"partnerName"` // 合伙人姓名
  164 + OrderCode string `json:"orderCode"` // 订单号
  165 + DeliveryCode string `json:"deliveryCode"` // 发货单号
  166 + PartnerCategory int `json:"partnerCategory"` // 合伙人类型id
  167 + PartnerCategoryName string `json:"partnerCategoryName"` // 合伙人类型名称
  168 + PageSize int `json:"pageSize"`
  169 + PageNumber int `json:"pageNumber"`
  170 + UpdateTime []string `json:"updateTime"` // 订单更新时间
  171 + CreateTime []string `json:"createTime"` // 订单创建时间
  172 + SaleDate []string `json:"saleDate"` // 销售时间
172 } 173 }
173 var ( 174 var (
174 param Parameter 175 param Parameter
@@ -185,6 +186,7 @@ func (c *OrderInfoController) PageListOrderReal() { @@ -185,6 +186,7 @@ func (c *OrderInfoController) PageListOrderReal() {
185 if param.PageSize == 0 { 186 if param.PageSize == 0 {
186 param.PageSize = 20 187 param.PageSize = 20
187 } 188 }
  189 + // 订单更新时间处理
188 var ( 190 var (
189 updateTimeBegin string 191 updateTimeBegin string
190 updateTimeEnd string 192 updateTimeEnd string
@@ -211,6 +213,7 @@ func (c *OrderInfoController) PageListOrderReal() { @@ -211,6 +213,7 @@ func (c *OrderInfoController) PageListOrderReal() {
211 updateTimeEnd = t.Format("2006-01-02 15:04:05-07") 213 updateTimeEnd = t.Format("2006-01-02 15:04:05-07")
212 } 214 }
213 } 215 }
  216 + // 订单创建时间处理
214 var ( 217 var (
215 createTimeBegin string 218 createTimeBegin string
216 createTimeEnd string 219 createTimeEnd string
@@ -237,29 +240,57 @@ func (c *OrderInfoController) PageListOrderReal() { @@ -237,29 +240,57 @@ func (c *OrderInfoController) PageListOrderReal() {
237 createTimeEnd = t.Format("2006-01-02 15:04:05-07") 240 createTimeEnd = t.Format("2006-01-02 15:04:05-07")
238 } 241 }
239 } 242 }
240 - 243 + // 订单销售时间处理
  244 + var (
  245 + saleDateBegin string
  246 + saleDateEnd string
  247 + )
  248 + if len(param.SaleDate) > 0 {
  249 + if len(param.SaleDate[0]) > 0 {
  250 + t, err := time.ParseInLocation("2006-01-02", param.SaleDate[0], time.Local)
  251 + if err != nil {
  252 + c.ResponseError(errors.New("销售开始时间格式错误"))
  253 + return
  254 + }
  255 + saleDateBegin = t.Format("2006-01-02 15:04:05-07")
  256 + }
  257 + }
  258 + if len(param.SaleDate) > 1 {
  259 + if len(param.SaleDate[1]) > 0 {
  260 + t, err := time.ParseInLocation("2006-01-02", param.SaleDate[1], time.Local)
  261 + if err != nil {
  262 + c.ResponseError(errors.New("销售结束时间格式错误"))
  263 + return
  264 + }
  265 + //设定时间边界
  266 + t = t.Add(86399 * time.Second)
  267 + saleDateEnd = t.Format("2006-01-02 15:04:05-07")
  268 + }
  269 + }
241 companyId := c.GetUserCompany() 270 companyId := c.GetUserCompany()
242 orderSrv := orderService.NewOrderInfoService(nil) 271 orderSrv := orderService.NewOrderInfoService(nil)
243 - orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{  
244 - //PartnerOrCode: param.SearchText,  
245 - PartnerName: param.PartnerName,  
246 - OrderCode: param.OrderCode,  
247 - DeliveryCode: param.DeliveryCode,  
248 - OrderType: domain.OrderReal,  
249 - Limit: param.PageSize,  
250 - Offset: (param.PageNumber - 1) * param.PageSize,  
251 - CompanyId: companyId,  
252 - PartnerCategory: param.PartnerCategory,  
253 - UpdateTimeBegin: updateTimeBegin,  
254 - UpdateTimeEnd: updateTimeEnd,  
255 - CreateTimeBegin: createTimeBegin,  
256 - CreateTimeEnd: createTimeEnd, 272 + orderInfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
  273 + PartnerName: param.PartnerName,
  274 + OrderCode: param.OrderCode,
  275 + DeliveryCode: param.DeliveryCode,
  276 + OrderType: domain.OrderReal,
  277 + Limit: param.PageSize,
  278 + Offset: (param.PageNumber - 1) * param.PageSize,
  279 + CompanyId: companyId,
  280 + PartnerCategory: param.PartnerCategory,
  281 + PartnerCategoryName: param.PartnerCategoryName,
  282 + UpdateTimeBegin: updateTimeBegin,
  283 + UpdateTimeEnd: updateTimeEnd,
  284 + CreateTimeBegin: createTimeBegin,
  285 + CreateTimeEnd: createTimeEnd,
  286 + SaleDateBegin: saleDateBegin,
  287 + SaleDateEnd: saleDateEnd,
257 }) 288 })
258 if err != nil { 289 if err != nil {
259 c.ResponseError(err) 290 c.ResponseError(err)
260 return 291 return
261 } 292 }
262 - c.ResponsePageList(orderinfos, cnt, param.PageNumber) 293 + c.ResponsePageList(orderInfos, cnt, param.PageNumber)
263 return 294 return
264 } 295 }
265 296
@@ -299,7 +330,8 @@ func (c *OrderInfoController) GetOrderReal() { @@ -299,7 +330,8 @@ func (c *OrderInfoController) GetOrderReal() {
299 allGoods := []map[string]interface{}{} 330 allGoods := []map[string]interface{}{}
300 for _, v := range orderinfo.Goods { 331 for _, v := range orderinfo.Goods {
301 m := map[string]interface{}{ 332 m := map[string]interface{}{
302 - "id": fmt.Sprint(v.Id), 333 + //"id": fmt.Sprint(v.Id),
  334 + "id": v.Id,
303 "productName": v.GoodName, 335 "productName": v.GoodName,
304 "orderNum": v.PlanGoodNumber, 336 "orderNum": v.PlanGoodNumber,
305 "univalence": v.Price, 337 "univalence": v.Price,
@@ -330,8 +362,9 @@ func (c *OrderInfoController) GetOrderReal() { @@ -330,8 +362,9 @@ func (c *OrderInfoController) GetOrderReal() {
330 "orderNumCountControl": "", 362 "orderNumCountControl": "",
331 "orderAmountAdjustmentCountControl": "", 363 "orderAmountAdjustmentCountControl": "",
332 "product": allGoods, 364 "product": allGoods,
333 - "create_time": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:06"),  
334 - "update_time": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:06"), 365 + "create_time": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
  366 + "update_time": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
  367 + "saleDate": orderinfo.SaleDate.Local().Format("2006-01-02 15:04:05"),
335 "partnerCategoryId": orderinfo.PartnerCategory.Id, 368 "partnerCategoryId": orderinfo.PartnerCategory.Id,
336 "partnerCategoryName": orderinfo.PartnerCategory.Name, 369 "partnerCategoryName": orderinfo.PartnerCategory.Name,
337 } 370 }
@@ -350,6 +383,7 @@ type postRealOrderDetail struct { @@ -350,6 +383,7 @@ type postRealOrderDetail struct {
350 postPurposeOrderDetail 383 postPurposeOrderDetail
351 PartnerCategoryId int64 `json:"partnerCategoryId"` 384 PartnerCategoryId int64 `json:"partnerCategoryId"`
352 ShipmentsId string `json:"shipmentsId"` //发货单号 385 ShipmentsId string `json:"shipmentsId"` //发货单号
  386 + SaleDate string `json:"saleDate"` // 销售日期
353 } 387 }
354 388
355 func (postData *postRealOrderDetail) Valid() error { 389 func (postData *postRealOrderDetail) Valid() error {
@@ -380,10 +414,18 @@ func (c *OrderInfoController) UpdateOrderReal() { @@ -380,10 +414,18 @@ func (c *OrderInfoController) UpdateOrderReal() {
380 return 414 return
381 } 415 }
382 var orderDataReturn *domain.OrderBase 416 var orderDataReturn *domain.OrderBase
  417 + saleDate, err := time.ParseInLocation("2006-01-02 15:04:05", param.SaleDate, time.Local)
  418 + saleDateWithTz := time.Date(saleDate.Year(), saleDate.Month(), saleDate.Day(), time.Now().Hour(), time.Now().Minute(), time.Now().Second(), time.Now().Nanosecond(), time.Local)
  419 +
  420 + if err != nil {
  421 + e := lib.ThrowError(lib.ARG_ERROR, err.Error())
  422 + c.ResponseError(e)
  423 + return
  424 + }
383 if param.Id == 0 { 425 if param.Id == 0 {
384 - orderDataReturn, err = c.addOrderReal(param) 426 + orderDataReturn, err = c.addOrderReal(param, saleDateWithTz)
385 } else { 427 } else {
386 - err = c.editOrderReal(param) 428 + err = c.editOrderReal(param, saleDateWithTz)
387 } 429 }
388 if err != nil { 430 if err != nil {
389 c.ResponseError(err) 431 c.ResponseError(err)
@@ -399,7 +441,7 @@ func (c *OrderInfoController) UpdateOrderReal() { @@ -399,7 +441,7 @@ func (c *OrderInfoController) UpdateOrderReal() {
399 return 441 return
400 } 442 }
401 443
402 -func (c *OrderInfoController) addOrderReal(param postRealOrderDetail) (*domain.OrderBase, error) { 444 +func (c *OrderInfoController) addOrderReal(param postRealOrderDetail, saleDate time.Time) (*domain.OrderBase, error) {
403 orderSrv := orderService.NewOrderInfoService(nil) 445 orderSrv := orderService.NewOrderInfoService(nil)
404 newGoods := []orderCmd.OrderGoodData{} 446 newGoods := []orderCmd.OrderGoodData{}
405 for _, v := range param.Product { 447 for _, v := range param.Product {
@@ -423,12 +465,13 @@ func (c *OrderInfoController) addOrderReal(param postRealOrderDetail) (*domain.O @@ -423,12 +465,13 @@ func (c *OrderInfoController) addOrderReal(param postRealOrderDetail) (*domain.O
423 Goods: newGoods, 465 Goods: newGoods,
424 CompanyId: companyId, 466 CompanyId: companyId,
425 PartnerCategory: param.PartnerCategoryId, 467 PartnerCategory: param.PartnerCategoryId,
  468 + SaleDate: saleDate,
426 } 469 }
427 orderData, err := orderSrv.CreateNewOrder(createcmd) 470 orderData, err := orderSrv.CreateNewOrder(createcmd)
428 return orderData, err 471 return orderData, err
429 } 472 }
430 473
431 -func (c *OrderInfoController) editOrderReal(param postRealOrderDetail) error { 474 +func (c *OrderInfoController) editOrderReal(param postRealOrderDetail, saleDate time.Time) error {
432 475
433 newGoods := []orderCmd.OrderGoodData{} 476 newGoods := []orderCmd.OrderGoodData{}
434 for _, v := range param.Product { 477 for _, v := range param.Product {
@@ -453,6 +496,7 @@ func (c *OrderInfoController) editOrderReal(param postRealOrderDetail) error { @@ -453,6 +496,7 @@ func (c *OrderInfoController) editOrderReal(param postRealOrderDetail) error {
453 Goods: newGoods, 496 Goods: newGoods,
454 CompanyId: companyId, 497 CompanyId: companyId,
455 PartnerCategory: param.PartnerCategoryId, 498 PartnerCategory: param.PartnerCategoryId,
  499 + SaleDate: saleDate,
456 } 500 }
457 orderSrv := orderService.NewOrderInfoService(nil) 501 orderSrv := orderService.NewOrderInfoService(nil)
458 _, err := orderSrv.UpdateOrderData(updatecmd) 502 _, err := orderSrv.UpdateOrderData(updatecmd)
@@ -527,17 +571,20 @@ func (c *OrderInfoController) RemoveOrderReal() { @@ -527,17 +571,20 @@ func (c *OrderInfoController) RemoveOrderReal() {
527 571
528 //ListOrderForExcel excel 导出实际订单的列表 572 //ListOrderForExcel excel 导出实际订单的列表
529 func (c *OrderInfoController) ListOrderForExcel() { 573 func (c *OrderInfoController) ListOrderForExcel() {
530 - type Parameter struct {  
531 - //SearchText string `json:"searchText"`  
532 - PartnerName string `json:"partnerName"` // 合伙人姓名  
533 - OrderCode string `json:"orderCode"` // 订单号  
534 - DeliveryCode string `json:"deliveryCode"` // 发货单号  
535 - PartnerCategory int `json:"PartnerCategory"`  
536 - UpdateTime []string `json:"updateTime"`  
537 - CreateTime []string `json:"createTime"`  
538 - } 574 + //type Parameter struct {
  575 + // PartnerName string `json:"partnerName"` // 合伙人姓名
  576 + // OrderCode string `json:"orderCode"` // 订单号
  577 + // DeliveryCode string `json:"deliveryCode"` // 发货单号
  578 + // PartnerCategory int `json:"partnerCategory"` // 合伙人类型
  579 + // PartnerCategoryName string `json:"partnerCategoryName"` // 合伙人类型名称
  580 + // UpdateTime []string `json:"updateTime"` // 更新时间
  581 + // CreateTime []string `json:"createTime"` // 创建时间
  582 + // SaleDate []string `json:"saleDate"` // 销售日期
  583 + //}
  584 +
539 var ( 585 var (
540 - param Parameter 586 + //param Parameter
  587 + param orderQuery.ListOrderForExcelQuery
541 err error 588 err error
542 ) 589 )
543 if err = c.BindJsonData(&param); err != nil { 590 if err = c.BindJsonData(&param); err != nil {
@@ -545,13 +592,19 @@ func (c *OrderInfoController) ListOrderForExcel() { @@ -545,13 +592,19 @@ func (c *OrderInfoController) ListOrderForExcel() {
545 c.ResponseError(errors.New("json数据解析失败")) 592 c.ResponseError(errors.New("json数据解析失败"))
546 return 593 return
547 } 594 }
  595 + if param.Type != "ORDER_BASE" {
  596 + logs.Error(err)
  597 + c.ResponseError(errors.New("错误的操作类型"))
  598 + return
  599 + }
  600 + // 订单更新时间
548 var ( 601 var (
549 updateTimeBegin string 602 updateTimeBegin string
550 updateTimeEnd string 603 updateTimeEnd string
551 ) 604 )
552 - if len(param.UpdateTime) > 0 {  
553 - if len(param.UpdateTime[0]) > 0 {  
554 - t, err := time.ParseInLocation("2006-01-02", param.UpdateTime[0], time.Local) 605 + if len(param.Where.UpdateTime) > 0 {
  606 + if len(param.Where.UpdateTime[0]) > 0 {
  607 + t, err := time.ParseInLocation("2006-01-02", param.Where.UpdateTime[0], time.Local)
555 if err != nil { 608 if err != nil {
556 c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误")) 609 c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误"))
557 return 610 return
@@ -559,9 +612,9 @@ func (c *OrderInfoController) ListOrderForExcel() { @@ -559,9 +612,9 @@ func (c *OrderInfoController) ListOrderForExcel() {
559 updateTimeBegin = t.Format("2006-01-02 15:04:05-07") 612 updateTimeBegin = t.Format("2006-01-02 15:04:05-07")
560 } 613 }
561 } 614 }
562 - if len(param.UpdateTime) > 1 {  
563 - if len(param.UpdateTime[1]) > 0 {  
564 - t, err := time.ParseInLocation("2006-01-02", param.UpdateTime[1], time.Local) 615 + if len(param.Where.UpdateTime) > 1 {
  616 + if len(param.Where.UpdateTime[1]) > 0 {
  617 + t, err := time.ParseInLocation("2006-01-02", param.Where.UpdateTime[1], time.Local)
565 if err != nil { 618 if err != nil {
566 c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误")) 619 c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误"))
567 return 620 return
@@ -571,13 +624,14 @@ func (c *OrderInfoController) ListOrderForExcel() { @@ -571,13 +624,14 @@ func (c *OrderInfoController) ListOrderForExcel() {
571 updateTimeEnd = t.Format("2006-01-02 15:04:05-07") 624 updateTimeEnd = t.Format("2006-01-02 15:04:05-07")
572 } 625 }
573 } 626 }
  627 + // 订单创建时间
574 var ( 628 var (
575 createTimeBegin string 629 createTimeBegin string
576 createTimeEnd string 630 createTimeEnd string
577 ) 631 )
578 - if len(param.CreateTime) > 0 {  
579 - if len(param.CreateTime[0]) > 0 {  
580 - t, err := time.ParseInLocation("2006-01-02", param.CreateTime[0], time.Local) 632 + if len(param.Where.CreateTime) > 0 {
  633 + if len(param.Where.CreateTime[0]) > 0 {
  634 + t, err := time.ParseInLocation("2006-01-02", param.Where.CreateTime[0], time.Local)
581 if err != nil { 635 if err != nil {
582 c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误")) 636 c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误"))
583 return 637 return
@@ -585,9 +639,9 @@ func (c *OrderInfoController) ListOrderForExcel() { @@ -585,9 +639,9 @@ func (c *OrderInfoController) ListOrderForExcel() {
585 createTimeBegin = t.Format("2006-01-02 15:04:05-07") 639 createTimeBegin = t.Format("2006-01-02 15:04:05-07")
586 } 640 }
587 } 641 }
588 - if len(param.CreateTime) > 1 {  
589 - if len(param.CreateTime[1]) > 0 {  
590 - t, err := time.ParseInLocation("2006-01-02", param.CreateTime[1], time.Local) 642 + if len(param.Where.CreateTime) > 1 {
  643 + if len(param.Where.CreateTime[1]) > 0 {
  644 + t, err := time.ParseInLocation("2006-01-02", param.Where.CreateTime[1], time.Local)
591 if err != nil { 645 if err != nil {
592 c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误")) 646 c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误"))
593 return 647 return
@@ -597,21 +651,51 @@ func (c *OrderInfoController) ListOrderForExcel() { @@ -597,21 +651,51 @@ func (c *OrderInfoController) ListOrderForExcel() {
597 createTimeEnd = t.Format("2006-01-02 15:04:05-07") 651 createTimeEnd = t.Format("2006-01-02 15:04:05-07")
598 } 652 }
599 } 653 }
600 - 654 + // 订单销售时间处理
  655 + var (
  656 + saleDateBegin string
  657 + saleDateEnd string
  658 + )
  659 + if len(param.Where.SaleDate) > 0 {
  660 + if len(param.Where.SaleDate[0]) > 0 {
  661 + t, err := time.ParseInLocation("2006-01-02", param.Where.SaleDate[0], time.Local)
  662 + if err != nil {
  663 + c.ResponseError(errors.New("销售开始时间格式错误"))
  664 + return
  665 + }
  666 + saleDateBegin = t.Format("2006-01-02 15:04:05-07")
  667 + }
  668 + }
  669 + if len(param.Where.SaleDate) > 1 {
  670 + if len(param.Where.SaleDate[1]) > 0 {
  671 + t, err := time.ParseInLocation("2006-01-02", param.Where.SaleDate[1], time.Local)
  672 + if err != nil {
  673 + c.ResponseError(errors.New("销售结束时间格式错误"))
  674 + return
  675 + }
  676 + //设定时间边界
  677 + t = t.Add(86399 * time.Second)
  678 + saleDateEnd = t.Format("2006-01-02 15:04:05-07")
  679 + }
  680 + }
601 companyId := c.GetUserCompany() 681 companyId := c.GetUserCompany()
  682 + uid := c.GetUserId()
602 orderSrv := orderService.NewOrderInfoService(nil) 683 orderSrv := orderService.NewOrderInfoService(nil)
603 - orderinfos, columns, err := orderSrv.ListOrderForExcel(orderQuery.ListOrderBaseQuery{  
604 - //PartnerOrCode: param.SearchText,  
605 - PartnerName: param.PartnerName,  
606 - OrderCode: param.OrderCode,  
607 - DeliveryCode: param.DeliveryCode,  
608 - OrderType: domain.OrderReal,  
609 - CompanyId: companyId,  
610 - PartnerCategory: param.PartnerCategory,  
611 - UpdateTimeBegin: updateTimeBegin,  
612 - UpdateTimeEnd: updateTimeEnd,  
613 - CreateTimeBegin: createTimeBegin,  
614 - CreateTimeEnd: createTimeEnd, 684 + orderInfos, columns, err := orderSrv.ListOrderForExcel(orderQuery.ListOrderBaseQuery{
  685 + PartnerName: param.Where.PartnerName,
  686 + OrderCode: param.Where.OrderCode,
  687 + DeliveryCode: param.Where.DeliveryCode,
  688 + OrderType: domain.OrderReal,
  689 + CompanyId: companyId,
  690 + Uid: uid,
  691 + PartnerCategory: param.Where.PartnerCategory,
  692 + PartnerCategoryName: param.Where.PartnerCategoryName,
  693 + UpdateTimeBegin: updateTimeBegin,
  694 + UpdateTimeEnd: updateTimeEnd,
  695 + CreateTimeBegin: createTimeBegin,
  696 + CreateTimeEnd: createTimeEnd,
  697 + SaleDateBegin: saleDateBegin,
  698 + SaleDateEnd: saleDateEnd,
615 }) 699 })
616 if err != nil { 700 if err != nil {
617 c.ResponseError(err) 701 c.ResponseError(err)
@@ -627,8 +711,8 @@ func (c *OrderInfoController) ListOrderForExcel() { @@ -627,8 +711,8 @@ func (c *OrderInfoController) ListOrderForExcel() {
627 } 711 }
628 excelMaker := exceltool.NewExcelMaker() 712 excelMaker := exceltool.NewExcelMaker()
629 excelMaker.SetListHead(excelHeaders) 713 excelMaker.SetListHead(excelHeaders)
630 - excelMaker.MakeListExcel(orderinfos)  
631 - c.ResponseExcelByFile(c.Ctx, excelMaker) 714 + _ = excelMaker.MakeListExcel(orderInfos)
  715 + _ = c.ResponseExcelByFile(c.Ctx, excelMaker)
632 return 716 return
633 } 717 }
634 718
@@ -667,7 +751,7 @@ func (c *OrderInfoController) DownloadTemplate() { @@ -667,7 +751,7 @@ func (c *OrderInfoController) DownloadTemplate() {
667 } 751 }
668 752
669 // 获取导入模板 753 // 获取导入模板
670 - req := httplib.Get("http://suplus-file-dev.fjmaimaimai.com/upload/file/2021010803305336443.xlsx") 754 + req := httplib.Get("http://suplus-file-dev.fjmaimaimai.com/upload/file/2021020111293523855.xlsx")
671 err = req.ToFile(constant.IMPORT_EXCEL) 755 err = req.ToFile(constant.IMPORT_EXCEL)
672 if err != nil { 756 if err != nil {
673 logs.Error("could not save to file: ", err) 757 logs.Error("could not save to file: ", err)
@@ -708,8 +792,8 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -708,8 +792,8 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
708 // 返回字段定义 792 // 返回字段定义
709 ret := map[string]interface{}{} 793 ret := map[string]interface{}{}
710 794
711 - // 返回信息表头定义 0: 订单号, 1: 发货单号, 2: 客户名称, 3: 订单区域, 4: 编号, 5: 合伙人, 6: 类型, 7: 业务员抽成比例, 8: 产品名称, 9: 数量, 10: 单价, 11: 合伙人分红比例  
712 - var tableHeader = []string{"错误详情", "行号", "订单号", "发货单号", "客户名称", "订单区域", "编号", "合伙人", "类型", "业务员抽成比例", "产品名称", "数量", "单价", "合伙人分红比例"} 795 + // 返回信息表头定义 0: 订单号, 1: 发货单号, 2: 客户名称, 3: 订单区域, 4: 销售日期, 5: 编号, 6: 合伙人, 7: 类型, 8: 业务员抽成比例, 9: 产品名称, 10: 数量, 11: 单价, 12: 合伙人分红比例
  796 + var tableHeader = []string{"错误详情", "行号", "订单号", "发货单号", "客户名称", "订单区域", "销售日期", "编号", "合伙人", "类型", "业务员抽成比例", "产品名称", "数量", "单价", "合伙人分红比例"}
713 797
714 // 文件后缀名校验 798 // 文件后缀名校验
715 ext := path.Ext(h.Filename) 799 ext := path.Ext(h.Filename)
@@ -781,7 +865,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -781,7 +865,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
781 nullCell := make([]interface{}, 0) 865 nullCell := make([]interface{}, 0)
782 var myRow []string 866 var myRow []string
783 for j, _ := range row { 867 for j, _ := range row {
784 - if j != 7 { // 业务员抽成比例非必填 868 + if j != 8 { // 业务员抽成比例非必填
785 if row[j] == "" || row[j] == " " { // 空字符补位 869 if row[j] == "" || row[j] == " " { // 空字符补位
786 tmpRow[j] = "" 870 tmpRow[j] = ""
787 col := strconv.Itoa(j + 1) 871 col := strconv.Itoa(j + 1)
@@ -847,7 +931,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -847,7 +931,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
847 col := strconv.Itoa(j + 1) 931 col := strconv.Itoa(j + 1)
848 932
849 switch j { 933 switch j {
850 - case 0, 1, 2, 3, 4, 5, 8: // 订单号、发货单号、客户名称、订单区域、编号、合伙人、产品名称长度校验 934 + case 0, 1, 2, 3, 5, 6, 9: // 订单号、发货单号、客户名称、订单区域、编号、合伙人、产品名称长度校验
851 { 935 {
852 cellStr := strings.TrimSpace(cell) 936 cellStr := strings.TrimSpace(cell)
853 lenCellStr := utf8.RuneCountInString(cellStr) 937 lenCellStr := utf8.RuneCountInString(cellStr)
@@ -860,7 +944,19 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -860,7 +944,19 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
860 myRow = tmpRow 944 myRow = tmpRow
861 } 945 }
862 } 946 }
863 - case 6: // 合伙人类型校验(事业合伙、业务合伙、研发合伙、业务-产品应用合伙) 947 + case 4: // 销售日期格式和有效性校验
  948 + {
  949 + regexpStr := `(\d{4})/(\d{2})/(\d{2})`
  950 + ok := regexp.MustCompile(regexpStr).MatchString(cell)
  951 + if !ok {
  952 + var tmpRow []string
  953 + tmpRow = append(tmpRow, "第"+r+"行第"+col+"列销售日期格式错误,请输入正确的销售日期") // 错误信息
  954 + tmpRow = append(tmpRow, r) // 行号
  955 + tmpRow = append(tmpRow, row...) // 错误行数据
  956 + myRow = tmpRow
  957 + }
  958 + }
  959 + case 7: // 合伙人类型校验(事业合伙、业务合伙、研发合伙、业务-产品应用合伙)
864 { 960 {
865 if !utils.IsContain(partnerType, cell) { 961 if !utils.IsContain(partnerType, cell) {
866 var tmpRow []string 962 var tmpRow []string
@@ -870,7 +966,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -870,7 +966,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
870 myRow = tmpRow 966 myRow = tmpRow
871 } 967 }
872 } 968 }
873 - case 7: // 业务员抽成比例,非必填,精确到小数点后两位 969 + case 8: // 业务员抽成比例,非必填,精确到小数点后两位
874 { 970 {
875 if len(cell) > 0 { 971 if len(cell) > 0 {
876 972
@@ -905,7 +1001,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -905,7 +1001,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
905 } 1001 }
906 } 1002 }
907 } 1003 }
908 - case 9: // 数量不超过16位正整数 1004 + case 10: // 产品数量不超过16位正整数
909 { 1005 {
910 //参数类型转换 1006 //参数类型转换
911 orderNum, err := strconv.ParseInt(cell, 10, 64) 1007 orderNum, err := strconv.ParseInt(cell, 10, 64)
@@ -926,7 +1022,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -926,7 +1022,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
926 myRow = tmpRow 1022 myRow = tmpRow
927 } 1023 }
928 } 1024 }
929 - case 10: // 单价,精确到小数点后两位,小数点左侧最多可输入16位数字 1025 + case 11: // 单价,精确到小数点后两位,小数点左侧最多可输入16位数字
930 { 1026 {
931 1027
932 // 参数类型转换 1028 // 参数类型转换
@@ -948,7 +1044,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -948,7 +1044,7 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
948 myRow = tmpRow 1044 myRow = tmpRow
949 } 1045 }
950 } 1046 }
951 - case 11: // 合伙人分红比例,精确到小数点后两位 1047 + case 12: // 合伙人分红比例,精确到小数点后两位
952 { 1048 {
953 //参数类型转换 1049 //参数类型转换
954 partnerRatio, parseErr := strconv.ParseFloat(cell, 64) 1050 partnerRatio, parseErr := strconv.ParseFloat(cell, 64)
@@ -1011,29 +1107,30 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -1011,29 +1107,30 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
1011 var orderCommands = make(map[string]*orderCmd.CreateOrderCommand, 0) 1107 var orderCommands = make(map[string]*orderCmd.CreateOrderCommand, 0)
1012 for i, row := range rows { 1108 for i, row := range rows {
1013 if i > 2 && len(row) == constant.EXCEL_COLUMN { 1109 if i > 2 && len(row) == constant.EXCEL_COLUMN {
1014 - hashValue := md5.Sum([]byte(row[0] + row[1] + row[4] + row[6])) // 根据:订单号+发货单号+合伙人编号+合伙类型计算哈希值 1110 + hashValue := md5.Sum([]byte(row[0] + row[1] + row[5] + row[7])) // 根据:订单号+发货单号+合伙人编号+合伙类型计算哈希值
1015 hashString := hex.EncodeToString(hashValue[:]) 1111 hashString := hex.EncodeToString(hashValue[:])
1016 1112
1017 if _, ok := orderCommands[hashString]; !ok { 1113 if _, ok := orderCommands[hashString]; !ok {
1018 - //订单相关,0: 订单号, 1: 发货单号, 2: 客户名称, 3: 订单区域, 4: 编号, 5: 合伙人, 6: 类型, 7: 业务抽成比例,  
1019 - sbPercent, _ := strconv.ParseFloat(row[7], 64) //业务抽成比例 1114 + //订单相关,0: 订单号, 1: 发货单号, 2: 客户名称, 3: 订单区域, 4: 销售日期, 5: 编号, 6: 合伙人, 7: 类型, 8: 业务抽成比例,
  1115 + sbPercent, _ := strconv.ParseFloat(row[8], 64) //业务抽成比例
1020 1116
1021 - //产品相关,8: 产品名称, 9: 数量, 10: 单价, 11: 合伙人分红比例  
1022 - amount, _ := strconv.ParseInt(row[9], 10, 64) // 数量  
1023 - price, _ := strconv.ParseFloat(row[10], 64) // 单价  
1024 - percent, _ := strconv.ParseFloat(row[11], 64) // 合伙人分红比例 1117 + //产品相关,9: 产品名称, 10: 数量, 11: 单价, 12: 合伙人分红比例
  1118 + amount, _ := strconv.ParseInt(row[10], 10, 64) // 数量
  1119 + price, _ := strconv.ParseFloat(row[11], 64) // 单价
  1120 + percent, _ := strconv.ParseFloat(row[12], 64) // 合伙人分红比例
1025 1121
1026 // 获取partnerId 1122 // 获取partnerId
1027 var partnerInfo *domain.PartnerInfo 1123 var partnerInfo *domain.PartnerInfo
1028 1124
  1125 + // 5: 合伙人编号
1029 orderQueryData := orderQuery.GetPartnerIdQuery{ 1126 orderQueryData := orderQuery.GetPartnerIdQuery{
1030 - Code: row[4], 1127 + Code: row[5],
1031 PartnerCategory: 0, 1128 PartnerCategory: 0,
1032 CompanyId: companyId, 1129 CompanyId: companyId,
1033 } 1130 }
1034 1131
1035 - // 1: 事业合伙、2: 业务合伙、3: 研发合伙、4: 业务-产品应用合伙  
1036 - switch row[6] { 1132 + // 7: 合伙人类型 1: 事业合伙、2: 业务合伙、3: 研发合伙、4: 业务-产品应用合伙
  1133 + switch row[7] {
1037 case "事业合伙": 1134 case "事业合伙":
1038 orderQueryData.PartnerCategory = 1 1135 orderQueryData.PartnerCategory = 1
1039 case "业务合伙": 1136 case "业务合伙":
@@ -1046,6 +1143,19 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -1046,6 +1143,19 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
1046 orderQueryData.PartnerCategory = 0 1143 orderQueryData.PartnerCategory = 0
1047 } 1144 }
1048 1145
  1146 + // 销售日期时间格式转换
  1147 + timeValue, err := time.ParseInLocation("2006/01/02", row[4], time.Local)
  1148 + if err != nil {
  1149 + e := lib.ThrowError(lib.ARG_ERROR, err.Error())
  1150 + c.ResponseError(e)
  1151 + return
  1152 + }
  1153 +
  1154 + //saleDate, err := time.ParseInLocation("2006-01-02 15:04:05", param.SaleDate, time.Local)
  1155 + saleDateWithTz := time.Date(timeValue.Year(), timeValue.Month(), timeValue.Day(), time.Now().Hour(), time.Now().Minute(), time.Now().Second(), time.Now().Nanosecond(), time.Local)
  1156 +
  1157 + fmt.Print("销售日期:", saleDateWithTz, "\n")
  1158 +
1049 // 初始化建订单命令集 1159 // 初始化建订单命令集
1050 orderCommands[hashString] = &orderCmd.CreateOrderCommand{ 1160 orderCommands[hashString] = &orderCmd.CreateOrderCommand{
1051 OrderType: 0, 1161 OrderType: 0,
@@ -1053,11 +1163,12 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -1053,11 +1163,12 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
1053 DeliveryCode: row[1], 1163 DeliveryCode: row[1],
1054 BuyerName: row[2], 1164 BuyerName: row[2],
1055 OrderRegion: row[3], 1165 OrderRegion: row[3],
  1166 + SaleDate: saleDateWithTz,
1056 PartnerId: 0, // 根据合伙人类型+合伙人编号查找合伙人id 1167 PartnerId: 0, // 根据合伙人类型+合伙人编号查找合伙人id
1057 SalesmanBonusPercent: sbPercent, 1168 SalesmanBonusPercent: sbPercent,
1058 Goods: []orderCmd.OrderGoodData{ 1169 Goods: []orderCmd.OrderGoodData{
1059 { 1170 {
1060 - GoodName: row[8], 1171 + GoodName: row[9],
1061 PlanGoodNumber: int(amount), 1172 PlanGoodNumber: int(amount),
1062 Price: price, 1173 Price: price,
1063 PartnerBonusPercent: percent, 1174 PartnerBonusPercent: percent,
@@ -1082,14 +1193,14 @@ func (c *OrderInfoController) ImportOrderFromExcel() { @@ -1082,14 +1193,14 @@ func (c *OrderInfoController) ImportOrderFromExcel() {
1082 orderCommands[hashString].PartnerId = partnerInfo.Partner.Id 1193 orderCommands[hashString].PartnerId = partnerInfo.Partner.Id
1083 } 1194 }
1084 } else { 1195 } else {
1085 - //产品相关,8: 产品名称, 9: 数量, 10: 单价, 11: 合伙人分红比例  
1086 - amount, _ := strconv.ParseInt(row[9], 10, 64) // 数量  
1087 - price, _ := strconv.ParseFloat(row[10], 64) // 单价  
1088 - percent, _ := strconv.ParseFloat(row[11], 64) // 合伙人分红比例 1196 + //产品相关,9: 产品名称, 10: 数量, 11: 单价, 12: 合伙人分红比例
  1197 + amount, _ := strconv.ParseInt(row[10], 10, 64) // 数量
  1198 + price, _ := strconv.ParseFloat(row[11], 64) // 单价
  1199 + percent, _ := strconv.ParseFloat(row[12], 64) // 合伙人分红比例
1089 1200
1090 // 记录同一笔订单产品 1201 // 记录同一笔订单产品
1091 orderCommands[hashString].Goods = append(orderCommands[hashString].Goods, orderCmd.OrderGoodData{ 1202 orderCommands[hashString].Goods = append(orderCommands[hashString].Goods, orderCmd.OrderGoodData{
1092 - GoodName: row[8], 1203 + GoodName: row[9],
1093 PlanGoodNumber: int(amount), 1204 PlanGoodNumber: int(amount),
1094 Price: price, 1205 Price: price,
1095 PartnerBonusPercent: percent, 1206 PartnerBonusPercent: percent,
  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("/column-settings/", &controllers.ColumnSettingController{}, "Post:CreateColumnSetting")
  10 + beego.Router("/column-settings/:columnSettingId", &controllers.ColumnSettingController{}, "Put:UpdateColumnSetting")
  11 + beego.Router("/column-settings/:columnSettingId", &controllers.ColumnSettingController{}, "Get:GetColumnSetting")
  12 + beego.Router("/column-settings/:columnSettingId", &controllers.ColumnSettingController{}, "Delete:RemoveColumnSetting")
  13 + beego.Router("/column-settings/", &controllers.ColumnSettingController{}, "Post:ResetColumn")
  14 + beego.Router("/column-settings/", &controllers.ColumnSettingController{}, "Get:ListColumnSetting")
  15 +}
@@ -41,8 +41,13 @@ func init() { @@ -41,8 +41,13 @@ func init() {
41 beego.NSRouter("/actual/del", &controllers.OrderInfoController{}, "POST:RemoveOrderReal"), // 删除实际订单 41 beego.NSRouter("/actual/del", &controllers.OrderInfoController{}, "POST:RemoveOrderReal"), // 删除实际订单
42 beego.NSRouter("/actual/update", &controllers.OrderInfoController{}, "POST:UpdateOrderReal"), // 新增实际订单 42 beego.NSRouter("/actual/update", &controllers.OrderInfoController{}, "POST:UpdateOrderReal"), // 新增实际订单
43 beego.NSRouter("/actual/close", &controllers.OrderInfoController{}, "POST:OrderDisable"), 43 beego.NSRouter("/actual/close", &controllers.OrderInfoController{}, "POST:OrderDisable"),
44 - beego.NSRouter("/fileImportTemplate", &controllers.OrderInfoController{}, "POST:DownloadTemplate"), // 下载导入模板  
45 - beego.NSRouter("/fileImport", &controllers.OrderInfoController{}, "POST:ImportOrderFromExcel"), // 导入订单数据 44 + beego.NSRouter("/fileImportTemplate", &controllers.OrderInfoController{}, "POST:DownloadTemplate"), // 下载导入模板
  45 + beego.NSRouter("/fileImport", &controllers.OrderInfoController{}, "POST:ImportOrderFromExcel"), // 导入订单数据
  46 + beego.NSRouter("/actual/listColumn", &controllers.ColumnSettingController{}, "POST:GetColumnSetting"), // 返回栏目设置列表
  47 + beego.NSRouter("/actual/updateColumn", &controllers.ColumnSettingController{}, "POST:UpdateColumnSetting"), // 更新栏目设置
  48 + beego.NSRouter("/actual/resetColumn", &controllers.ColumnSettingController{}, "POST:ResetColumn"), // 重置栏目设置
  49 + beego.NSRouter("/actual/createColumn", &controllers.ColumnSettingController{}, "POST:CreateColumnSetting"), // 创建栏目设置,测试用
  50 + beego.NSRouter("/actual/listDefaultColumn", &controllers.ColumnSettingController{}, "POST:ListDefaultColumnSetting"), // 返回默认栏目设置
46 ), 51 ),
47 beego.NSNamespace("/common", 52 beego.NSNamespace("/common",
48 beego.NSRouter("/partner", &controllers.CommonController{}, "POST:GetPartnerList"), 53 beego.NSRouter("/partner", &controllers.CommonController{}, "POST:GetPartnerList"),
  1 +package column_setting
  2 +
  3 +import (
  4 + "net/http"
  5 + "net/http/httptest"
  6 + "testing"
  7 +
  8 + "github.com/astaxie/beego"
  9 + . "github.com/onsi/ginkgo"
  10 + . "github.com/onsi/gomega"
  11 + _ "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  12 + _ "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego"
  13 +)
  14 +
  15 +func TestColumnSetting(t *testing.T) {
  16 + RegisterFailHandler(Fail)
  17 + RunSpecs(t, "Beego Port ColumnSetting 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 column_setting
  2 +
  3 +import (
  4 + "net/http"
  5 +
  6 + "github.com/gavv/httpexpect"
  7 + . "github.com/onsi/ginkgo"
  8 + . "github.com/onsi/gomega"
  9 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  10 +)
  11 +
  12 +var _ = Describe("创建栏目设置增删改查", func() {
  13 + Describe("提交数据创建栏目设置增删改查", func() {
  14 + Context("提交正确的新栏目设置数据", func() {
  15 + It("返回栏目设置数据", func() {
  16 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  17 + body := map[string]interface{}{
  18 + "description": "string",
  19 + "userName": "string",
  20 + }
  21 + httpExpect.POST("/column-settings/").
  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 column_settings WHERE true")
  36 + Expect(err).NotTo(HaveOccurred())
  37 + })
  38 +})
  1 +package column_setting
  2 +
  3 +import (
  4 + "net/http"
  5 +
  6 + "github.com/gavv/httpexpect"
  7 + "github.com/go-pg/pg"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("返回栏目设置增删改查", func() {
  14 + var column_settingId int64
  15 + BeforeEach(func() {
  16 + _, err := pG.DB.QueryOne(
  17 + pg.Scan(&column_settingId),
  18 + "INSERT INTO column_settings (column_setting_id, company_id, created_at, description, key, uid, updated_at, user_name, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
  19 + "testColumnSettingId", "testCompanyId", "testCreatedAt", "testDescription", "testKey", "testUid", "testUpdatedAt", "testUserName", "testValue")
  20 + Expect(err).NotTo(HaveOccurred())
  21 + })
  22 + Describe("根据column_settingId参数返回栏目设置", func() {
  23 + Context("传入有效的column_settingId", func() {
  24 + It("返回栏目设置数据", func() {
  25 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  26 + httpExpect.GET("/column-settings/{columnSettingId}").
  27 + Expect().
  28 + Status(http.StatusOK).
  29 + JSON().
  30 + Object().
  31 + ContainsKey("code").ValueEqual("code", 0).
  32 + ContainsKey("msg").ValueEqual("msg", "ok").
  33 + ContainsKey("data").Value("data").Object()
  34 + })
  35 + })
  36 + })
  37 + AfterEach(func() {
  38 + _, err := pG.DB.Exec("DELETE FROM column_settings WHERE true")
  39 + Expect(err).NotTo(HaveOccurred())
  40 + })
  41 +})
  1 +package column_setting
  2 +
  3 +import (
  4 + "net/http"
  5 +
  6 + "github.com/gavv/httpexpect"
  7 + "github.com/go-pg/pg"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("返回栏目设置增删改查列表", func() {
  14 + var column_settingId int64
  15 + BeforeEach(func() {
  16 + _, err := pG.DB.QueryOne(
  17 + pg.Scan(&column_settingId),
  18 + "INSERT INTO column_settings (column_setting_id, company_id, created_at, description, key, uid, updated_at, user_name, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
  19 + "testColumnSettingId", "testCompanyId", "testCreatedAt", "testDescription", "testKey", "testUid", "testUpdatedAt", "testUserName", "testValue")
  20 + Expect(err).NotTo(HaveOccurred())
  21 + })
  22 + Describe("根据参数返回栏目设置列表", func() {
  23 + Context("传入有效的参数", func() {
  24 + It("返回栏目设置数据列表", func() {
  25 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  26 + httpExpect.GET("/column-settings/").
  27 + WithQuery("offset", "int").
  28 + WithQuery("limit", "int").
  29 + Expect().
  30 + Status(http.StatusOK).
  31 + JSON().
  32 + Object().
  33 + ContainsKey("code").ValueEqual("code", 0).
  34 + ContainsKey("msg").ValueEqual("msg", "ok").
  35 + ContainsKey("data").Value("data").Object().
  36 + ContainsKey("count").ValueEqual("count", 1).
  37 + ContainsKey("column_settings").Value("column_settings").Array()
  38 + })
  39 + })
  40 + })
  41 + AfterEach(func() {
  42 + _, err := pG.DB.Exec("DELETE FROM column_settings WHERE true")
  43 + Expect(err).NotTo(HaveOccurred())
  44 + })
  45 +})
  1 +package column_setting
  2 +
  3 +import (
  4 + "net/http"
  5 +
  6 + "github.com/gavv/httpexpect"
  7 + "github.com/go-pg/pg"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("移除栏目设置增删改查", func() {
  14 + var column_settingId int64
  15 + BeforeEach(func() {
  16 + _, err := pG.DB.QueryOne(
  17 + pg.Scan(&column_settingId),
  18 + "INSERT INTO column_settings (column_setting_id, company_id, created_at, description, key, uid, updated_at, user_name, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
  19 + "testColumnSettingId", "testCompanyId", "testCreatedAt", "testDescription", "testKey", "testUid", "testUpdatedAt", "testUserName", "testValue")
  20 + Expect(err).NotTo(HaveOccurred())
  21 + })
  22 + Describe("根据参数移除栏目设置增删改查", func() {
  23 + Context("传入有效的column_settingId", func() {
  24 + It("返回被移除栏目设置的数据", func() {
  25 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  26 + httpExpect.DELETE("/column-settings/{columnSettingId}").
  27 + Expect().
  28 + Status(http.StatusOK).
  29 + JSON().
  30 + Object().
  31 + ContainsKey("code").ValueEqual("code", 0).
  32 + ContainsKey("msg").ValueEqual("msg", "ok").
  33 + ContainsKey("data").Value("data").Object()
  34 + })
  35 + })
  36 + })
  37 + AfterEach(func() {
  38 + _, err := pG.DB.Exec("DELETE FROM column_settings WHERE true")
  39 + Expect(err).NotTo(HaveOccurred())
  40 + })
  41 +})
  1 +package column_setting
  2 +
  3 +import (
  4 + "net/http"
  5 +
  6 + "github.com/gavv/httpexpect"
  7 + "github.com/go-pg/pg"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("重置栏目设置", func() {
  14 + var column_settingId int64
  15 + BeforeEach(func() {
  16 + _, err := pG.DB.QueryOne(
  17 + pg.Scan(&column_settingId),
  18 + "INSERT INTO column_settings (column_setting_id, company_id, created_at, description, key, uid, updated_at, user_name, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
  19 + "testColumnSettingId", "testCompanyId", "testCreatedAt", "testDescription", "testKey", "testUid", "testUpdatedAt", "testUserName", "testValue")
  20 + Expect(err).NotTo(HaveOccurred())
  21 + })
  22 + Describe("重置栏目设置", func() {
  23 + Context("", func() {
  24 + It("", func() {
  25 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  26 + body := map[string]interface{}{}
  27 + httpExpect.POST("/column-settings/").
  28 + WithJSON(body).
  29 + Expect().
  30 + Status(http.StatusOK).
  31 + JSON().
  32 + Object().
  33 + ContainsKey("code").ValueEqual("code", 0).
  34 + ContainsKey("msg").ValueEqual("msg", "ok").
  35 + ContainsKey("data").Value("data").Object()
  36 + })
  37 + })
  38 + })
  39 + AfterEach(func() {
  40 + _, err := pG.DB.Exec("DELETE FROM column_settings WHERE true")
  41 + Expect(err).NotTo(HaveOccurred())
  42 + })
  43 +})
  1 +package column_setting
  2 +
  3 +import (
  4 + "net/http"
  5 +
  6 + "github.com/gavv/httpexpect"
  7 + "github.com/go-pg/pg"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("更新栏目设置增删改查", func() {
  14 + var column_settingId int64
  15 + BeforeEach(func() {
  16 + _, err := pG.DB.QueryOne(
  17 + pg.Scan(&column_settingId),
  18 + "INSERT INTO column_settings (column_setting_id, company_id, created_at, description, key, uid, updated_at, user_name, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
  19 + "testColumnSettingId", "testCompanyId", "testCreatedAt", "testDescription", "testKey", "testUid", "testUpdatedAt", "testUserName", "testValue")
  20 + Expect(err).NotTo(HaveOccurred())
  21 + })
  22 + Describe("提交数据更新栏目设置增删改查", func() {
  23 + Context("提交正确的栏目设置数据", func() {
  24 + It("返回更新后的栏目设置数据", func() {
  25 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  26 + body := map[string]interface{}{}
  27 + httpExpect.PUT("/column-settings/{columnSettingId}").
  28 + WithJSON(body).
  29 + Expect().
  30 + Status(http.StatusOK).
  31 + JSON().
  32 + Object().
  33 + ContainsKey("code").ValueEqual("code", 0).
  34 + ContainsKey("msg").ValueEqual("msg", "ok").
  35 + ContainsKey("data").Value("data").Object().
  36 + ContainsKey("id").ValueEqual("id", column_settingId)
  37 + })
  38 + })
  39 + })
  40 + AfterEach(func() {
  41 + _, err := pG.DB.Exec("DELETE FROM column_settings WHERE true")
  42 + Expect(err).NotTo(HaveOccurred())
  43 + })
  44 +})
  1 +validation
  2 +==============
  3 +
  4 +validation is a form validation for a data validation and error collecting using Go.
  5 +
  6 +## Installation and tests
  7 +
  8 +Install:
  9 +
  10 + go get github.com/astaxie/beego/validation
  11 +
  12 +Test:
  13 +
  14 + go test github.com/astaxie/beego/validation
  15 +
  16 +## Example
  17 +
  18 +Direct Use:
  19 +
  20 + import (
  21 + "github.com/astaxie/beego/validation"
  22 + "log"
  23 + )
  24 +
  25 + type User struct {
  26 + Name string
  27 + Age int
  28 + }
  29 +
  30 + func main() {
  31 + u := User{"man", 40}
  32 + valid := validation.Validation{}
  33 + valid.Required(u.Name, "name")
  34 + valid.MaxSize(u.Name, 15, "nameMax")
  35 + valid.Range(u.Age, 0, 140, "age")
  36 + if valid.HasErrors() {
  37 + // validation does not pass
  38 + // print invalid message
  39 + for _, err := range valid.Errors {
  40 + log.Println(err.Key, err.Message)
  41 + }
  42 + }
  43 + // or use like this
  44 + if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok {
  45 + log.Println(v.Error.Key, v.Error.Message)
  46 + }
  47 + }
  48 +
  49 +Struct Tag Use:
  50 +
  51 + import (
  52 + "github.com/astaxie/beego/validation"
  53 + )
  54 +
  55 + // validation function follow with "valid" tag
  56 + // functions divide with ";"
  57 + // parameters in parentheses "()" and divide with ","
  58 + // Match function's pattern string must in "//"
  59 + type user struct {
  60 + Id int
  61 + Name string `valid:"Required;Match(/^(test)?\\w*@;com$/)"`
  62 + Age int `valid:"Required;Range(1, 140)"`
  63 + }
  64 +
  65 + func main() {
  66 + valid := validation.Validation{}
  67 + // ignore empty field valid
  68 + // see CanSkipFuncs
  69 + // valid := validation.Validation{RequiredFirst:true}
  70 + u := user{Name: "test", Age: 40}
  71 + b, err := valid.Valid(u)
  72 + if err != nil {
  73 + // handle error
  74 + }
  75 + if !b {
  76 + // validation does not pass
  77 + // blabla...
  78 + }
  79 + }
  80 +
  81 +Use custom function:
  82 +
  83 + import (
  84 + "github.com/astaxie/beego/validation"
  85 + )
  86 +
  87 + type user struct {
  88 + Id int
  89 + Name string `valid:"Required;IsMe"`
  90 + Age int `valid:"Required;Range(1, 140)"`
  91 + }
  92 +
  93 + func IsMe(v *validation.Validation, obj interface{}, key string) {
  94 + name, ok:= obj.(string)
  95 + if !ok {
  96 + // wrong use case?
  97 + return
  98 + }
  99 +
  100 + if name != "me" {
  101 + // valid false
  102 + v.SetError("Name", "is not me!")
  103 + }
  104 + }
  105 +
  106 + func main() {
  107 + valid := validation.Validation{}
  108 + if err := validation.AddCustomFunc("IsMe", IsMe); err != nil {
  109 + // hadle error
  110 + }
  111 + u := user{Name: "test", Age: 40}
  112 + b, err := valid.Valid(u)
  113 + if err != nil {
  114 + // handle error
  115 + }
  116 + if !b {
  117 + // validation does not pass
  118 + // blabla...
  119 + }
  120 + }
  121 +
  122 +Struct Tag Functions:
  123 +
  124 + Required
  125 + Min(min int)
  126 + Max(max int)
  127 + Range(min, max int)
  128 + MinSize(min int)
  129 + MaxSize(max int)
  130 + Length(length int)
  131 + Alpha
  132 + Numeric
  133 + AlphaNumeric
  134 + Match(pattern string)
  135 + AlphaDash
  136 + Email
  137 + IP
  138 + Base64
  139 + Mobile
  140 + Tel
  141 + Phone
  142 + ZipCode
  143 +
  144 +
  145 +## LICENSE
  146 +
  147 +BSD License http://creativecommons.org/licenses/BSD/
  1 +// Copyright 2014 beego Author. All Rights Reserved.
  2 +//
  3 +// Licensed under the Apache License, Version 2.0 (the "License");
  4 +// you may not use this file except in compliance with the License.
  5 +// You may obtain a copy of the License at
  6 +//
  7 +// http://www.apache.org/licenses/LICENSE-2.0
  8 +//
  9 +// Unless required by applicable law or agreed to in writing, software
  10 +// distributed under the License is distributed on an "AS IS" BASIS,
  11 +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12 +// See the License for the specific language governing permissions and
  13 +// limitations under the License.
  14 +
  15 +package validation
  16 +
  17 +import (
  18 + "fmt"
  19 + "reflect"
  20 + "regexp"
  21 + "strconv"
  22 + "strings"
  23 +)
  24 +
  25 +const (
  26 + // ValidTag struct tag
  27 + ValidTag = "valid"
  28 +
  29 + LabelTag = "label"
  30 +
  31 + wordsize = 32 << (^uint(0) >> 32 & 1)
  32 +)
  33 +
  34 +var (
  35 + // key: function name
  36 + // value: the number of parameters
  37 + funcs = make(Funcs)
  38 +
  39 + // doesn't belong to validation functions
  40 + unFuncs = map[string]bool{
  41 + "Clear": true,
  42 + "HasErrors": true,
  43 + "ErrorMap": true,
  44 + "Error": true,
  45 + "apply": true,
  46 + "Check": true,
  47 + "Valid": true,
  48 + "NoMatch": true,
  49 + }
  50 + // ErrInt64On32 show 32 bit platform not support int64
  51 + ErrInt64On32 = fmt.Errorf("not support int64 on 32-bit platform")
  52 +)
  53 +
  54 +func init() {
  55 + v := &Validation{}
  56 + t := reflect.TypeOf(v)
  57 + for i := 0; i < t.NumMethod(); i++ {
  58 + m := t.Method(i)
  59 + if !unFuncs[m.Name] {
  60 + funcs[m.Name] = m.Func
  61 + }
  62 + }
  63 +}
  64 +
  65 +// CustomFunc is for custom validate function
  66 +type CustomFunc func(v *Validation, obj interface{}, key string)
  67 +
  68 +// AddCustomFunc Add a custom function to validation
  69 +// The name can not be:
  70 +// Clear
  71 +// HasErrors
  72 +// ErrorMap
  73 +// Error
  74 +// Check
  75 +// Valid
  76 +// NoMatch
  77 +// If the name is same with exists function, it will replace the origin valid function
  78 +func AddCustomFunc(name string, f CustomFunc) error {
  79 + if unFuncs[name] {
  80 + return fmt.Errorf("invalid function name: %s", name)
  81 + }
  82 +
  83 + funcs[name] = reflect.ValueOf(f)
  84 + return nil
  85 +}
  86 +
  87 +// ValidFunc Valid function type
  88 +type ValidFunc struct {
  89 + Name string
  90 + Params []interface{}
  91 +}
  92 +
  93 +// Funcs Validate function map
  94 +type Funcs map[string]reflect.Value
  95 +
  96 +// Call validate values with named type string
  97 +func (f Funcs) Call(name string, params ...interface{}) (result []reflect.Value, err error) {
  98 + defer func() {
  99 + if r := recover(); r != nil {
  100 + err = fmt.Errorf("%v", r)
  101 + }
  102 + }()
  103 + if _, ok := f[name]; !ok {
  104 + err = fmt.Errorf("%s does not exist", name)
  105 + return
  106 + }
  107 + if len(params) != f[name].Type().NumIn() {
  108 + err = fmt.Errorf("The number of params is not adapted")
  109 + return
  110 + }
  111 + in := make([]reflect.Value, len(params))
  112 + for k, param := range params {
  113 + in[k] = reflect.ValueOf(param)
  114 + }
  115 + result = f[name].Call(in)
  116 + return
  117 +}
  118 +
  119 +func isStruct(t reflect.Type) bool {
  120 + return t.Kind() == reflect.Struct
  121 +}
  122 +
  123 +func isStructPtr(t reflect.Type) bool {
  124 + return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
  125 +}
  126 +
  127 +func getValidFuncs(f reflect.StructField) (vfs []ValidFunc, err error) {
  128 + tag := f.Tag.Get(ValidTag)
  129 + label := f.Tag.Get(LabelTag)
  130 + if len(tag) == 0 {
  131 + return
  132 + }
  133 + if vfs, tag, err = getRegFuncs(tag, f.Name); err != nil {
  134 + return
  135 + }
  136 + fs := strings.Split(tag, ";")
  137 + for _, vfunc := range fs {
  138 + var vf ValidFunc
  139 + if len(vfunc) == 0 {
  140 + continue
  141 + }
  142 + vf, err = parseFunc(vfunc, f.Name, label)
  143 + if err != nil {
  144 + return
  145 + }
  146 + vfs = append(vfs, vf)
  147 + }
  148 + return
  149 +}
  150 +
  151 +// Get Match function
  152 +// May be get NoMatch function in the future
  153 +func getRegFuncs(tag, key string) (vfs []ValidFunc, str string, err error) {
  154 + tag = strings.TrimSpace(tag)
  155 + index := strings.Index(tag, "Match(/")
  156 + if index == -1 {
  157 + str = tag
  158 + return
  159 + }
  160 + end := strings.LastIndex(tag, "/)")
  161 + if end < index {
  162 + err = fmt.Errorf("invalid Match function")
  163 + return
  164 + }
  165 + reg, err := regexp.Compile(tag[index+len("Match(/") : end])
  166 + if err != nil {
  167 + return
  168 + }
  169 + vfs = []ValidFunc{{"Match", []interface{}{reg, key + ".Match"}}}
  170 + str = strings.TrimSpace(tag[:index]) + strings.TrimSpace(tag[end+len("/)"):])
  171 + return
  172 +}
  173 +
  174 +func parseFunc(vfunc, key string, label string) (v ValidFunc, err error) {
  175 + defer func() {
  176 + if r := recover(); r != nil {
  177 + err = fmt.Errorf("%v", r)
  178 + }
  179 + }()
  180 +
  181 + vfunc = strings.TrimSpace(vfunc)
  182 + start := strings.Index(vfunc, "(")
  183 + var num int
  184 +
  185 + // doesn't need parameter valid function
  186 + if start == -1 {
  187 + if num, err = numIn(vfunc); err != nil {
  188 + return
  189 + }
  190 + if num != 0 {
  191 + err = fmt.Errorf("%s require %d parameters", vfunc, num)
  192 + return
  193 + }
  194 + v = ValidFunc{vfunc, []interface{}{key + "." + vfunc + "." + label}}
  195 + return
  196 + }
  197 +
  198 + end := strings.Index(vfunc, ")")
  199 + if end == -1 {
  200 + err = fmt.Errorf("invalid valid function")
  201 + return
  202 + }
  203 +
  204 + name := strings.TrimSpace(vfunc[:start])
  205 + if num, err = numIn(name); err != nil {
  206 + return
  207 + }
  208 +
  209 + params := strings.Split(vfunc[start+1:end], ",")
  210 + // the num of param must be equal
  211 + if num != len(params) {
  212 + err = fmt.Errorf("%s require %d parameters", name, num)
  213 + return
  214 + }
  215 +
  216 + tParams, err := trim(name, key+"."+ name + "." + label, params)
  217 + if err != nil {
  218 + return
  219 + }
  220 + v = ValidFunc{name, tParams}
  221 + return
  222 +}
  223 +
  224 +func numIn(name string) (num int, err error) {
  225 + fn, ok := funcs[name]
  226 + if !ok {
  227 + err = fmt.Errorf("doesn't exists %s valid function", name)
  228 + return
  229 + }
  230 + // sub *Validation obj and key
  231 + num = fn.Type().NumIn() - 3
  232 + return
  233 +}
  234 +
  235 +func trim(name, key string, s []string) (ts []interface{}, err error) {
  236 + ts = make([]interface{}, len(s), len(s)+1)
  237 + fn, ok := funcs[name]
  238 + if !ok {
  239 + err = fmt.Errorf("doesn't exists %s valid function", name)
  240 + return
  241 + }
  242 + for i := 0; i < len(s); i++ {
  243 + var param interface{}
  244 + // skip *Validation and obj params
  245 + if param, err = parseParam(fn.Type().In(i+2), strings.TrimSpace(s[i])); err != nil {
  246 + return
  247 + }
  248 + ts[i] = param
  249 + }
  250 + ts = append(ts, key)
  251 + return
  252 +}
  253 +
  254 +// modify the parameters's type to adapt the function input parameters' type
  255 +func parseParam(t reflect.Type, s string) (i interface{}, err error) {
  256 + switch t.Kind() {
  257 + case reflect.Int:
  258 + i, err = strconv.Atoi(s)
  259 + case reflect.Int64:
  260 + if wordsize == 32 {
  261 + return nil, ErrInt64On32
  262 + }
  263 + i, err = strconv.ParseInt(s, 10, 64)
  264 + case reflect.Int32:
  265 + var v int64
  266 + v, err = strconv.ParseInt(s, 10, 32)
  267 + if err == nil {
  268 + i = int32(v)
  269 + }
  270 + case reflect.Int16:
  271 + var v int64
  272 + v, err = strconv.ParseInt(s, 10, 16)
  273 + if err == nil {
  274 + i = int16(v)
  275 + }
  276 + case reflect.Int8:
  277 + var v int64
  278 + v, err = strconv.ParseInt(s, 10, 8)
  279 + if err == nil {
  280 + i = int8(v)
  281 + }
  282 + case reflect.String:
  283 + i = s
  284 + case reflect.Ptr:
  285 + if t.Elem().String() != "regexp.Regexp" {
  286 + err = fmt.Errorf("not support %s", t.Elem().String())
  287 + return
  288 + }
  289 + i, err = regexp.Compile(s)
  290 + default:
  291 + err = fmt.Errorf("not support %s", t.Kind().String())
  292 + }
  293 + return
  294 +}
  295 +
  296 +func mergeParam(v *Validation, obj interface{}, params []interface{}) []interface{} {
  297 + return append([]interface{}{v, obj}, params...)
  298 +}
  1 +// Copyright 2014 beego Author. All Rights Reserved.
  2 +//
  3 +// Licensed under the Apache License, Version 2.0 (the "License");
  4 +// you may not use this file except in compliance with the License.
  5 +// You may obtain a copy of the License at
  6 +//
  7 +// http://www.apache.org/licenses/LICENSE-2.0
  8 +//
  9 +// Unless required by applicable law or agreed to in writing, software
  10 +// distributed under the License is distributed on an "AS IS" BASIS,
  11 +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12 +// See the License for the specific language governing permissions and
  13 +// limitations under the License.
  14 +
  15 +// Package validation for validations
  16 +//
  17 +// import (
  18 +// "github.com/astaxie/beego/validation"
  19 +// "log"
  20 +// )
  21 +//
  22 +// type User struct {
  23 +// Name string
  24 +// Age int
  25 +// }
  26 +//
  27 +// func main() {
  28 +// u := User{"man", 40}
  29 +// valid := validation.Validation{}
  30 +// valid.Required(u.Name, "name")
  31 +// valid.MaxSize(u.Name, 15, "nameMax")
  32 +// valid.Range(u.Age, 0, 140, "age")
  33 +// if valid.HasErrors() {
  34 +// // validation does not pass
  35 +// // print invalid message
  36 +// for _, err := range valid.Errors {
  37 +// log.Println(err.Key, err.Message)
  38 +// }
  39 +// }
  40 +// // or use like this
  41 +// if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok {
  42 +// log.Println(v.Error.Key, v.Error.Message)
  43 +// }
  44 +// }
  45 +//
  46 +// more info: http://beego.me/docs/mvc/controller/validation.md
  47 +package validation
  48 +
  49 +import (
  50 + "fmt"
  51 + "reflect"
  52 + "regexp"
  53 + "strings"
  54 +)
  55 +
  56 +// ValidFormer valid interface
  57 +type ValidFormer interface {
  58 + Valid(*Validation)
  59 +}
  60 +
  61 +// Error show the error
  62 +type Error struct {
  63 + Message, Key, Name, Field, Tmpl string
  64 + Value interface{}
  65 + LimitValue interface{}
  66 +}
  67 +
  68 +// String Returns the Message.
  69 +func (e *Error) String() string {
  70 + if e == nil {
  71 + return ""
  72 + }
  73 + return e.Message
  74 +}
  75 +
  76 +// Implement Error interface.
  77 +// Return e.String()
  78 +func (e *Error) Error() string { return e.String() }
  79 +
  80 +// Result is returned from every validation method.
  81 +// It provides an indication of success, and a pointer to the Error (if any).
  82 +type Result struct {
  83 + Error *Error
  84 + Ok bool
  85 +}
  86 +
  87 +// Key Get Result by given key string.
  88 +func (r *Result) Key(key string) *Result {
  89 + if r.Error != nil {
  90 + r.Error.Key = key
  91 + }
  92 + return r
  93 +}
  94 +
  95 +// Message Set Result message by string or format string with args
  96 +func (r *Result) Message(message string, args ...interface{}) *Result {
  97 + if r.Error != nil {
  98 + if len(args) == 0 {
  99 + r.Error.Message = message
  100 + } else {
  101 + r.Error.Message = fmt.Sprintf(message, args...)
  102 + }
  103 + }
  104 + return r
  105 +}
  106 +
  107 +// A Validation context manages data validation and error messages.
  108 +type Validation struct {
  109 + // if this field set true, in struct tag valid
  110 + // if the struct field vale is empty
  111 + // it will skip those valid functions, see CanSkipFuncs
  112 + RequiredFirst bool
  113 +
  114 + Errors []*Error
  115 + ErrorsMap map[string][]*Error
  116 +}
  117 +
  118 +// Clear Clean all ValidationError.
  119 +func (v *Validation) Clear() {
  120 + v.Errors = []*Error{}
  121 + v.ErrorsMap = nil
  122 +}
  123 +
  124 +// HasErrors Has ValidationError nor not.
  125 +func (v *Validation) HasErrors() bool {
  126 + return len(v.Errors) > 0
  127 +}
  128 +
  129 +// ErrorMap Return the errors mapped by key.
  130 +// If there are multiple validation errors associated with a single key, the
  131 +// first one "wins". (Typically the first validation will be the more basic).
  132 +func (v *Validation) ErrorMap() map[string][]*Error {
  133 + return v.ErrorsMap
  134 +}
  135 +
  136 +// Error Add an error to the validation context.
  137 +func (v *Validation) Error(message string, args ...interface{}) *Result {
  138 + result := (&Result{
  139 + Ok: false,
  140 + Error: &Error{},
  141 + }).Message(message, args...)
  142 + v.Errors = append(v.Errors, result.Error)
  143 + return result
  144 +}
  145 +
  146 +// Required Test that the argument is non-nil and non-empty (if string or list)
  147 +func (v *Validation) Required(obj interface{}, key string) *Result {
  148 + return v.apply(Required{key}, obj)
  149 +}
  150 +
  151 +// Min Test that the obj is greater than min if obj's type is int
  152 +func (v *Validation) Min(obj interface{}, min int, key string) *Result {
  153 + return v.apply(Min{min, key}, obj)
  154 +}
  155 +
  156 +// Max Test that the obj is less than max if obj's type is int
  157 +func (v *Validation) Max(obj interface{}, max int, key string) *Result {
  158 + return v.apply(Max{max, key}, obj)
  159 +}
  160 +
  161 +// Range Test that the obj is between mni and max if obj's type is int
  162 +func (v *Validation) Range(obj interface{}, min, max int, key string) *Result {
  163 + return v.apply(Range{Min{Min: min}, Max{Max: max}, key}, obj)
  164 +}
  165 +
  166 +// MinSize Test that the obj is longer than min size if type is string or slice
  167 +func (v *Validation) MinSize(obj interface{}, min int, key string) *Result {
  168 + return v.apply(MinSize{min, key}, obj)
  169 +}
  170 +
  171 +// MaxSize Test that the obj is shorter than max size if type is string or slice
  172 +func (v *Validation) MaxSize(obj interface{}, max int, key string) *Result {
  173 + return v.apply(MaxSize{max, key}, obj)
  174 +}
  175 +
  176 +// Length Test that the obj is same length to n if type is string or slice
  177 +func (v *Validation) Length(obj interface{}, n int, key string) *Result {
  178 + return v.apply(Length{n, key}, obj)
  179 +}
  180 +
  181 +// Alpha Test that the obj is [a-zA-Z] if type is string
  182 +func (v *Validation) Alpha(obj interface{}, key string) *Result {
  183 + return v.apply(Alpha{key}, obj)
  184 +}
  185 +
  186 +// Numeric Test that the obj is [0-9] if type is string
  187 +func (v *Validation) Numeric(obj interface{}, key string) *Result {
  188 + return v.apply(Numeric{key}, obj)
  189 +}
  190 +
  191 +// AlphaNumeric Test that the obj is [0-9a-zA-Z] if type is string
  192 +func (v *Validation) AlphaNumeric(obj interface{}, key string) *Result {
  193 + return v.apply(AlphaNumeric{key}, obj)
  194 +}
  195 +
  196 +// Match Test that the obj matches regexp if type is string
  197 +func (v *Validation) Match(obj interface{}, regex *regexp.Regexp, key string) *Result {
  198 + return v.apply(Match{regex, key}, obj)
  199 +}
  200 +
  201 +// NoMatch Test that the obj doesn't match regexp if type is string
  202 +func (v *Validation) NoMatch(obj interface{}, regex *regexp.Regexp, key string) *Result {
  203 + return v.apply(NoMatch{Match{Regexp: regex}, key}, obj)
  204 +}
  205 +
  206 +// AlphaDash Test that the obj is [0-9a-zA-Z_-] if type is string
  207 +func (v *Validation) AlphaDash(obj interface{}, key string) *Result {
  208 + return v.apply(AlphaDash{NoMatch{Match: Match{Regexp: alphaDashPattern}}, key}, obj)
  209 +}
  210 +
  211 +// Email Test that the obj is email address if type is string
  212 +func (v *Validation) Email(obj interface{}, key string) *Result {
  213 + return v.apply(Email{Match{Regexp: emailPattern}, key}, obj)
  214 +}
  215 +
  216 +// IP Test that the obj is IP address if type is string
  217 +func (v *Validation) IP(obj interface{}, key string) *Result {
  218 + return v.apply(IP{Match{Regexp: ipPattern}, key}, obj)
  219 +}
  220 +
  221 +// Base64 Test that the obj is base64 encoded if type is string
  222 +func (v *Validation) Base64(obj interface{}, key string) *Result {
  223 + return v.apply(Base64{Match{Regexp: base64Pattern}, key}, obj)
  224 +}
  225 +
  226 +// Mobile Test that the obj is chinese mobile number if type is string
  227 +func (v *Validation) Mobile(obj interface{}, key string) *Result {
  228 + return v.apply(Mobile{Match{Regexp: mobilePattern}, key}, obj)
  229 +}
  230 +
  231 +// Tel Test that the obj is chinese telephone number if type is string
  232 +func (v *Validation) Tel(obj interface{}, key string) *Result {
  233 + return v.apply(Tel{Match{Regexp: telPattern}, key}, obj)
  234 +}
  235 +
  236 +// Phone Test that the obj is chinese mobile or telephone number if type is string
  237 +func (v *Validation) Phone(obj interface{}, key string) *Result {
  238 + return v.apply(Phone{Mobile{Match: Match{Regexp: mobilePattern}},
  239 + Tel{Match: Match{Regexp: telPattern}}, key}, obj)
  240 +}
  241 +
  242 +// ZipCode Test that the obj is chinese zip code if type is string
  243 +func (v *Validation) ZipCode(obj interface{}, key string) *Result {
  244 + return v.apply(ZipCode{Match{Regexp: zipCodePattern}, key}, obj)
  245 +}
  246 +
  247 +func (v *Validation) apply(chk Validator, obj interface{}) *Result {
  248 + if nil == obj {
  249 + if chk.IsSatisfied(obj) {
  250 + return &Result{Ok: true}
  251 + }
  252 + } else if reflect.TypeOf(obj).Kind() == reflect.Ptr {
  253 + if reflect.ValueOf(obj).IsNil() {
  254 + if chk.IsSatisfied(nil) {
  255 + return &Result{Ok: true}
  256 + }
  257 + } else {
  258 + if chk.IsSatisfied(reflect.ValueOf(obj).Elem().Interface()) {
  259 + return &Result{Ok: true}
  260 + }
  261 + }
  262 + } else if chk.IsSatisfied(obj) {
  263 + return &Result{Ok: true}
  264 + }
  265 +
  266 + // Add the error to the validation context.
  267 + key := chk.GetKey()
  268 + Name := key
  269 + Field := ""
  270 + Label := ""
  271 + parts := strings.Split(key, ".")
  272 + if len(parts) == 3 {
  273 + Field = parts[0]
  274 + Name = parts[1]
  275 + Label = parts[2]
  276 + if len(Label) == 0 {
  277 + Label = Field
  278 + }
  279 + }
  280 +
  281 + err := &Error{
  282 + Message: Label + " " + chk.DefaultMessage(),
  283 + Key: key,
  284 + Name: Name,
  285 + Field: Field,
  286 + Value: obj,
  287 + Tmpl: MessageTmpls[Name],
  288 + LimitValue: chk.GetLimitValue(),
  289 + }
  290 + v.setError(err)
  291 +
  292 + // Also return it in the result.
  293 + return &Result{
  294 + Ok: false,
  295 + Error: err,
  296 + }
  297 +}
  298 +
  299 +// key must like aa.bb.cc or aa.bb.
  300 +// AddError adds independent error message for the provided key
  301 +func (v *Validation) AddError(key, message string) {
  302 + Name := key
  303 + Field := ""
  304 +
  305 + Label := ""
  306 + parts := strings.Split(key, ".")
  307 + if len(parts) == 3 {
  308 + Field = parts[0]
  309 + Name = parts[1]
  310 + Label = parts[2]
  311 + if len(Label) == 0 {
  312 + Label = Field
  313 + }
  314 + }
  315 +
  316 + err := &Error{
  317 + Message: Label + " " + message,
  318 + Key: key,
  319 + Name: Name,
  320 + Field: Field,
  321 + }
  322 + v.setError(err)
  323 +}
  324 +
  325 +func (v *Validation) setError(err *Error) {
  326 + v.Errors = append(v.Errors, err)
  327 + if v.ErrorsMap == nil {
  328 + v.ErrorsMap = make(map[string][]*Error)
  329 + }
  330 + if _, ok := v.ErrorsMap[err.Field]; !ok {
  331 + v.ErrorsMap[err.Field] = []*Error{}
  332 + }
  333 + v.ErrorsMap[err.Field] = append(v.ErrorsMap[err.Field], err)
  334 +}
  335 +
  336 +// SetError Set error message for one field in ValidationError
  337 +func (v *Validation) SetError(fieldName string, errMsg string) *Error {
  338 + err := &Error{Key: fieldName, Field: fieldName, Tmpl: errMsg, Message: errMsg}
  339 + v.setError(err)
  340 + return err
  341 +}
  342 +
  343 +// Check Apply a group of validators to a field, in order, and return the
  344 +// ValidationResult from the first one that fails, or the last one that
  345 +// succeeds.
  346 +func (v *Validation) Check(obj interface{}, checks ...Validator) *Result {
  347 + var result *Result
  348 + for _, check := range checks {
  349 + result = v.apply(check, obj)
  350 + if !result.Ok {
  351 + return result
  352 + }
  353 + }
  354 + return result
  355 +}
  356 +
  357 +// Valid Validate a struct.
  358 +// the obj parameter must be a struct or a struct pointer
  359 +func (v *Validation) Valid(obj interface{}) (b bool, err error) {
  360 + objT := reflect.TypeOf(obj)
  361 + objV := reflect.ValueOf(obj)
  362 + switch {
  363 + case isStruct(objT):
  364 + case isStructPtr(objT):
  365 + objT = objT.Elem()
  366 + objV = objV.Elem()
  367 + default:
  368 + err = fmt.Errorf("%v must be a struct or a struct pointer", obj)
  369 + return
  370 + }
  371 +
  372 + for i := 0; i < objT.NumField(); i++ {
  373 + var vfs []ValidFunc
  374 + if vfs, err = getValidFuncs(objT.Field(i)); err != nil {
  375 + return
  376 + }
  377 +
  378 + var hasRequired bool
  379 + for _, vf := range vfs {
  380 + if vf.Name == "Required" {
  381 + hasRequired = true
  382 + }
  383 +
  384 + currentField := objV.Field(i).Interface()
  385 + if objV.Field(i).Kind() == reflect.Ptr {
  386 + if objV.Field(i).IsNil() {
  387 + currentField = ""
  388 + } else {
  389 + currentField = objV.Field(i).Elem().Interface()
  390 + }
  391 + }
  392 +
  393 + chk := Required{""}.IsSatisfied(currentField)
  394 + if !hasRequired && v.RequiredFirst && !chk {
  395 + if _, ok := CanSkipFuncs[vf.Name]; ok {
  396 + continue
  397 + }
  398 + }
  399 +
  400 + if _, err = funcs.Call(vf.Name,
  401 + mergeParam(v, objV.Field(i).Interface(), vf.Params)...); err != nil {
  402 + return
  403 + }
  404 + }
  405 + }
  406 +
  407 + if !v.HasErrors() {
  408 + if form, ok := obj.(ValidFormer); ok {
  409 + form.Valid(v)
  410 + }
  411 + }
  412 +
  413 + return !v.HasErrors(), nil
  414 +}
  415 +
  416 +// RecursiveValid Recursively validate a struct.
  417 +// Step1: Validate by v.Valid
  418 +// Step2: If pass on step1, then reflect obj's fields
  419 +// Step3: Do the Recursively validation to all struct or struct pointer fields
  420 +func (v *Validation) RecursiveValid(objc interface{}) (bool, error) {
  421 + //Step 1: validate obj itself firstly
  422 + // fails if objc is not struct
  423 + pass, err := v.Valid(objc)
  424 + if err != nil || !pass {
  425 + return pass, err // Stop recursive validation
  426 + }
  427 + // Step 2: Validate struct's struct fields
  428 + objT := reflect.TypeOf(objc)
  429 + objV := reflect.ValueOf(objc)
  430 +
  431 + if isStructPtr(objT) {
  432 + objT = objT.Elem()
  433 + objV = objV.Elem()
  434 + }
  435 +
  436 + for i := 0; i < objT.NumField(); i++ {
  437 +
  438 + t := objT.Field(i).Type
  439 +
  440 + // Recursive applies to struct or pointer to structs fields
  441 + if isStruct(t) || isStructPtr(t) {
  442 + // Step 3: do the recursive validation
  443 + // Only valid the Public field recursively
  444 + if objV.Field(i).CanInterface() {
  445 + pass, err = v.RecursiveValid(objV.Field(i).Interface())
  446 + }
  447 + }
  448 + }
  449 + return pass, err
  450 +}
  451 +
  452 +func (v *Validation) CanSkipAlso(skipFunc string) {
  453 + if _, ok := CanSkipFuncs[skipFunc]; !ok {
  454 + CanSkipFuncs[skipFunc] = struct{}{}
  455 + }
  456 +}