作者 Administrator

合并分支 'dev' 到 'master'

Dev



查看合并请求 !4
正在显示 127 个修改的文件 包含 5728 行增加141 行删除
... ... @@ -6,6 +6,8 @@
# Folders
_obj
_test
public/file
logs
# Architecture specific extensions/prefixes
*.[568vq]
... ... @@ -23,3 +25,4 @@ _testmain.go
*.test
.log
.idea
... ...
FROM golang:latest
MAINTAINER linmadan <772181827@qq.com>
FROM 192.168.0.243:5000/mmm/mmm-worth:20201122
#FROM golang:latest
#MAINTAINER linmadan <772181827@qq.com>
ENV APP_DIR $GOPATH/src/mmm-worth
RUN mkdir -p $APP_DIR
WORKDIR $APP_DIR/
... ... @@ -10,6 +11,6 @@ COPY ./main.go main.go
RUN ["ln","-sf","/usr/share/zoneinfo/Asia/Shanghai","/etc/localtime"]
ENV GO111MODULE on
ENV GOPROXY https://goproxy.io
RUN ["go","mod","tidy"]
#RUN ["go","mod","tidy"]
RUN ["go","build"]
ENTRYPOINT ["./mmm-worth"]
\ No newline at end of file
... ...
... ... @@ -39,9 +39,6 @@ spec:
operator: In
values:
- cn-hangzhou.i-bp1djh1xn7taumbue1ze
- cn-hangzhou.i-bp1djh1xn7taumbue1zd
- cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
- cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
containers:
- name: mmm-worth
image: 192.168.0.243:5000/mmm/mmm-worth:dev
... ... @@ -57,11 +54,11 @@ spec:
- name: POSTGRESQL_USER
value: "postgres"
- name: POSTGRESQL_PASSWORD
value: "postgres_15432"
value: "eagle1010"
- name: POSTGRESQL_HOST
value: "101.37.68.23"
value: "114.55.200.59"
- name: POSTGRESQL_PORT
value: "15432"
value: "31543"
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
... ...
... ... @@ -39,9 +39,6 @@ spec:
operator: In
values:
- cn-hangzhou.i-bp1djh1xn7taumbue1ze
- cn-hangzhou.i-bp1djh1xn7taumbue1zd
- cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
- cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
containers:
- name: mmm-worth
image: 192.168.0.243:5000/mmm/mmm-worth:test
... ... @@ -57,11 +54,11 @@ spec:
- name: POSTGRESQL_USER
value: "postgres"
- name: POSTGRESQL_PASSWORD
value: "postgres_15432"
value: "eagle1010"
- name: POSTGRESQL_HOST
value: "101.37.68.23"
value: "114.55.200.59"
- name: POSTGRESQL_PORT
value: "15432"
value: "31543"
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
... ...
... ... @@ -3,6 +3,7 @@ module gitlab.fjmaimaimai.com/linmadan/mmm-worth
go 1.14
require (
github.com/360EntSecGroup-Skylar/excelize/v2 v2.3.1
github.com/ajg/form v1.5.1 // indirect
github.com/astaxie/beego v1.12.1
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
... ... @@ -13,13 +14,14 @@ require (
github.com/gorilla/websocket v1.4.2 // indirect
github.com/imkira/go-interpol v1.1.0 // indirect
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9
github.com/linmadan/egglib-go v0.0.0-20201125083542-25358a549edb
github.com/mattn/go-colorable v0.1.6 // indirect
github.com/moul/http2curl v1.0.0 // indirect
github.com/onsi/ginkgo v1.10.3
github.com/onsi/gomega v1.7.1
github.com/sergi/go-diff v1.1.0 // indirect
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
github.com/shopspring/decimal v1.2.0
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/valyala/fasthttp v1.9.0 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
... ... @@ -27,6 +29,7 @@ require (
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
golang.org/x/tools v0.0.0-20200117065230-39095c1d176c
)
replace gitlab.fjmaimaimai.com/linmadan/mmm-worth => ../mmm-worth
... ...
github.com/360EntSecGroup-Skylar/excelize/v2 v2.3.1 h1:j56fC19WoD3z+u+ZHxm2XwRGyS1XmdSMk7058BLhdsM=
github.com/360EntSecGroup-Skylar/excelize/v2 v2.3.1/go.mod h1:gXEhMjm1VadSGjAzyDlBxmdYglP8eJpYWxpwJnmXRWw=
github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo=
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/OwnLocal/goes v1.0.0/go.mod h1:8rIFjBGTue3lCU0wplczcUgt9Gxgrkkrw7etMIcn8TM=
... ... @@ -79,11 +81,15 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9 h1:zJZsqJ1wFMYb2yrja5S3OZ+oASx4irRksZ8+emFs56M=
github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9/go.mod h1:S1zYn9bb6h+Qzu1aOO8raFhHniewOBaif3YvA9qA6lk=
github.com/linmadan/egglib-go v0.0.0-20201125083542-25358a549edb h1:Ocxw5BWyRrRkTHSsTmQx0UnGsAYZDOwa3K9oGlXF8Jo=
github.com/linmadan/egglib-go v0.0.0-20201125083542-25358a549edb/go.mod h1:S1zYn9bb6h+Qzu1aOO8raFhHniewOBaif3YvA9qA6lk=
github.com/mattn/go-colorable v0.1.6 h1:6Su7aK7lXmJ/U79bYtBjLNaha4Fs1Rg9plHpcH+vvnE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/moul/http2curl v1.0.0 h1:dRMWoAtb+ePxMlLkrCbAqh4TlPHXvoGUSQ323/9Zahs=
github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
... ... @@ -98,10 +104,16 @@ github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6J
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/richardlehane/mscfb v1.0.3 h1:rD8TBkYWkObWO0oLDFCbwMeZ4KoalxQy+QgniCj3nKI=
github.com/richardlehane/mscfb v1.0.3/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=
github.com/richardlehane/msoleps v1.0.1 h1:RfrALnSNXzmXLbGct/P2b4xkFz4e8Gmj/0Vj9M9xC1o=
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw=
github.com/siddontang/ledisdb v0.0.0-20181029004158-becf5f38d373/go.mod h1:mF1DpOSOUiJRMR+FDqaqu3EBqrybQtrDDszLUZ6oxPg=
github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA=
... ... @@ -119,6 +131,8 @@ github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
... ... @@ -134,6 +148,8 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/xuri/efp v0.0.0-20200605144744-ba689101faaf h1:spotWVWg9DP470pPFQ7LaYtUqDpWEOS/BUrSmwFZE4k=
github.com/xuri/efp v0.0.0-20200605144744-ba689101faaf/go.mod h1:uBiSUepVYMhGTfDeBKKasV4GpgBlzJ46gXUBAqV8qLk=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI=
github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA=
... ... @@ -150,6 +166,11 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191029031824-8986dd9e96cf h1:fnPsqIDRbCSgumaMCRpoIoF2s4qxv0xSSS0BVZUE/ss=
golang.org/x/crypto v0.0.0-20191029031824-8986dd9e96cf/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM=
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/image v0.0.0-20200922025426-e59bae62ef32 h1:E+SEVulmY8U4+i6vSB88YSc2OKAFfvbHPU/uDTdQu7M=
golang.org/x/image v0.0.0-20200922025426-e59bae62ef32/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
... ... @@ -160,6 +181,8 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g=
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200904194848-62affa334b73 h1:MXfv8rhZWmFeqX3GNZRsd6vOLoaCHjYEX3qkRo3YBUA=
golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
... ... @@ -173,12 +196,17 @@ golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20200117065230-39095c1d176c h1:FodBYPZKH5tAN2O60HlglMwXGAeV/4k+NKbli79M/2c=
golang.org/x/tools v0.0.0-20200117065230-39095c1d176c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.2/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
... ... @@ -198,5 +226,7 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mellium.im/sasl v0.2.1 h1:nspKSRg7/SyO0cRGY71OkfHab8tf9kCts6a6oTDut0w=
mellium.im/sasl v0.2.1/go.mod h1:ROaEDLQNuf9vjKqE1SrAfnsobm2YKXT1gnN1uDp1PjQ=
... ...
... ... @@ -35,5 +35,10 @@ func main() {
}
}
}()
// excel文件路径映射
beego.SetStaticPath("/download", "download")
beego.SetStaticPath("/logs", "log")
beego.Run()
}
... ...
... ... @@ -21,6 +21,7 @@ func (configService *ConfigService) ListTaskStatus(listTaskStatusQuery *query.Li
4: "待验收",
5: "已完成",
7: "待确认",
8: "已过期",
}
var list []map[string]interface{}
for key, value := range taskStatusMap {
... ... @@ -165,7 +166,7 @@ func (configService *ConfigService) ListBidTimeMatch(listBidTimeMatchQuery *quer
}, nil
}
// 返回员工权限字典列表(1任务管理,2素币管理,3成员管理)
// 返回员工权限字典列表(1任务管理,2素币管理,3成员管理,4标签管理,5排行榜管理
func (configService *ConfigService) ListEmployeePermission(listEmployeePermissionQuery *query.ListEmployeePermissionQuery) (interface{}, error) {
if err := listEmployeePermissionQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
... ... @@ -175,6 +176,7 @@ func (configService *ConfigService) ListEmployeePermission(listEmployeePermissio
2: "素币管理",
3: "成员管理",
4: "标签管理",
5: "排行榜管理",
}
var list []map[string]interface{}
for key, value := range employeePermissionMap {
... ...
... ... @@ -2,7 +2,6 @@ package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
... ...
... ... @@ -2,6 +2,7 @@ package command
import (
"fmt"
"time"
"github.com/astaxie/beego/validation"
)
... ... @@ -15,6 +16,8 @@ type CreateEmployeeCommand struct {
EmployeeAccount string `json:"employeeAccount,omitempty"`
// 员工头像URL
EmployeeAvatarUrl string `json:"employeeAvatarUrl,omitempty"`
// 创建时间
CreateTime time.Time `json:"createTime"`
}
func (createEmployeeCommand *CreateEmployeeCommand) ValidateCommand() error {
... ...
... ... @@ -2,7 +2,6 @@ package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
... ...
... ... @@ -2,6 +2,7 @@ package command
import (
"fmt"
"time"
"github.com/astaxie/beego/validation"
)
... ... @@ -17,6 +18,8 @@ type UpdateEmployeeCommand struct {
EmployeeAvatarUrl string `json:"employeeAvatarUrl,omitempty"`
// 员工权限集合
Permissions []int `json:"permissions,omitempty"`
// 创建时间
CreateTime time.Time `json:"createTime"`
}
func (updateEmployeeCommand *UpdateEmployeeCommand) ValidateCommand() error {
... ...
... ... @@ -13,6 +13,8 @@ type ListEmployeeQuery struct {
EmployeeNameMatch string `json:"employeeNameMatch,omitempty"`
// 查询偏离量
Offset int `json:"offset,omitempty"`
// 员工状态(启用或者禁用)
Status int `json:"status"`
// 查询限制
Limit int `json:"limit,omitempty"`
}
... ...
... ... @@ -8,6 +8,7 @@ import (
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/employee/query"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/factory"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"time"
)
// 员工服务
... ... @@ -36,6 +37,7 @@ func (employeeService *EmployeeService) CreateEmployee(createEmployeeCommand *co
EmployeeAccount: createEmployeeCommand.EmployeeAccount,
},
SuMoney: 0,
CreateTime: time.Now(),
}
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
... ... @@ -122,6 +124,7 @@ func (employeeService *EmployeeService) UpdateEmployee(updateEmployeeCommand *co
if employee == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updateEmployeeCommand.Uid)))
}
updateEmployeeCommand.CreateTime = time.Now()
if err := employee.Update(tool_funs.SimpleStructToMap(updateEmployeeCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
... ... @@ -180,6 +183,7 @@ func (employeeService *EmployeeService) ListEmployee(listEmployeeQuery *query.Li
if err := listEmployeeQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -190,6 +194,7 @@ func (employeeService *EmployeeService) ListEmployee(listEmployeeQuery *query.Li
defer func() {
transactionContext.RollbackTransaction()
}()
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -198,7 +203,13 @@ func (employeeService *EmployeeService) ListEmployee(listEmployeeQuery *query.Li
} else {
employeeRepository = value
}
if count, employees, err := employeeRepository.Find(tool_funs.SimpleStructToMap(listEmployeeQuery)); err != nil {
if count, employees, err := employeeRepository.Find(map[string]interface{}{
"companyId": listEmployeeQuery.CompanyId,
"employeeNameMatch": listEmployeeQuery.EmployeeNameMatch,
"offset": listEmployeeQuery.Offset,
"limit": listEmployeeQuery.Limit,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
... ...
... ... @@ -28,3 +28,19 @@ func CreateNotificationDao(options map[string]interface{}) (*dao.NotificationDao
}
return dao.NewNotificationDao(transactionContext)
}
func CreateCashPoolDao(options map[string]interface{}) (*dao.CashPoolDao, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return dao.NewCashPoolDao(transactionContext)
}
func CreateListIntervalDao(options map[string]interface{}) (*dao.ListIntervalDao, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return dao.NewListIntervalDao(transactionContext)
}
\ No newline at end of file
... ...
... ... @@ -109,3 +109,6 @@ func CreateExchangeSuMoneyService(options map[string]interface{}) (service.Excha
}
return domainService.NewExchangeSuMoneyService(transactionContext)
}
... ...
... ... @@ -85,3 +85,35 @@ func CreateSentNotificationRepository(options map[string]interface{}) (domain.Se
}
return repository.NewSentNotificationRepository(transactionContext)
}
func CreateCashPoolRepository(options map[string]interface{}) (domain.CashPoolRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewCashPoolRepository(transactionContext)
}
func CreateExchangeCashActivityRepository(options map[string]interface{}) (domain.ExchangeActivityRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewExchangeCashActivityRepository(transactionContext)
}
func CreateExchangeCashPersonListRepository(options map[string]interface{}) (domain.ExchangeCashPersonListRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewExchangeCashPersonListRepository(transactionContext)
}
func CreateListIntervalRepository(options map[string]interface{}) (domain.ListIntervalRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewListIntervalRepository(transactionContext)
}
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
"time"
)
type CreateListIntervalCommand struct {
CompanyId int `json:"companyId" valid:"Required"` // 公司id
ListIntervalStartTime time.Time `json:"listIntervalStartTime"` // 排行榜开始时间
ListIntervalEndTime time.Time `json:"listIntervalEndTime"` // 排行榜结束时间
}
func (createListIntervalCommand *CreateListIntervalCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createListIntervalCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type RemoveListIntervalCommand struct {
ListIntervalId int `json:"listIntervalId" valid:"Required"` // 排行榜Id
}
func (removeListIntervalCommand *RemoveListIntervalCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeListIntervalCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
"time"
)
type UpdateListIntervalCommand struct {
ListIntervalId int `json:"listIntervalId" valid:"Required"` // 排行榜id
ListIntervalStartTime time.Time `json:"listIntervalStartTime"` // 排行榜开始时间
ListIntervalEndTime time.Time `json:"listIntervalEndTime"` // 排行榜结束时间
}
func (updateListIntervalCommand *UpdateListIntervalCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateListIntervalCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type GetListIntervalQuery struct {
ListIntervalId int `json:"listIntervalId"` // 排行榜id
}
func (getListIntervalQuery *GetListIntervalQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getListIntervalQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ListListIntervalQuery struct {
CompanyId int `json:"companyId"` // 公司id
Offset int `json:"offset,omitempty"` // 查询偏离量
Limit int `json:"limit,omitempty"` // 查询限制
}
func (listListIntervalQuery *ListListIntervalQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listListIntervalQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/factory"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/listInterval/command"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/listInterval/query"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/dao"
"time"
)
type ListIntervalService struct {
}
// 创建排行榜时间
func (listIntervalService *ListIntervalService) CreateListInterval(createListIntervalCommand *command.CreateListIntervalCommand) (interface{}, error) {
if err := createListIntervalCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
// 排行榜时间仓储初始化
var listIntervalRepository domain.ListIntervalRepository
if value, err := factory.CreateListIntervalRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
listIntervalRepository = value
}
// 排行榜管理DAO初始化
var listIntervalDao *dao.ListIntervalDao
if value, err := factory.CreateListIntervalDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
listIntervalDao = value
}
// 获取当前最新排行榜时间
listListIntervalQuery := &query.ListListIntervalQuery {
CompanyId: createListIntervalCommand.CompanyId,
Offset: 0,
Limit: 1,
}
// 获取上个年榜时间
_, listIntervals, err := listIntervalRepository.Find(tool_funs.SimpleStructToMap(listListIntervalQuery))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
startTime := time.Date(createListIntervalCommand.ListIntervalStartTime.Local().Year(), createListIntervalCommand.ListIntervalStartTime.Local().Month(), createListIntervalCommand.ListIntervalStartTime.Local().Day(), 0, 0, 0, 0, time.Local)
endTime := time.Date(createListIntervalCommand.ListIntervalEndTime.Local().Year(), createListIntervalCommand.ListIntervalEndTime.Local().Month(), createListIntervalCommand.ListIntervalEndTime.Local().Day(), 23, 59, 59, 0, time.Local)
// 判断年榜时间是否重叠
if len(listIntervals) > 0 {
ok := listIntervalDao.RankPeriodCheckTime(startTime.Local().Unix(), endTime.Local().Unix(), 0, listIntervals[0].CompanyId)
if !ok {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "年榜时间不能重叠")
}
}
// 创建排行榜时间
newListInterval := &domain.ListInterval {
CompanyId: createListIntervalCommand.CompanyId,
IntervalStartTime: startTime,
IntervalEndTime: endTime,
}
listInterval, err := listIntervalRepository.Save(newListInterval)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return listInterval, nil
}
// 返回排行榜时间列表
func (listIntervalService *ListIntervalService) ListListInterval(listListIntervalQuery *query.ListListIntervalQuery) (interface{}, error) {
if err := listListIntervalQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var listIntervalRepository domain.ListIntervalRepository
if value, err := factory.CreateListIntervalRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
listIntervalRepository = value
}
if count, listIntervals, err := listIntervalRepository.Find(tool_funs.SimpleStructToMap(listListIntervalQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"listIntervals": listIntervals,
}, nil
}
}
// 返回排行榜时间
func (listIntervalService *ListIntervalService) GetListInterval(getListIntervalQuery *query.GetListIntervalQuery) (interface{}, error) {
if err := getListIntervalQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var listIntervalRepository domain.ListIntervalRepository
if value, err := factory.CreateListIntervalRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
listIntervalRepository = value
}
listInterval, err := listIntervalRepository.FindOne(map[string]interface{}{"listId": getListIntervalQuery.ListIntervalId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if listInterval == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getListIntervalQuery.ListIntervalId)))
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return listInterval, nil
}
}
// 更新排行榜时间
func (listIntervalService *ListIntervalService) UpdateListInterval(updateListIntervalCommand *command.UpdateListIntervalCommand) (interface{}, error) {
if err := updateListIntervalCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
// 排行榜管理仓储初始化
var listIntervalRepository domain.ListIntervalRepository
if value, err := factory.CreateListIntervalRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
listIntervalRepository = value
}
// 排行榜管理DAO初始化
var listIntervalDao *dao.ListIntervalDao
if value, err := factory.CreateListIntervalDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
listIntervalDao = value
}
// 获取当前年榜
listIntervalFound, err := listIntervalRepository.FindOne(map[string]interface{}{"listId": updateListIntervalCommand.ListIntervalId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if listIntervalFound == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updateListIntervalCommand.ListIntervalId)))
}
// 当前更新的开始结束时间
startTime := time.Date(updateListIntervalCommand.ListIntervalStartTime.Local().Year(), updateListIntervalCommand.ListIntervalStartTime.Local().Month(), updateListIntervalCommand.ListIntervalStartTime.Local().Day(), 0, 0, 0, 0, time.Local)
endTime := time.Date(updateListIntervalCommand.ListIntervalEndTime.Local().Year(), updateListIntervalCommand.ListIntervalEndTime.Local().Month(), updateListIntervalCommand.ListIntervalEndTime.Local().Day(), 23, 59, 59, 0, time.Local)
updateListIntervalCommand.ListIntervalStartTime = startTime
updateListIntervalCommand.ListIntervalEndTime = endTime
// 判断年榜时间是否重叠
ok := listIntervalDao.RankPeriodCheckTime(startTime.Unix(), endTime.Unix(), listIntervalFound.ListIntervalId, listIntervalFound.CompanyId)
if !ok {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "年榜时间不能重叠")
}
// 更新年榜
if err := listIntervalFound.Update(tool_funs.SimpleStructToMap(updateListIntervalCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if listIntervalUpdated, err := listIntervalRepository.Save(listIntervalFound); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return listIntervalUpdated, nil
}
}
// 移除排行榜时间
func (listIntervalService *ListIntervalService) RemoveListInterval(removeListIntervalCommand *command.RemoveListIntervalCommand) (interface{}, error) {
if err := removeListIntervalCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var listIntervalRepository domain.ListIntervalRepository
if value, err := factory.CreateListIntervalRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
listIntervalRepository = value
}
listInterval, err := listIntervalRepository.FindOne(map[string]interface{}{"listId": removeListIntervalCommand.ListIntervalId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if listInterval == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removeListIntervalCommand.ListIntervalId)))
}
if listInterval, err := listIntervalRepository.Remove(listInterval); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return listInterval, nil
}
}
func NewListIntervalService(options map[string] interface{}) *ListIntervalService {
newListIntervalService := &ListIntervalService{}
return newListIntervalService
}
\ No newline at end of file
... ...
... ... @@ -28,6 +28,7 @@ func (notificationService *NotificationService) SystemNotificationNearThePlanned
defer func() {
transactionContext.RollbackTransaction()
}()
var notificationRepository domain.NotificationRepository
if value, err := factory.CreateNotificationRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -36,6 +37,7 @@ func (notificationService *NotificationService) SystemNotificationNearThePlanned
} else {
notificationRepository = value
}
var sentNotificationRepository domain.SentNotificationRepository
if value, err := factory.CreateSentNotificationRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -44,6 +46,7 @@ func (notificationService *NotificationService) SystemNotificationNearThePlanned
} else {
sentNotificationRepository = value
}
var taskDao *dao.TaskDao
if value, err := factory.CreateTaskDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -52,6 +55,13 @@ func (notificationService *NotificationService) SystemNotificationNearThePlanned
} else {
taskDao = value
}
// 更新已过期竞标任务状态
if err := taskDao.UpdateExpiredPlannedCompletionTimeBidTask(); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
// 返回快过期任务并发送消息
if tasks, err := taskDao.ListNearThePlannedCompletionTimeTask(); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -88,6 +98,7 @@ func (notificationService *NotificationService) SystemNotificationNearThePlanned
}
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
... ... @@ -108,6 +119,7 @@ func (notificationService *NotificationService) SystemNotificationNearBidEndTime
defer func() {
transactionContext.RollbackTransaction()
}()
var notificationRepository domain.NotificationRepository
if value, err := factory.CreateNotificationRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -116,6 +128,7 @@ func (notificationService *NotificationService) SystemNotificationNearBidEndTime
} else {
notificationRepository = value
}
var sentNotificationRepository domain.SentNotificationRepository
if value, err := factory.CreateSentNotificationRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -124,6 +137,7 @@ func (notificationService *NotificationService) SystemNotificationNearBidEndTime
} else {
sentNotificationRepository = value
}
var taskDao *dao.TaskDao
if value, err := factory.CreateTaskDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -132,6 +146,7 @@ func (notificationService *NotificationService) SystemNotificationNearBidEndTime
} else {
taskDao = value
}
if tasks, err := taskDao.ListNearBidEndTimeTask(); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
"time"
)
type EmployeesContributionsStatisticsCommand struct {
CompanyId int `json:"companyId" valid:"Required"` // 公司id
StartTime time.Time `json:"startTime"` // 年榜开始时间
EndTime time.Time `json:"endTime"` // 年榜结束时间
}
func (employeesContributionsStatisticsCommand *EmployeesContributionsStatisticsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(employeesContributionsStatisticsCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"time"
"github.com/astaxie/beego/validation"
)
type EmployeesSuMoneyStatisticsCommand struct {
CompanyId int `json:"companyId" valid:"Required"` // 公司id
StartTime time.Time `json:"startTime"` // 年榜开始时间
EndTime time.Time `json:"endTime"` // 年榜结束时间
}
func (employeesSuMoneyStatisticsCommand *EmployeesSuMoneyStatisticsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(employeesSuMoneyStatisticsCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
"time"
)
type EmployeesRankingListStatisticsCommand struct {
CompanyId int `json:"companyId" valid:"Required"` // 公司id
StartTime time.Time `json:"startTime"` // 年榜开始时间
EndTime time.Time `json:"endTime"` // 年榜结束时间
Offset int `json:"offset,omitempty"` // 查询偏离量
Limit int `json:"limit,omitempty"` // 查询限制
}
func (employeesRankingListStatisticsCommand *EmployeesRankingListStatisticsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(employeesRankingListStatisticsCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
... ... @@ -9,6 +9,7 @@ import (
type PersonTaskStatisticsCommand struct {
// 统一用户UID
Uid int64 `json:"uid" valid:"Required"`
CompanyId int `json:"companyId" valid:"Required"`
}
func (personTaskStatisticsCommand *PersonTaskStatisticsCommand) ValidateCommand() error {
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 获取系统现金值
type SystemCashStatisticsCommand struct {
CompanyId int64 `json:"companyId" valid:"Required"` // 公司ID
}
func (systemCashStatisticsCommand *SystemCashStatisticsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(systemCashStatisticsCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 获取系统素币值
type SystemSuMoneyStatisticsCommand struct {
CompanyId int64 `json:"companyId" valid:"Required"` // 公司ID
}
func (systemSuMoneyStatisticsCommand *SystemSuMoneyStatisticsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(systemSuMoneyStatisticsCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
... ... @@ -2,10 +2,13 @@ package service
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/factory"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/statistics/command"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/suMoney/query"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/dao"
"time"
)
// 数据统计服务
... ... @@ -27,6 +30,7 @@ func (statisticsService *StatisticsService) PersonNotificationStatistics(personN
defer func() {
transactionContext.RollbackTransaction()
}()
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -35,6 +39,7 @@ func (statisticsService *StatisticsService) PersonNotificationStatistics(personN
} else {
employeeDao = value
}
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -43,6 +48,7 @@ func (statisticsService *StatisticsService) PersonNotificationStatistics(personN
} else {
employeeRepository = value
}
employee, err := employeeRepository.FindOne(map[string]interface{}{
"uid": personNotificationStatisticsCommand.Uid,
})
... ... @@ -52,6 +58,7 @@ func (statisticsService *StatisticsService) PersonNotificationStatistics(personN
if employee == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的企业员工")
}
if personNotificationStatistics, err := employeeDao.CalculatePersonUnReadNotification(personNotificationStatisticsCommand.Uid); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -77,6 +84,7 @@ func (statisticsService *StatisticsService) SystemTaskStatistics(systemTaskStati
defer func() {
transactionContext.RollbackTransaction()
}()
var taskDao *dao.TaskDao
if value, err := factory.CreateTaskDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -85,6 +93,7 @@ func (statisticsService *StatisticsService) SystemTaskStatistics(systemTaskStati
} else {
taskDao = value
}
if systemTaskStatistics, err := taskDao.CalculateSystemTask(systemTaskStatisticsCommand.CompanyId); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -110,6 +119,7 @@ func (statisticsService *StatisticsService) PersonTaskStatistics(personTaskStati
defer func() {
transactionContext.RollbackTransaction()
}()
var taskDao *dao.TaskDao
if value, err := factory.CreateTaskDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -118,6 +128,7 @@ func (statisticsService *StatisticsService) PersonTaskStatistics(personTaskStati
} else {
taskDao = value
}
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -126,6 +137,7 @@ func (statisticsService *StatisticsService) PersonTaskStatistics(personTaskStati
} else {
employeeRepository = value
}
employee, err := employeeRepository.FindOne(map[string]interface{}{
"uid": personTaskStatisticsCommand.Uid,
})
... ... @@ -135,7 +147,8 @@ func (statisticsService *StatisticsService) PersonTaskStatistics(personTaskStati
if employee == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的企业员工")
}
if personTaskStatistics, err := taskDao.CalculatePersonTask(personTaskStatisticsCommand.Uid); err != nil {
if personTaskStatistics, err := taskDao.CalculatePersonTask(personTaskStatisticsCommand.Uid, personTaskStatisticsCommand.CompanyId); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
... ... @@ -160,6 +173,7 @@ func (statisticsService *StatisticsService) PersonSuMoneyStatistics(personSuMone
defer func() {
transactionContext.RollbackTransaction()
}()
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -168,6 +182,7 @@ func (statisticsService *StatisticsService) PersonSuMoneyStatistics(personSuMone
} else {
employeeDao = value
}
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -176,6 +191,7 @@ func (statisticsService *StatisticsService) PersonSuMoneyStatistics(personSuMone
} else {
employeeRepository = value
}
employee, err := employeeRepository.FindOne(map[string]interface{}{
"uid": personSuMoneyStatisticsCommand.Uid,
})
... ... @@ -185,6 +201,7 @@ func (statisticsService *StatisticsService) PersonSuMoneyStatistics(personSuMone
if employee == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的企业员工")
}
if personSuMoneyStatistics, err := employeeDao.CalculatePersonSuMoney(personSuMoneyStatisticsCommand.Uid); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -196,6 +213,327 @@ func (statisticsService *StatisticsService) PersonSuMoneyStatistics(personSuMone
}
}
// 获取系统素币统计
func (statisticsService *StatisticsService) SystemSuMoneyStatistics(systemSuMoneyStatisticsCommand *command.SystemSuMoneyStatisticsCommand) (interface{}, error) {
if err := systemSuMoneyStatisticsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
employeeDao = value
}
if systemSuMoneyStatistics, err := employeeDao.CalculateSystemSuMoney(systemSuMoneyStatisticsCommand.CompanyId); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return systemSuMoneyStatistics, nil
}
}
// 获取系统现金统计
func (statisticsService *StatisticsService) SystemCashStatistics(systemCashStatisticsCommand *command.SystemCashStatisticsCommand) (interface{}, error) {
if err := systemCashStatisticsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
employeeDao = value
}
// 判断现金池是否存在
var cashPoolRepository domain.CashPoolRepository
if value, err := factory.CreateCashPoolRepository(map[string] interface{} {
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
cashPoolRepository = value
}
countCashPools, _, err := cashPoolRepository.Find(tool_funs.SimpleStructToMap(systemCashStatisticsCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if countCashPools == 0 { // 现金池为空时处理
return map[string]interface{} {
"systemExchangedCash" : 0,
"systemUnExchangeCash": 0,
}, nil
}
if systemCashStatistics, err := employeeDao.CalculateSystemCash(systemCashStatisticsCommand.CompanyId); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return systemCashStatistics, nil
}
}
// 获取公司员工财富值分组统计
func (statisticsService *StatisticsService) EmployeesSuMoneyStatistics(employeesSuMoneyStatisticsCommand *command.EmployeesSuMoneyStatisticsCommand) (interface{}, error) {
if err := employeesSuMoneyStatisticsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
employeeDao = value
}
if employeesSuMoneyStatisticsCommand.StartTime.IsZero() && employeesSuMoneyStatisticsCommand.EndTime.IsZero() {
employeesSuMoneyStatisticsCommand.StartTime = time.Date(1971, time.Month(1), 1, 0, 0, 0, 0, time.Now().Location())
employeesSuMoneyStatisticsCommand.EndTime = time.Now().Local()
}
if employeesSuMoneyStatistics, err := employeeDao.CalculateEmployeesSuMoney(employeesSuMoneyStatisticsCommand.CompanyId, employeesSuMoneyStatisticsCommand.StartTime, employeesSuMoneyStatisticsCommand.EndTime); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return employeesSuMoneyStatistics, nil
}
}
// 获取公司员工贡献值分组统计
func (statisticsService *StatisticsService) EmployeesContributionsStatistics(employeesContributionsStatisticsCommand *command.EmployeesContributionsStatisticsCommand) (interface{}, error) {
if err := employeesContributionsStatisticsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
employeeDao = value
}
if employeesContributionsStatisticsCommand.StartTime.IsZero() && employeesContributionsStatisticsCommand.EndTime.IsZero() {
employeesContributionsStatisticsCommand.StartTime = time.Date(1971, time.Month(1), 1, 0, 0, 0, 0, time.Now().Location())
employeesContributionsStatisticsCommand.EndTime = time.Now().Local()
}
if employeesContributionsStatistics, err := employeeDao.CalculateEmployeesContributions(employeesContributionsStatisticsCommand.CompanyId, employeesContributionsStatisticsCommand.StartTime, employeesContributionsStatisticsCommand.EndTime); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return employeesContributionsStatistics, nil
}
}
// 贡献值、财富值榜单
func (statisticsService *StatisticsService) ContributionsWealthRanking(contributionsWealthRankingQuery *query.ContributionsWealthRankingQuery) (interface{}, error) {
if err := contributionsWealthRankingQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
// 员工仓储初始化
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
employeeRepository = value
}
// 员工DAO初始化
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
employeeDao = value
}
if contributionsWealthRankingQuery.RankingType == 1 { // 返回总榜
contributionsWealthRankingQuery.StartTime = time.Date(0001, 01, 01, 0, 0, 0, 0, time.UTC)
contributionsWealthRankingQuery.EndTime = time.Date(0001, 01, 01, 0, 0, 0, 0, time.UTC)
} else if contributionsWealthRankingQuery.RankingType == 2 { // 返回年榜
// 获取公司最新年榜
var listIntervalRepository domain.ListIntervalRepository
if value, err := factory.CreateListIntervalRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
listIntervalRepository = value
}
listListIntervalQuery := map[string]interface{} {
"companyId": contributionsWealthRankingQuery.CompanyId,
}
if _, listIntervals, err := listIntervalRepository.FindAll(listListIntervalQuery); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if len(listIntervals) == 0 { // 未配置年榜
contributionsWealthRankingQuery.StartTime = time.Date(0001, 01, 02, 0, 0, 0, 0, time.Local)
contributionsWealthRankingQuery.EndTime = time.Date(0001, 01, 02, 0, 0, 0, 0, time.Local)
} else if len(listIntervals) == 1 { // 只配置了一个年榜
currentTime := time.Now().Unix()
if currentTime >= listIntervals[0].IntervalStartTime.Unix() && currentTime <= listIntervals[0].IntervalEndTime.Unix() {
contributionsWealthRankingQuery.StartTime = listIntervals[0].IntervalStartTime
contributionsWealthRankingQuery.EndTime = listIntervals[0].IntervalEndTime
} else { // 当前时间处于空档期
contributionsWealthRankingQuery.StartTime = time.Date(0001, 01, 02, 0, 0, 0, 0, time.Local)
contributionsWealthRankingQuery.EndTime = time.Date(0001, 01, 02, 0, 0, 0, 0, time.Local)
}
} else if len(listIntervals) > 1 { // 配置了多个年榜,判断当前时间是否在榜单里
currentTime := time.Now().Unix()
for _, listInterval := range listIntervals {
if currentTime >= listInterval.IntervalStartTime.Unix() && currentTime <= listInterval.IntervalEndTime.Unix() {
contributionsWealthRankingQuery.StartTime = listInterval.IntervalStartTime
contributionsWealthRankingQuery.EndTime = listInterval.IntervalEndTime
break
} else { // 当前时间处于空档期
contributionsWealthRankingQuery.StartTime = time.Date(0001, 01, 02, 0, 0, 0, 0, time.Local)
contributionsWealthRankingQuery.EndTime = time.Date(0001, 01, 02, 0, 0, 0, 0, time.Local)
continue
}
}
} else {
contributionsWealthRankingQuery.StartTime = time.Date(0001, 01, 02, 0, 0, 0, 0, time.Local)
contributionsWealthRankingQuery.EndTime = time.Date(0001, 01, 02, 0, 0, 0, 0, time.Local)
}
}
}
// 默认返回总榜
if contributionsWealthRankingStatistics, err := employeeDao.ContributionsWealthRanking(tool_funs.SimpleStructToMap(contributionsWealthRankingQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
uidName := map[int64]interface{}{}
if _, employees, err := employeeRepository.FindAll(map[string]interface{}{
"companyId": contributionsWealthRankingQuery.CompanyId,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
for _, employee := range employees {
uidName[employee.EmployeeInfo.Uid] = employee.EmployeeInfo.EmployeeName
}
}
// 财富值排行榜
for i, _ := range contributionsWealthRankingStatistics.(map[string]interface{})["employeesWealth"].([]struct{Uid int64;EmployeeName string;EmployeeSuMoney float64;Ranking int}) {
uid := contributionsWealthRankingStatistics.(map[string]interface{})["employeesWealth"].([]struct{Uid int64;EmployeeName string;EmployeeSuMoney float64;Ranking int})[i].Uid
if uidName[uid] != nil {
contributionsWealthRankingStatistics.(map[string]interface{})["employeesWealth"].([]struct{Uid int64;EmployeeName string;EmployeeSuMoney float64;Ranking int})[i].EmployeeName = uidName[uid].(string)
}
}
// 个人财富值
if contributionsWealthRankingStatistics.(map[string]interface{})["currentEmployeeWealth"] != nil {
currentEmployeeWealth := contributionsWealthRankingStatistics.(map[string]interface{})["currentEmployeeWealth"].(struct{Uid int64;EmployeeName string;EmployeeSuMoney float64;Ranking int})
uidWealth := contributionsWealthRankingStatistics.(map[string]interface{})["currentEmployeeWealth"].(struct{Uid int64;EmployeeName string;EmployeeSuMoney float64;Ranking int}).Uid
if uidName[uidWealth] != nil {
currentEmployeeWealth.EmployeeName = uidName[uidWealth].(string)
}
contributionsWealthRankingStatistics.(map[string]interface{})["currentEmployeeWealth"] = currentEmployeeWealth
}
// 贡献值排行版
for i, _ := range contributionsWealthRankingStatistics.(map[string]interface{})["employeesContributions"].([]struct { Uid int64; EmployeeName string; EmployeesContributions float64; Ranking int }) {
uid := contributionsWealthRankingStatistics.(map[string]interface{})["employeesContributions"].([]struct{Uid int64;EmployeeName string;EmployeesContributions float64;Ranking int})[i].Uid
if uidName[uid] != nil {
contributionsWealthRankingStatistics.(map[string]interface{})["employeesContributions"].([]struct{Uid int64;EmployeeName string;EmployeesContributions float64;Ranking int})[i].EmployeeName = uidName[uid].(string)
}
}
// 个人贡献值
if contributionsWealthRankingStatistics.(map[string]interface{})["currentEmployeeContributions"] != nil {
currentEmployeeContributions := contributionsWealthRankingStatistics.(map[string]interface{})["currentEmployeeContributions"].(struct{Uid int64;EmployeeName string;EmployeesContributions float64;Ranking int})
uidContributions := contributionsWealthRankingStatistics.(map[string]interface{})["currentEmployeeContributions"].(struct{Uid int64;EmployeeName string;EmployeesContributions float64;Ranking int}).Uid
if uidName[uidContributions] != nil {
currentEmployeeContributions.EmployeeName = uidName[uidContributions].(string)
}
contributionsWealthRankingStatistics.(map[string]interface{})["currentEmployeeContributions"] = currentEmployeeContributions
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return contributionsWealthRankingStatistics, nil
}
}
func NewStatisticsService(options map[string]interface{}) *StatisticsService {
newStatisticsService := &StatisticsService{}
return newStatisticsService
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
"time"
)
type ContributionsTransactionRecordStatisticsCommand struct {
// 统一用户UID
Uid int64 `json:"uid" valid:"Required"`
// 事务时间区间-开始时间
TransactionStartTime time.Time `json:"transactionStartTime,omitempty"`
// 事务时间区间-截止时间
TransactionEndTime time.Time `json:"transactionEndTime,omitempty"`
}
func (contributionsTransactionRecordStatisticsCommand *ContributionsTransactionRecordStatisticsCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(contributionsTransactionRecordStatisticsCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 创建现金池
type CreateCashPoolCommand struct {
CompanyId int64 `json:"companyId" valid:"Required"` // 公司ID
Cash float64 `json:"cash" valid:"Required"` // 投入的现金值
}
func (createCashPoolCommand *CreateCashPoolCommand) ValidateCommand() error {
valid := validation.Validation{}
rt, err := valid.Valid(createCashPoolCommand)
if err != nil {
return err
}
if !rt {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
"time"
)
// 创建现金兑换活动
type CreateExchangeCashActivityCommand struct {
CompanyId int64 `json:"companyId" valid:"Required"` // 公司id
ExchangeActivityName string `json:"exchangeActivityName"` // 活动名称
Deadline time.Time `json:"deadline"` // 活动截止时间
ExchangeRate float64 `json:"exchangeRate"` // 兑换汇率
CreateTime time.Time `json:"createTime"` // 创建时间
}
func (createExchangeActivityCommand *CreateExchangeCashActivityCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createExchangeActivityCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type CreateExchangeCashPersonCommand struct {
Uid int64 `json:"uid"` // 统一用户id
PersonName string `json:"personName,omitempty"` // 兑换现金人员名称
Operator int64 `json:"operator"` // 操作人
PersonAccount string `json:"personAccount,omitempty"` // 手机账号
ExchangeCashActivityId int64 `json:"exchangeCashActivityId" valid:"Required"` // 参与的兑换活动id
ExchangedSuMoney float64 `json:"exchangedSuMoney"` // 已兑换素币值
}
func (createExchangeCashPersonCommand *CreateExchangeCashPersonCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createExchangeCashPersonCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
... ... @@ -7,14 +7,10 @@ import (
)
type ExchangeSuMoneyCommand struct {
// 兑换人UID
Uid int64 `json:"uid" valid:"Required"`
// 素币值
SuMoney float64 `json:"suMoney" valid:"Required"`
// 操作人UID
Operator int64 `json:"operator,omitempty"`
// 兑换描述
ExchangeDescription string `json:"exchangeDescription" valid:"Required"`
Uid int64 `json:"uid" valid:"Required"` // 兑换人UID
SuMoney float64 `json:"suMoney" valid:"Required"` // 素币值
Operator int64 `json:"operator,omitempty"` // 操作人UID
ExchangeDescription string `json:"exchangeDescription" valid:"Required"` // 兑换描述
}
func (exchangeSuMoneyCommand *ExchangeSuMoneyCommand) ValidateCommand() error {
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ExportExchangeCashListCommand struct {
Ids []int `json:"ids"`
Where map[string]interface{} `json:"where"`
}
func (exportExchangeCashListCommand *ExportExchangeCashListCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(exportExchangeCashListCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ExportSuMoneyCommand struct {
Ids []int `json:"ids"` // 员工uid
Where map[string]interface{} `json:"where"`
}
func (exportSuMoneyCommand *ExportSuMoneyCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(exportSuMoneyCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ExportTransactionRecordCommand struct {
Ids []int `json:"ids"`
Where map[string]interface{} `json:"where"`
}
func (exportTransactionRecordCommand *ExportTransactionRecordCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(exportTransactionRecordCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ImportExchangeCashListCommand struct {
Where map[string]interface{} `json:"where"`
}
func (importExchangeCashListCommand *ImportExchangeCashListCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(importExchangeCashListCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
... ... @@ -7,16 +7,11 @@ import (
)
type OperationSuMoneyCommand struct {
// 素币拥有者UID
Uid int64 `json:"uid" valid:"Required"`
// 操作类型(1增加,2扣除)
OperationType int `json:"operationType" valid:"Required"`
// 素币值
SuMoney float64 `json:"suMoney" valid:"Required"`
// 操作人UID
Operator int64 `json:"operator,omitempty"`
// 理由描述
OperationDescription string `json:"operationDescription" valid:"Required"`
Uid int64 `json:"uid" valid:"Required"` // 素币拥有者UID
OperationType int `json:"operationType" valid:"Required"` // 操作类型(1增加,2扣除, 3兑换物资, 4兑换现金)
SuMoney float64 `json:"suMoney" valid:"Required"` // 素币值
Operator int64 `json:"operator,omitempty"` // 操作人UID
OperationDescription string `json:"operationDescription" valid:"Required"` // 理由描述
}
func (operationSuMoneyCommand *OperationSuMoneyCommand) ValidateCommand() error {
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 删除兑换现金活动
type RemoveExchangeCashActivityCommand struct {
ActivityId int64 `json:"activityId" valid:"Required"`
}
func (removeExchangeCashActivityCommand *RemoveExchangeCashActivityCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeExchangeCashActivityCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 移除兑换现金人员
type RemoveExchangeCashPersonCommand struct {
ListId int64 `json:"listId" valid:"Required"` // 兑换现金人员编号
Operator int64 `json:"operator,omitempty"` // 操作人
}
func (removeExchangeCashPersonCommand *RemoveExchangeCashPersonCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeExchangeCashPersonCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type SearchExchangeCashActivityCommand struct {
ActivityNameMatch string `json:"activityNameMatch"` // 兑换现金活动名称
CompanyId int64 `json:"companyId"` // 公司id
Deadline string `json:"deadline,omitempty"` // 截止时间筛选
Offset int `json:"offset,omitempty"` // 查询偏移量
Limit int `json:"limit,omitempty"` // 查询限制条目
}
func (searchExchangeCashActivityCommand *SearchExchangeCashActivityCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(searchExchangeCashActivityCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type SearchExchangeCashPersonCommand struct {
ListName string `json:"listName"` // 兑换素币人员名称
}
func (searchExchangeCashPersonCommand *SearchExchangeCashPersonCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(searchExchangeCashPersonCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type SearchSuMoneyTransactionCommand struct {
EmployeeName string `json:"employeeName"` // 员工姓名
}
func (searchSuMoneyTransactionCommand *SearchSuMoneyTransactionCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(searchSuMoneyTransactionCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
... ... @@ -9,17 +9,20 @@ import (
type SearchSuMoneyTransactionRecordCommand struct {
// 统一用户UID
Uid int64 `json:"uid" valid:"Required"`
//Uid int64 `json:"uid" valid:"Required"`
Uid int64 `json:"uid"`
// 记录类型(1兑换,2任务奖励,3增加,4扣除)
RecordType int `json:"recordType,omitempty"`
// 记录类型列表(1兑换,2任务奖励,3增加,4扣除)
RecordTypes []int `json:"recordTypes,omitempty"`
// 操作人UID
// 事务时间区间-开始时间
TransactionStartTime time.Time `json:"transactionStartTime,omitempty"`
// 事务时间区间-截止时间
TransactionEndTime time.Time `json:"transactionEndTime,omitempty"`
// 操作人UID
Operator int64 `json:"operator,omitempty"`
// 关联人员姓名
EmployeeMatchName string `json:"employeeMatchName"`
// 查询偏离量
Offset int `json:"offset,omitempty"`
// 查询限制
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type UpdateCashPoolCommand struct {
CashPoolId int64 `json:"cashPoolId"` // 现金池编号
ExchangedCash float64 `json:"exchangedCash"` // 已兑换现金
ExchangedSuMoney float64 `json:"exchangedSuMoney"` // 已兑换素币
UnExchangeCash float64 `json:"unExchangeCash"` // 未兑换现金
UnExchangeSuMoney float64 `json:"unExchangeSuMoney"` // 未兑换素币
Rate float64 `json:"rate"` // 平均兑换汇率
Cash float64 `json:"cash"`
//CompanyId int64 `json:"companyId"`
LastRate float64 `json:"lastRate"`
//CreateTime time.Time `json:"createTime"`
}
func (updateCashPoolCommand *UpdateCashPoolCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateCashPoolCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
"time"
)
type UpdateExchangeCashActivityCommand struct {
ExchangeCashActivityId int64 `json:"exchangeCashActivityId"` // 兑换现金活动id
ExchangeActivityName string `json:"exchangeActivityName"` // 活动名称
Deadline time.Time `json:"deadline"` // 活动截止时间
CountDown int64 `json:"countDown"` // 活动倒计时
ExchangedSuMoney float64 `json:"exchangedSuMoney"` // 已兑换素币
ExchangedCash float64 `json:"exchangedCash"` // 已兑换现金
ExchangeRate float64 `json:"exchangeRate"` // 兑换汇率
}
func (updateExchangeCashActivity *UpdateExchangeCashActivityCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateExchangeCashActivity)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package command
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type UpdateExchangeCashPersonCommand struct {
ListId int64 `json:"listId" valid:"Required"` // 兑换现金人员编号
ExchangedSuMoney float64 `json:"exchangedSuMoney"` // 已兑换的素币(需要和当前的已兑换素币进行比较,少于当前已兑换素币则生成一条扣除素币记录,大于当前已兑换素币则生成一条增加素币记录)
ExchangedCash float64 `json:"exchangedCash"` // 已兑换现金
Operator int64 `json:"operator,omitempty"` // 操作人
}
func (updateExchangeCashPersonCommand *UpdateExchangeCashPersonCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateExchangeCashPersonCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
"time"
)
type ContributionsWealthRankingQuery struct {
CompanyId int64 `json:"companyId" valid:"Required"` // 公司ID
RankingType int `json:"rankingType" valid:"Required"` // 榜单类型,区分总榜和年榜 1:总榜,2:年榜
Offset int `json:"offset,omitempty"` // 查询偏离量
Limit int `json:"limit,omitempty"` // 查询限制
Uid int64 `json:"uid" valid:"Required"` // 统一用户id
StartTime time.Time `json:"startTime"` // 榜单开始时间,由后台根据榜单类型后去
EndTime time.Time `json:"endTime"` // 榜单结束更新,由后台根据榜单类型获取
}
func (contributionsWealthRankingQuery *ContributionsWealthRankingQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(contributionsWealthRankingQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ExchangeListRankingQuery struct {
ActivityId int64 `json:"activityId"`
CompanyId int64 `json:"companyId"` // 公司ID
Offset int `json:"offset,omitempty"` // 查询偏离量
Limit int `json:"limit,omitempty"` // 查询限制
Uid int64 `json:"uid"` // 统一用户id
}
func (exchangeListRankingQuery *ExchangeListRankingQuery) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(exchangeListRankingQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 获取现金池
type GetCashPoolQuery struct {
CompanyId int64 `json:"companyId" valid:"Required"` // 公司id
}
func (getCashPoolQuery *GetCashPoolQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getCashPoolQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 获取兑换现金活动
type GetExchangeCashActivityQuery struct {
ExchangeCashActivityId int64 `json:"exchangeCashActivityId"` // 兑换现金活动id
}
func (getExchangeCashActivityQuery *GetExchangeCashActivityQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getExchangeCashActivityQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type GetExchangeCashPersonQuery struct {
ExchangeCashPersonId int64 `json:"exchangeCashPersonId"` // 参与兑换现金活动人员id
}
func (getExchangeCashPersonQuery *GetExchangeCashPersonQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getExchangeCashPersonQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 获取兑换现金活动列表
type ListExchangeCashActivityQuery struct {
CompanyId int64 `json:"companyId"` // 公司id
ActivityNameMatch string `json:"activityNameMatch,omitempty"` // 活动名称匹配
//Deadline time.Time `json:"deadline,omitempty"` // 截止时间筛选
IsEnd bool `json:"isEnd"` // 已结束活动和未结束活动筛选 true: 已结束活动 false: 未结束活动
Offset int `json:"offset,omitempty"` // 查询偏移量
Limit int `json:"limit,omitempty"` // 查询限制条目
}
func (listExchangeCashActivityQuery *ListExchangeCashActivityQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listExchangeCashActivityQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ListExchangeCashActivityDeadlineQuery struct {
CompanyId int64 `json:"companyId"` // 公司id
}
func (listExchangeCashActivityDeadlineQuery *ListExchangeCashActivityDeadlineQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listExchangeCashActivityDeadlineQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
package query
import (
"fmt"
"github.com/astaxie/beego/validation"
)
// 获取兑换活动兑换清单
type ListExchangeCashPersonQuery struct {
CompanyId int64 `json:"companyId"` // 公司id
ExchangeCashActivityId int64 `json:"exchangeCashActivityId"` // 兑换现金活动id
ExchangeCashPersonNameMatch string `json:"exchangeCashPersonNameMatch,omitempty"` // 兑换活动名称匹配
Offset int `json:"offset,omitempty"` // 查询偏离量
Limit int `json:"limit,omitempty"` // 查询限制
}
func (listExchangeCashPersonQuery *ListExchangeCashPersonQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listExchangeCashPersonQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
\ No newline at end of file
... ...
... ... @@ -30,6 +30,18 @@ func (suMoneyService *SuMoneyService) OperationSuMoney(operationSuMoneyCommand *
defer func() {
transactionContext.RollbackTransaction()
}()
// 员工仓储初始化
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
employeeRepository = value
}
// 操作素币服务初始化
var operationSuMoneyService service.OperationSuMoneyService
if value, err := factory.CreateOperationSuMoneyService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -38,6 +50,20 @@ func (suMoneyService *SuMoneyService) OperationSuMoney(operationSuMoneyCommand *
} else {
operationSuMoneyService = value
}
// 判断当前员工是否有效
getEmployee := map[string]interface{}{
"uid": operationSuMoneyCommand.Uid,
"status": 1,
}
employeeFound, err := employeeRepository.FindOne(getEmployee)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if employeeFound == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的员工")
}
if task, err := operationSuMoneyService.Operation(operationSuMoneyCommand.Uid, operationSuMoneyCommand.Operator, operationSuMoneyCommand.SuMoney, operationSuMoneyCommand.OperationType, operationSuMoneyCommand.OperationDescription); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -63,6 +89,7 @@ func (suMoneyService *SuMoneyService) GetSuMoneyTransactionRecord(getSuMoneyTran
defer func() {
transactionContext.RollbackTransaction()
}()
var suMoneyTransactionRecordRepository domain.SuMoneyTransactionRecordRepository
if value, err := factory.CreateSuMoneyTransactionRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -71,6 +98,7 @@ func (suMoneyService *SuMoneyService) GetSuMoneyTransactionRecord(getSuMoneyTran
} else {
suMoneyTransactionRecordRepository = value
}
if suMoneyTransactionRecord, err := suMoneyTransactionRecordRepository.FindOne(map[string]interface{}{"suMoneyTransactionRecordId": getSuMoneyTransactionRecordQuery.SuMoneyTransactionRecordId}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -96,6 +124,7 @@ func (suMoneyService *SuMoneyService) ExchangeSuMoney(exchangeSuMoneyCommand *co
defer func() {
transactionContext.RollbackTransaction()
}()
var exchangeSuMoneyService service.ExchangeSuMoneyService
if value, err := factory.CreateExchangeSuMoneyService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -104,6 +133,7 @@ func (suMoneyService *SuMoneyService) ExchangeSuMoney(exchangeSuMoneyCommand *co
} else {
exchangeSuMoneyService = value
}
if task, err := exchangeSuMoneyService.Exchange(exchangeSuMoneyCommand.Uid, exchangeSuMoneyCommand.Operator, exchangeSuMoneyCommand.SuMoney, exchangeSuMoneyCommand.ExchangeDescription); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -129,6 +159,8 @@ func (suMoneyService *SuMoneyService) SearchSuMoneyTransactionRecord(searchSuMon
defer func() {
transactionContext.RollbackTransaction()
}()
// 素币事务记录仓储初始化
var suMoneyTransactionRecordRepository domain.SuMoneyTransactionRecordRepository
if value, err := factory.CreateSuMoneyTransactionRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -137,20 +169,57 @@ func (suMoneyService *SuMoneyService) SearchSuMoneyTransactionRecord(searchSuMon
} else {
suMoneyTransactionRecordRepository = value
}
// 获取素币兑换事务记录
if count, suMoneyTransactionRecords, err := suMoneyTransactionRecordRepository.Find(tool_funs.SimpleStructToMap(searchSuMoneyTransactionRecordCommand)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var suMoneyTransactionRecordsFormat []interface{}
for _, suMoneyTransactionRecord := range suMoneyTransactionRecords {
suMoneyTransactionRecordFormat := map[string]interface{} {
"suMoneyTransactionRecordId": suMoneyTransactionRecord.SuMoneyTransactionRecordId,
"recordType": suMoneyTransactionRecord.RecordType,
"employee": map[string]interface{} {
"uid": suMoneyTransactionRecord.Employee.Uid,
"employeeName": suMoneyTransactionRecord.Employee.EmployeeName,
"employeeAccount": suMoneyTransactionRecord.Employee.EmployeeAccount,
"employeeAvatarUrl": suMoneyTransactionRecord.Employee.EmployeeAvatarUrl,
"isPrincipal": suMoneyTransactionRecord.Employee.IsPrincipal,
},
"suMoneyBeforeTransaction": suMoneyTransactionRecord.SuMoneyBeforeTransaction,
"currentSuMoney": suMoneyTransactionRecord.CurrentSuMoney,
"suMoney": suMoneyTransactionRecord.SuMoney,
"cashBeforeTransaction": suMoneyTransactionRecord.CashBeforeTransaction,
"currentCash": suMoneyTransactionRecord.CurrentCash,
"cash": suMoneyTransactionRecord.Cash,
"operator": map[string]interface{} {
"uid": suMoneyTransactionRecord.Operator.Uid,
"employeeName": suMoneyTransactionRecord.Operator.EmployeeName,
"employeeAccount": suMoneyTransactionRecord.Operator.EmployeeAccount,
"employeeAvatarUrl": suMoneyTransactionRecord.Operator.EmployeeAvatarUrl,
"isPrincipal": suMoneyTransactionRecord.Operator.IsPrincipal,
},
"recordDescription": suMoneyTransactionRecord.RecordDescription,
"createTime": suMoneyTransactionRecord.CreateTime.Local(),
}
suMoneyTransactionRecordsFormat = append(suMoneyTransactionRecordsFormat, suMoneyTransactionRecordFormat)
}
if len(suMoneyTransactionRecordsFormat) == 0 {
suMoneyTransactionRecordsFormat = []interface{}{}
}
return map[string]interface{}{
"count": count,
"suMoneyTransactionRecords": suMoneyTransactionRecords,
"suMoneyTransactionRecords": suMoneyTransactionRecordsFormat,
}, nil
}
}
// 素币事务记录统计
// 素币事务记录统计(个人素币)
func (suMoneyService *SuMoneyService) SuMoneyTransactionRecordStatistics(suMoneyTransactionRecordStatisticsCommand *command.SuMoneyTransactionRecordStatisticsCommand) (interface{}, error) {
if err := suMoneyTransactionRecordStatisticsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
... ... @@ -165,6 +234,8 @@ func (suMoneyService *SuMoneyService) SuMoneyTransactionRecordStatistics(suMoney
defer func() {
transactionContext.RollbackTransaction()
}()
// 员工DAO初始化
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -173,6 +244,7 @@ func (suMoneyService *SuMoneyService) SuMoneyTransactionRecordStatistics(suMoney
} else {
employeeDao = value
}
if calculateResult, err := employeeDao.CalculateSuMoneyTransactionRecord(suMoneyTransactionRecordStatisticsCommand.Uid, suMoneyTransactionRecordStatisticsCommand.TransactionStartTime, suMoneyTransactionRecordStatisticsCommand.TransactionEndTime); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -183,6 +255,123 @@ func (suMoneyService *SuMoneyService) SuMoneyTransactionRecordStatistics(suMoney
}
}
// 贡献值事务记录统计(个人贡献值)
func (suMoneyService *SuMoneyService) ContributionsTransactionRecordStatistics(contributionsTransactionRecordStatisticsCommand *command.ContributionsTransactionRecordStatisticsCommand) (interface{}, error) {
if err := contributionsTransactionRecordStatisticsCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var employeeDao *dao.EmployeeDao
if value, err := factory.CreateEmployeeDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
employeeDao = value
}
if calculateResult, err := employeeDao.CalculateContributionsTransactionRecord(contributionsTransactionRecordStatisticsCommand.Uid, contributionsTransactionRecordStatisticsCommand.TransactionStartTime, contributionsTransactionRecordStatisticsCommand.TransactionEndTime); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return calculateResult, nil
}
}
// 根据uid获取员工素币(导出素币流水)
func (suMoneyService *SuMoneyService) ListSuMoneyById(exportSuMoneyCommand *command.ExportSuMoneyCommand) ([]*domain.Employee, error) {
if err := exportSuMoneyCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
if len(exportSuMoneyCommand.Ids) == 0 && exportSuMoneyCommand.Where == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "未勾选需要导出的数据")
}
// 员工仓储初始化
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
employeeRepository = value
}
if _, employees, err := employeeRepository.FindByIds(tool_funs.SimpleStructToMap(exportSuMoneyCommand)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return employees, nil
}
}
// 根据id获取事务记录(导出素币流水记录)
func (suMoneyService *SuMoneyService) ListSuMoneyTransactionRecordById(exportSuMoneyTransactionRecordCommand *command.ExportTransactionRecordCommand) ([]*domain.SuMoneyTransactionRecord, error) {
if err := exportSuMoneyTransactionRecordCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
if len(exportSuMoneyTransactionRecordCommand.Ids) == 0 && exportSuMoneyTransactionRecordCommand.Where == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "未勾选需要导出的数据")
}
var suMoneyTransactionRecordRepository domain.SuMoneyTransactionRecordRepository
if value, err := factory.CreateSuMoneyTransactionRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
suMoneyTransactionRecordRepository = value
}
if _, suMoneyTransactionRecords, err := suMoneyTransactionRecordRepository.FindById(tool_funs.SimpleStructToMap(exportSuMoneyTransactionRecordCommand)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return suMoneyTransactionRecords, nil
}
}
func NewSuMoneyService(options map[string]interface{}) *SuMoneyService {
newSuMoneyService := &SuMoneyService{}
return newSuMoneyService
... ...
... ... @@ -15,6 +15,8 @@ type AcceptanceTaskCommand struct {
Operator int64 `json:"operator" valid:"Required"`
// 任务参与者UID列表
Participators []int64 `json:"participators,omitempty"`
// 实际奖励素币值
SuMoney float64 `jsons:"suMoney"`
// 任务贡献占比
TaskPercentage []*domain.TaskPercentageItem `json:"taskPercentage"`
// 引用资源解决分
... ...
... ... @@ -29,6 +29,10 @@ type CreateTaskCommand struct {
TaskNature int `json:"taskNature,omitempty"`
// 奖励素币
SuMoney float64 `json:"suMoney,omitempty"`
// 最小奖励素币
MinSuMoney float64 `json:"minSuMoney"`
// 最大奖励素币
MaxSuMoney float64 `json:"maxSuMoney"`
// 验收标准
AcceptanceStandard string `json:"acceptanceStandard,omitempty"`
// 任务描述
... ...
... ... @@ -13,12 +13,18 @@ type SearchTaskCommand struct {
Sponsor int64 `json:"sponsor,omitempty"`
// 任务内容匹配
TaskContentMatch string `json:"taskContentMatch,omitempty"`
// 任务名称匹配
TaskNameMatch string `json:"taskNameMatch,omitempty"`
// 任务类型
TaskType int `json:"taskType,omitempty"`
// 任务类型ID列表
TaskTypes []int `json:"taskTypes,omitempty"`
// 任务状态
TaskStatus int `json:"taskStatus,omitempty"`
// 任务状态ID列表
TaskStates []int `json:"taskStates,omitempty"`
// 任务状态ID列表
TaskStatuss []int `json:"taskStatuss,omitempty"`
// 项目归属
ProjectBelongs []int `json:"projectBelongs,omitempty"`
// 客户价值
... ...
... ... @@ -23,8 +23,12 @@ type UpdateTaskCommand struct {
CustomerValues []int `json:"customerValues,omitempty"`
// 任务性质
TaskNature int `json:"taskNature,omitempty"`
// 奖励素币
// 实际奖励素币
SuMoney float64 `json:"suMoney,omitempty"`
// 最小奖励素币
MinSuMoney float64 `json:"minSuMoney,omitempty"`
// 最大奖励素币
MaxSuMoney float64 `json:"maxSuMoney,omitempty"`
// 验收标准
AcceptanceStandard string `json:"acceptanceStandard,omitempty"`
// 任务描述
... ...
... ... @@ -29,6 +29,10 @@ type TaskDto struct {
TaskNature *domain.TaskNature `json:"taskNature"`
// 奖励素币
SuMoney float64 `json:"suMoney"`
// 最小奖励素币
MinSuMoney float64 `json:"minSuMoney"`
// 最大奖励素币
MaxSuMoney float64 `json:"maxSuMoney"`
// 验收标准
AcceptanceStandard string `json:"acceptanceStandard"`
// 任务描述
... ... @@ -99,6 +103,8 @@ func (dto *TaskDto) LoadDto(task *domain.Task, projectBelongMap map[int]*domain.
}
}
dto.SuMoney = task.SuMoney
dto.MinSuMoney = task.MinSuMoney
dto.MaxSuMoney = task.MaxSuMoney
dto.AcceptanceStandard = task.AcceptanceStandard
dto.TaskDescription = task.TaskDescription
dto.TaskPictureUrls = task.TaskPictureUrls
... ...
... ... @@ -2,6 +2,8 @@ package service
import (
"fmt"
"time"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
... ... @@ -13,7 +15,6 @@ import (
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain/service"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/dao"
"time"
)
// 任务服务
... ... @@ -25,6 +26,7 @@ func (taskService *TaskService) ConfirmRobTask(confirmRobTaskCommand *command.Co
if err := confirmRobTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -35,6 +37,7 @@ func (taskService *TaskService) ConfirmRobTask(confirmRobTaskCommand *command.Co
defer func() {
transactionContext.RollbackTransaction()
}()
var confirmRobTaskService service.ConfirmRobTaskService
if value, err := factory.CreateConfirmRobTaskService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -46,6 +49,7 @@ func (taskService *TaskService) ConfirmRobTask(confirmRobTaskCommand *command.Co
TransactionContext: transactionContext.(*pgTransaction.TransactionContext),
})
}
if task, err := confirmRobTaskService.Confirm(confirmRobTaskCommand.TaskId, confirmRobTaskCommand.Operator, confirmRobTaskCommand.PlannedCompletionTime); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -61,6 +65,7 @@ func (taskService *TaskService) RejectTaskReceiver(rejectTaskReceiverCommand *co
if err := rejectTaskReceiverCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -71,6 +76,7 @@ func (taskService *TaskService) RejectTaskReceiver(rejectTaskReceiverCommand *co
defer func() {
transactionContext.RollbackTransaction()
}()
var rejectTaskReceiverService service.RejectTaskReceiverService
if value, err := factory.CreateRejectTaskReceiverService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -82,6 +88,7 @@ func (taskService *TaskService) RejectTaskReceiver(rejectTaskReceiverCommand *co
TransactionContext: transactionContext.(*pgTransaction.TransactionContext),
})
}
if task, err := rejectTaskReceiverService.Reject(rejectTaskReceiverCommand.TaskId, rejectTaskReceiverCommand.Operator, rejectTaskReceiverCommand.RejectReason); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -97,6 +104,7 @@ func (taskService *TaskService) RobTask(robTaskCommand *command.RobTaskCommand)
if err := robTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -107,6 +115,7 @@ func (taskService *TaskService) RobTask(robTaskCommand *command.RobTaskCommand)
defer func() {
transactionContext.RollbackTransaction()
}()
var robTaskService service.RobTaskService
if value, err := factory.CreateRobTaskService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -119,6 +128,7 @@ func (taskService *TaskService) RobTask(robTaskCommand *command.RobTaskCommand)
TransactionContext: transactionContext.(*pgTransaction.TransactionContext),
})
}
if task, err := robTaskService.Rob(robTaskCommand.TaskId, robTaskCommand.Receiver); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -134,6 +144,7 @@ func (taskService *TaskService) BidTask(bidTaskCommand *command.BidTaskCommand)
if err := bidTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -144,6 +155,7 @@ func (taskService *TaskService) BidTask(bidTaskCommand *command.BidTaskCommand)
defer func() {
transactionContext.RollbackTransaction()
}()
var bidTaskService service.BidTaskService
if value, err := factory.CreateBidTaskService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -152,6 +164,7 @@ func (taskService *TaskService) BidTask(bidTaskCommand *command.BidTaskCommand)
} else {
bidTaskService = value
}
if task, err := bidTaskService.Bid(bidTaskCommand.TaskId, bidTaskCommand.Bidder); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -167,6 +180,7 @@ func (taskService *TaskService) ChooseSuccessfulBidder(chooseSuccessfulBidderCom
if err := chooseSuccessfulBidderCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -177,6 +191,7 @@ func (taskService *TaskService) ChooseSuccessfulBidder(chooseSuccessfulBidderCom
defer func() {
transactionContext.RollbackTransaction()
}()
var chooseSuccessfulBidderService service.ChooseSuccessfulBidderService
if value, err := factory.CreateChooseSuccessfulBidderService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -186,6 +201,7 @@ func (taskService *TaskService) ChooseSuccessfulBidder(chooseSuccessfulBidderCom
chooseSuccessfulBidderService = value
chooseSuccessfulBidderService.Subscribe(&subscriber.AbilityServiceSubscriber{})
}
if task, err := chooseSuccessfulBidderService.Choose(chooseSuccessfulBidderCommand.TaskId, chooseSuccessfulBidderCommand.SuccessfulBidder, chooseSuccessfulBidderCommand.Operator, chooseSuccessfulBidderCommand.PlannedCompletionTime); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -201,6 +217,7 @@ func (taskService *TaskService) ApplyCompleteTask(applyCompleteTaskCommand *comm
if err := applyCompleteTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -211,6 +228,7 @@ func (taskService *TaskService) ApplyCompleteTask(applyCompleteTaskCommand *comm
defer func() {
transactionContext.RollbackTransaction()
}()
var applyCompleteTaskService service.ApplyCompleteTaskService
if value, err := factory.CreateApplyCompleteTaskService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -219,6 +237,7 @@ func (taskService *TaskService) ApplyCompleteTask(applyCompleteTaskCommand *comm
} else {
applyCompleteTaskService = value
}
if task, err := applyCompleteTaskService.ApplyComplete(applyCompleteTaskCommand.TaskId, applyCompleteTaskCommand.Receiver); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -234,6 +253,7 @@ func (taskService *TaskService) ReleaseTask(releaseTaskCommand *command.ReleaseT
if err := releaseTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -244,6 +264,8 @@ func (taskService *TaskService) ReleaseTask(releaseTaskCommand *command.ReleaseT
defer func() {
transactionContext.RollbackTransaction()
}()
// 发布任务服务初始化
var releaseTaskService service.ReleaseTaskService
if value, err := factory.CreateReleaseTaskService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -256,6 +278,8 @@ func (taskService *TaskService) ReleaseTask(releaseTaskCommand *command.ReleaseT
TransactionContext: transactionContext.(*pgTransaction.TransactionContext),
})
}
// 关闭任务
if task, err := releaseTaskService.Release(releaseTaskCommand.TaskId, releaseTaskCommand.Operator); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -271,6 +295,7 @@ func (taskService *TaskService) OffTask(offTaskCommand *command.OffTaskCommand)
if err := offTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -281,6 +306,8 @@ func (taskService *TaskService) OffTask(offTaskCommand *command.OffTaskCommand)
defer func() {
transactionContext.RollbackTransaction()
}()
// 关闭任务服务初始化
var offTaskService service.OffTaskService
if value, err := factory.CreateOffTaskService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -290,6 +317,8 @@ func (taskService *TaskService) OffTask(offTaskCommand *command.OffTaskCommand)
offTaskService = value
offTaskService.Subscribe(&subscriber.AbilityServiceSubscriber{})
}
// 关闭任务
if task, err := offTaskService.Off(offTaskCommand.TaskId, offTaskCommand.Operator, offTaskCommand.OffReason); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -305,6 +334,7 @@ func (taskService *TaskService) AcceptanceTask(acceptanceTaskCommand *command.Ac
if err := acceptanceTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -315,6 +345,8 @@ func (taskService *TaskService) AcceptanceTask(acceptanceTaskCommand *command.Ac
defer func() {
transactionContext.RollbackTransaction()
}()
// 验收服务初始化
var acceptanceTaskService service.AcceptanceTaskService
if value, err := factory.CreateAcceptanceTaskService(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -324,7 +356,50 @@ func (taskService *TaskService) AcceptanceTask(acceptanceTaskCommand *command.Ac
acceptanceTaskService = value
acceptanceTaskService.Subscribe(&subscriber.AbilityServiceSubscriber{})
}
if task, err := acceptanceTaskService.Acceptance(acceptanceTaskCommand.TaskId, acceptanceTaskCommand.Operator, acceptanceTaskCommand.Participators, acceptanceTaskCommand.TaskPercentage, acceptanceTaskCommand.ReferenceResourceScore, acceptanceTaskCommand.SolveReport, acceptanceTaskCommand.SolvePictureUrls, acceptanceTaskCommand.ActualCompletionTime); err != nil {
// 员工仓储初始化
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
employeeRepository = value
}
// 填充百分比员工信息
for i, taskPercentage := range acceptanceTaskCommand.TaskPercentage {
getEmployee := map[string]interface{}{
"uid": taskPercentage.Contributor.Uid,
}
employeeFound, err := employeeRepository.FindOne(getEmployee)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if employeeFound == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的员工")
}
acceptanceTaskCommand.TaskPercentage[i].Contributor = employeeFound.EmployeeInfo
}
// 填充评分员工信息
for i, referenceResourceScore := range acceptanceTaskCommand.ReferenceResourceScore {
for j, solveScore := range referenceResourceScore.SolveScore {
getEmployee := map[string]interface{}{
"uid": solveScore.Contributor.Uid,
}
employeeFound, err := employeeRepository.FindOne(getEmployee)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if employeeFound == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的员工")
}
acceptanceTaskCommand.ReferenceResourceScore[i].SolveScore[j].Contributor = employeeFound.EmployeeInfo
}
}
if task, err := acceptanceTaskService.Acceptance(acceptanceTaskCommand.TaskId, acceptanceTaskCommand.Operator, acceptanceTaskCommand.Participators, acceptanceTaskCommand.SuMoney, acceptanceTaskCommand.TaskPercentage, acceptanceTaskCommand.ReferenceResourceScore, acceptanceTaskCommand.SolveReport, acceptanceTaskCommand.SolvePictureUrls, acceptanceTaskCommand.ActualCompletionTime); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
... ... @@ -336,10 +411,11 @@ func (taskService *TaskService) AcceptanceTask(acceptanceTaskCommand *command.Ac
// 搜索任务
func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTaskCommand) (interface{}, error) {
if err := searchTaskCommand.ValidateCommand(); err != nil {
if err := searchTaskCommand.ValidateCommand(); err != nil { // 校验搜索命令
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
transactionContext, err := factory.CreateTransactionContext(nil) // 工厂类创建事务上下文
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
... ... @@ -349,6 +425,7 @@ func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTask
defer func() {
transactionContext.RollbackTransaction()
}()
var taskRepository domain.TaskRepository
if value, err := factory.CreateTaskRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -357,6 +434,7 @@ func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTask
} else {
taskRepository = value
}
var projectBelongRepository domain.ProjectBelongRepository
if value, err := factory.CreateProjectBelongRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -365,6 +443,7 @@ func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTask
} else {
projectBelongRepository = value
}
projectBelongMap := make(map[int]*domain.ProjectBelong)
if _, projectBelongs, err := projectBelongRepository.Find(map[string]interface{}{
"companyId": searchTaskCommand.CompanyId,
... ... @@ -375,6 +454,7 @@ func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTask
projectBelongMap[projectBelong.ProjectBelongId] = projectBelong
}
}
var customerValueRepository domain.CustomerValueRepository
if value, err := factory.CreateCustomerValueRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -383,6 +463,7 @@ func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTask
} else {
customerValueRepository = value
}
customerValueMap := make(map[int]*domain.CustomerValue)
if _, customerValues, err := customerValueRepository.Find(map[string]interface{}{
"companyId": searchTaskCommand.CompanyId,
... ... @@ -393,6 +474,7 @@ func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTask
customerValueMap[customerValue.CustomerValueId] = customerValue
}
}
var taskNatureRepository domain.TaskNatureRepository
if value, err := factory.CreateTaskNatureRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -401,6 +483,7 @@ func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTask
} else {
taskNatureRepository = value
}
taskNatureMap := make(map[int]*domain.TaskNature)
if _, taskNatures, err := taskNatureRepository.Find(map[string]interface{}{
"companyId": searchTaskCommand.CompanyId,
... ... @@ -411,6 +494,7 @@ func (taskService *TaskService) SearchTask(searchTaskCommand *command.SearchTask
taskNatureMap[taskNature.TaskNatureId] = taskNature
}
}
if count, tasks, err := taskRepository.Find(tool_funs.SimpleStructToMap(searchTaskCommand)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -437,6 +521,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
if err := searchOffTaskRecordCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -447,6 +532,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
defer func() {
transactionContext.RollbackTransaction()
}()
var projectBelongRepository domain.ProjectBelongRepository
if value, err := factory.CreateProjectBelongRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -455,6 +541,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
} else {
projectBelongRepository = value
}
projectBelongMap := make(map[int]*domain.ProjectBelong)
if _, projectBelongs, err := projectBelongRepository.Find(map[string]interface{}{
"companyId": searchOffTaskRecordCommand.CompanyId,
... ... @@ -465,6 +552,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
projectBelongMap[projectBelong.ProjectBelongId] = projectBelong
}
}
var customerValueRepository domain.CustomerValueRepository
if value, err := factory.CreateCustomerValueRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -473,6 +561,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
} else {
customerValueRepository = value
}
customerValueMap := make(map[int]*domain.CustomerValue)
if _, customerValues, err := customerValueRepository.Find(map[string]interface{}{
"companyId": searchOffTaskRecordCommand.CompanyId,
... ... @@ -483,6 +572,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
customerValueMap[customerValue.CustomerValueId] = customerValue
}
}
var taskNatureRepository domain.TaskNatureRepository
if value, err := factory.CreateTaskNatureRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -491,6 +581,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
} else {
taskNatureRepository = value
}
taskNatureMap := make(map[int]*domain.TaskNature)
if _, taskNatures, err := taskNatureRepository.Find(map[string]interface{}{
"companyId": searchOffTaskRecordCommand.CompanyId,
... ... @@ -501,6 +592,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
taskNatureMap[taskNature.TaskNatureId] = taskNature
}
}
var taskRepository domain.TaskRepository
if value, err := factory.CreateTaskRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -509,6 +601,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
} else {
taskRepository = value
}
var offTaskRecordRepository domain.OffTaskRecordRepository
if value, err := factory.CreateOffTaskRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -517,6 +610,7 @@ func (taskService *TaskService) SearchOffTaskRecord(searchOffTaskRecordCommand *
} else {
offTaskRecordRepository = value
}
_, tasks, err := taskRepository.Find(map[string]interface{}{
"companyId": searchOffTaskRecordCommand.CompanyId,
"taskStatus": domain.TASK_STATUS_CLOSED,
... ... @@ -570,6 +664,7 @@ func (taskService *TaskService) GetOffTaskRecord(getOffTaskRecordQuery *query.Ge
if err := getOffTaskRecordQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -580,6 +675,7 @@ func (taskService *TaskService) GetOffTaskRecord(getOffTaskRecordQuery *query.Ge
defer func() {
transactionContext.RollbackTransaction()
}()
var offTaskRecordRepository domain.OffTaskRecordRepository
if value, err := factory.CreateOffTaskRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -588,6 +684,7 @@ func (taskService *TaskService) GetOffTaskRecord(getOffTaskRecordQuery *query.Ge
} else {
offTaskRecordRepository = value
}
offTaskRecord, err := offTaskRecordRepository.FindOne(map[string]interface{}{"offTaskRecordId": getOffTaskRecordQuery.OffTaskRecordId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ... @@ -607,6 +704,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
if err := searchRejectTaskRecordCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -617,6 +715,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
defer func() {
transactionContext.RollbackTransaction()
}()
var projectBelongRepository domain.ProjectBelongRepository
if value, err := factory.CreateProjectBelongRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -625,6 +724,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
} else {
projectBelongRepository = value
}
projectBelongMap := make(map[int]*domain.ProjectBelong)
if _, projectBelongs, err := projectBelongRepository.Find(map[string]interface{}{
"companyId": searchRejectTaskRecordCommand.CompanyId,
... ... @@ -635,6 +735,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
projectBelongMap[projectBelong.ProjectBelongId] = projectBelong
}
}
var customerValueRepository domain.CustomerValueRepository
if value, err := factory.CreateCustomerValueRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -643,6 +744,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
} else {
customerValueRepository = value
}
customerValueMap := make(map[int]*domain.CustomerValue)
if _, customerValues, err := customerValueRepository.Find(map[string]interface{}{
"companyId": searchRejectTaskRecordCommand.CompanyId,
... ... @@ -653,6 +755,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
customerValueMap[customerValue.CustomerValueId] = customerValue
}
}
var taskNatureRepository domain.TaskNatureRepository
if value, err := factory.CreateTaskNatureRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -661,6 +764,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
} else {
taskNatureRepository = value
}
taskNatureMap := make(map[int]*domain.TaskNature)
if _, taskNatures, err := taskNatureRepository.Find(map[string]interface{}{
"companyId": searchRejectTaskRecordCommand.CompanyId,
... ... @@ -671,6 +775,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
taskNatureMap[taskNature.TaskNatureId] = taskNature
}
}
var taskRepository domain.TaskRepository
if value, err := factory.CreateTaskRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -679,6 +784,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
} else {
taskRepository = value
}
var rejectTaskRecordRepository domain.RejectTaskRecordRepository
if value, err := factory.CreateRejectTaskRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -687,6 +793,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
} else {
rejectTaskRecordRepository = value
}
_, tasks, err := taskRepository.Find(map[string]interface{}{
"companyId": searchRejectTaskRecordCommand.CompanyId,
"taskContentMatch": searchRejectTaskRecordCommand.TaskContentMatch,
... ... @@ -702,6 +809,7 @@ func (taskService *TaskService) SearchRejectTaskRecord(searchRejectTaskRecordCom
for _, task := range tasks {
taskIds = append(taskIds, task.TaskId)
}
if count, rejectTaskRecords, err := rejectTaskRecordRepository.Find(map[string]interface{}{
"taskIds": taskIds,
"rejectStartTime": searchRejectTaskRecordCommand.RejectStartTime,
... ... @@ -739,6 +847,7 @@ func (taskService *TaskService) GetRejectTaskRecord(getRejectTaskRecordQuery *qu
if err := getRejectTaskRecordQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -749,6 +858,7 @@ func (taskService *TaskService) GetRejectTaskRecord(getRejectTaskRecordQuery *qu
defer func() {
transactionContext.RollbackTransaction()
}()
var rejectTaskRecordRepository domain.RejectTaskRecordRepository
if value, err := factory.CreateRejectTaskRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -757,6 +867,7 @@ func (taskService *TaskService) GetRejectTaskRecord(getRejectTaskRecordQuery *qu
} else {
rejectTaskRecordRepository = value
}
rejectTaskRecord, err := rejectTaskRecordRepository.FindOne(map[string]interface{}{"rejectTaskRecordId": getRejectTaskRecordQuery.RejectTaskRecordId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ... @@ -776,6 +887,7 @@ func (taskService *TaskService) CreateTask(createTaskCommand *command.CreateTask
if err := createTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -786,6 +898,7 @@ func (taskService *TaskService) CreateTask(createTaskCommand *command.CreateTask
defer func() {
transactionContext.RollbackTransaction()
}()
var taskDao *dao.TaskDao
if value, err := factory.CreateTaskDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -794,6 +907,7 @@ func (taskService *TaskService) CreateTask(createTaskCommand *command.CreateTask
} else {
taskDao = value
}
var employeeRepository domain.EmployeeRepository
if value, err := factory.CreateEmployeeRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -802,28 +916,54 @@ func (taskService *TaskService) CreateTask(createTaskCommand *command.CreateTask
} else {
employeeRepository = value
}
sponsor, err := employeeRepository.FindOne(map[string]interface{}{
"uid": createTaskCommand.Sponsor,
"status": 1,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if sponsor == nil {
// 获取无效的发布人员信息
sponsorInvalid, err := employeeRepository.FindOne(map[string]interface{}{
"uid": createTaskCommand.AssignedPerson,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if sponsorInvalid == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的发布者")
}
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的发布者:"+ sponsorInvalid.EmployeeInfo.EmployeeName)
}
// 获取任务指派人
var assignedPerson *domain.EmployeeInfo
if createTaskCommand.AssignedPerson != 0 {
employee, err := employeeRepository.FindOne(map[string]interface{}{
"uid": createTaskCommand.AssignedPerson,
"status": 1,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if employee == nil {
// 获取无效的指派人员信息
employeeInvalid, err := employeeRepository.FindOne(map[string]interface{}{
"uid": createTaskCommand.AssignedPerson,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if employeeInvalid == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的指派人员")
}
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的指派人员:" + employeeInvalid.EmployeeInfo.EmployeeName)
}
assignedPerson = employee.EmployeeInfo
}
newTask := &domain.Task{
TaskStatus: domain.TASK_STATUS_UNRELEASED,
CompanyId: createTaskCommand.CompanyId,
... ... @@ -838,6 +978,8 @@ func (taskService *TaskService) CreateTask(createTaskCommand *command.CreateTask
CustomerValues: createTaskCommand.CustomerValues,
TaskNature: createTaskCommand.TaskNature,
SuMoney: createTaskCommand.SuMoney,
MinSuMoney: createTaskCommand.MinSuMoney,
MaxSuMoney: createTaskCommand.MaxSuMoney,
AcceptanceStandard: createTaskCommand.AcceptanceStandard,
TaskDescription: createTaskCommand.TaskDescription,
TaskPictureUrls: createTaskCommand.TaskPictureUrls,
... ... @@ -846,6 +988,7 @@ func (taskService *TaskService) CreateTask(createTaskCommand *command.CreateTask
PlannedCompletionTime: createTaskCommand.PlannedCompletionTime,
CreateTime: time.Now(),
}
var taskRepository domain.TaskRepository
if value, err := factory.CreateTaskRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -854,6 +997,7 @@ func (taskService *TaskService) CreateTask(createTaskCommand *command.CreateTask
} else {
taskRepository = value
}
if createTaskCommand.ReferenceResourceItems != nil && len(createTaskCommand.ReferenceResourceItems) > 0 {
var referenceResourceIds []int64
for _, referenceResourceItem := range createTaskCommand.ReferenceResourceItems {
... ... @@ -871,6 +1015,7 @@ func (taskService *TaskService) CreateTask(createTaskCommand *command.CreateTask
}
}
}
if task, err := taskRepository.Save(newTask); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -908,6 +1053,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
if err := getTaskQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -918,6 +1064,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
defer func() {
transactionContext.RollbackTransaction()
}()
var taskRepository domain.TaskRepository
if value, err := factory.CreateTaskRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -926,6 +1073,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
} else {
taskRepository = value
}
task, err := taskRepository.FindOne(map[string]interface{}{"taskId": getTaskQuery.TaskId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ... @@ -941,6 +1089,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
} else {
projectBelongRepository = value
}
projectBelongMap := make(map[int]*domain.ProjectBelong)
if _, projectBelongs, err := projectBelongRepository.Find(map[string]interface{}{
"companyId": task.CompanyId,
... ... @@ -951,6 +1100,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
projectBelongMap[projectBelong.ProjectBelongId] = projectBelong
}
}
var customerValueRepository domain.CustomerValueRepository
if value, err := factory.CreateCustomerValueRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -959,6 +1109,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
} else {
customerValueRepository = value
}
customerValueMap := make(map[int]*domain.CustomerValue)
if _, customerValues, err := customerValueRepository.Find(map[string]interface{}{
"companyId": task.CompanyId,
... ... @@ -969,6 +1120,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
customerValueMap[customerValue.CustomerValueId] = customerValue
}
}
var taskNatureRepository domain.TaskNatureRepository
if value, err := factory.CreateTaskNatureRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -977,6 +1129,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
} else {
taskNatureRepository = value
}
taskNatureMap := make(map[int]*domain.TaskNature)
if _, taskNatures, err := taskNatureRepository.Find(map[string]interface{}{
"companyId": task.CompanyId,
... ... @@ -987,6 +1140,7 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
taskNatureMap[taskNature.TaskNatureId] = taskNature
}
}
taskDto := &dto.TaskDto{}
if err := taskDto.LoadDto(task, projectBelongMap, customerValueMap, taskNatureMap); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ... @@ -994,15 +1148,55 @@ func (taskService *TaskService) GetTask(getTaskQuery *query.GetTaskQuery) (inter
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
// 返回任务素币奖励范围
if taskDto.TaskStatus != 5 && task.MinSuMoney == 0 && task.MaxSuMoney == 0 {
taskDto.MinSuMoney = 0
taskDto.MaxSuMoney = task.SuMoney
}
return taskDto, nil
}
}
// 更新过期任务状态
func (taskService *TaskService) UpdateTaskStatus() (interface{}, error) {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var taskDao *dao.TaskDao
if value, err := factory.CreateTaskDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
taskDao = value
}
if err := taskDao.UpdateExpiredPlannedCompletionTimeBidTask(); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 更新任务
func (taskService *TaskService) UpdateTask(updateTaskCommand *command.UpdateTaskCommand) (interface{}, error) {
if err := updateTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -1013,6 +1207,7 @@ func (taskService *TaskService) UpdateTask(updateTaskCommand *command.UpdateTask
defer func() {
transactionContext.RollbackTransaction()
}()
var taskRepository domain.TaskRepository
if value, err := factory.CreateTaskRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -1021,6 +1216,7 @@ func (taskService *TaskService) UpdateTask(updateTaskCommand *command.UpdateTask
} else {
taskRepository = value
}
var taskDao *dao.TaskDao
if value, err := factory.CreateTaskDao(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -1029,13 +1225,34 @@ func (taskService *TaskService) UpdateTask(updateTaskCommand *command.UpdateTask
} else {
taskDao = value
}
var releaseTaskService service.ReleaseTaskService
if value, err := factory.CreateReleaseTaskService(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
releaseTaskService = value
releaseTaskService.Subscribe(&subscriber.AbilityServiceSubscriber{})
releaseTaskService.Subscribe(&subscriber.MmmOpenApiServiceServiceSubscriber{
TransactionContext: transactionContext.(*pgTransaction.TransactionContext),
})
}
var taskBidEndTime time.Time
// 找到当前任务
task, err := taskRepository.FindOne(map[string]interface{}{"taskId": updateTaskCommand.TaskId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if task == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updateTaskCommand.TaskId)))
} else {
if task.TaskStatus == domain.TASK_STATUS_EXPIRED {
taskBidEndTime = task.BidInfo.BidEndTime
}
}
if updateTaskCommand.ReferenceResourceItems != nil && len(updateTaskCommand.ReferenceResourceItems) > 0 {
var referenceResourceIds []int64
for _, referenceResourceItem := range updateTaskCommand.ReferenceResourceItems {
... ... @@ -1058,8 +1275,11 @@ func (taskService *TaskService) UpdateTask(updateTaskCommand *command.UpdateTask
}
}
}
updateData := tool_funs.SimpleStructToMap(updateTaskCommand)
fmt.Println(updateTaskCommand.AssignedPerson != int64(0))
if task.TaskType == domain.TASK_TYPE_DESIGNATE {
if updateTaskCommand.AssignedPerson != int64(0) {
var employeeRepository domain.EmployeeRepository
... ... @@ -1072,18 +1292,30 @@ func (taskService *TaskService) UpdateTask(updateTaskCommand *command.UpdateTask
}
employee, err := employeeRepository.FindOne(map[string]interface{}{
"uid": updateTaskCommand.AssignedPerson,
"status": 1,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if employee == nil {
// 获取无效的发布人员信息
employeeInvalid, err := employeeRepository.FindOne(map[string]interface{}{
"uid": updateTaskCommand.AssignedPerson,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if employeeInvalid == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的指派人员")
}
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的指派人员:" + employeeInvalid.EmployeeInfo.EmployeeName)
}
updateData["assignedPerson"] = employee.EmployeeInfo
} else {
updateData["assignedPerson"] = &domain.EmployeeInfo{}
}
}
if err := task.Update(updateData); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
... ... @@ -1095,6 +1327,18 @@ func (taskService *TaskService) UpdateTask(updateTaskCommand *command.UpdateTask
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
if task.TaskStatus == domain.TASK_STATUS_EXPIRED {
// 未修改时间或者修改的时间小于当前时间
if updateTaskCommand.BidEndTime.Local().Equal(taskBidEndTime.Local()) || updateTaskCommand.BidEndTime.Local().Before(time.Date(time.Now().Local().Year(), time.Now().Local().Month(), time.Now().Local().Day(), 23, 59, 59, 0, time.Local)) {
return nil, application.ThrowError(application.BUSINESS_ERROR, "请重新修改竞标时间")
} else {
if _, err := releaseTaskService.Release(task.TaskId, task.Sponsor.Uid); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
... ... @@ -1124,6 +1368,7 @@ func (taskService *TaskService) RemoveTask(removeTaskCommand *command.RemoveTask
if err := removeTaskCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -1134,6 +1379,7 @@ func (taskService *TaskService) RemoveTask(removeTaskCommand *command.RemoveTask
defer func() {
transactionContext.RollbackTransaction()
}()
var taskRepository domain.TaskRepository
if value, err := factory.CreateTaskRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -1142,6 +1388,7 @@ func (taskService *TaskService) RemoveTask(removeTaskCommand *command.RemoveTask
} else {
taskRepository = value
}
task, err := taskRepository.FindOne(map[string]interface{}{"taskId": removeTaskCommand.TaskId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ... @@ -1181,6 +1428,7 @@ func (taskService *TaskService) ListTask(listTaskQuery *query.ListTaskQuery) (in
if err := listTaskQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -1191,6 +1439,7 @@ func (taskService *TaskService) ListTask(listTaskQuery *query.ListTaskQuery) (in
defer func() {
transactionContext.RollbackTransaction()
}()
var taskRepository domain.TaskRepository
if value, err := factory.CreateTaskRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -1199,15 +1448,24 @@ func (taskService *TaskService) ListTask(listTaskQuery *query.ListTaskQuery) (in
} else {
taskRepository = value
}
if count, tasks, err := taskRepository.Find(tool_funs.SimpleStructToMap(listTaskQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var retTasks []*domain.Task
for _, task := range tasks {
if task.TaskStatus != 5 && task.MinSuMoney == 0 && task.MaxSuMoney == 0 {
task.MinSuMoney = 0
task.MaxSuMoney = task.SuMoney
}
retTasks = append(retTasks, task)
}
return map[string]interface{}{
"count": count,
"tasks": tasks,
"tasks": retTasks,
}, nil
}
}
... ...
... ... @@ -7,6 +7,7 @@ import (
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/unifiedUserCenter/command"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/dao"
"time"
)
// 统一用户中心适配服务
... ... @@ -88,12 +89,12 @@ func (unifiedUserCenterService *UnifiedUserCenterService) SyncEmployeeCallback(s
uids = append(uids, int64(uid.(float64)))
}
}
if value, ok := data["add"]; ok {
if value, ok := data["add"]; ok { // 添加员工
for _, addEmployee := range value.([]interface{}) {
addEmployees = append(addEmployees, addEmployee.(map[string]interface{}))
}
}
if value, ok := data["edit"]; ok {
if value, ok := data["edit"]; ok { // 编辑员工
for _, editEmployee := range value.([]interface{}) {
editEmployees = append(editEmployees, editEmployee.(map[string]interface{}))
}
... ... @@ -145,7 +146,9 @@ func (unifiedUserCenterService *UnifiedUserCenterService) SyncEmployeeCallback(s
},
Status: status,
SuMoney: 0,
CreateTime: time.Now(),
}
if _, err := employeeRepository.Save(employee); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
... ... @@ -205,6 +208,7 @@ func (unifiedUserCenterService *UnifiedUserCenterService) SyncEmployeeCallback(s
},
Status: status,
SuMoney: 0,
CreateTime: time.Now(),
}
if _, err := employeeRepository.Save(employee); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ...
... ... @@ -8,6 +8,9 @@ var LOG_LEVEL = "debug"
var ABILITY_SERVICE_HOST = "https://suplus-worth-app-gateway-dev.fjmaimaimai.com"
var MMM_OPEN_API_SERVICE_HOST = "http://mmm-open-api-dev.fjmaimaimai.com"
//var LOG_LEVEL = "debug"
var LOG_File = "logs/app.log"
func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
... ...
... ... @@ -2,11 +2,11 @@ package constant
import "os"
var POSTGRESQL_DB_NAME = "mmm-worth"
var POSTGRESQL_DB_NAME = "mmm-worth-test"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "abc123456"
var POSTGRESQL_PASSWORD = "1993618jack"
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "32432"
var POSTGRESQL_PORT = "5432"
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
... ...
package domain
import (
"time"
)
// 现金池
type CashPool struct {
CashPoolId int64 `json:"cashPoolId"` // 现金池id
Cash float64 `json:"cash"` // 投入现金池的现金
CompanyId int64 `json:"companyId"` // 公司id
ExchangedCash float64 `json:"exchangedCash"` // 已兑换的现金
UnExchangeCash float64 `json:"unExchangeCash"` // 未兑换的现金
ExchangedSuMoney float64 `json:"exchangedSuMoney"` // 已兑换的素币
UnExchangeSuMoney float64 `json:"unExchangeSuMoney"` // 未兑换的素币
Rate float64 `json:"rate"` // 平均兑换汇率
LastRate float64 `json:"lastRate"` // 上期活动兑换汇率
CreateTime time.Time `json:"createTime"` // 现金投入现金池时间
}
type CashPoolRepository interface {
Save(cashPool *CashPool) (*CashPool, error)
FindOne(queryOptions map[string]interface{}) (*CashPool, error)
Find(queryOptions map[string]interface{}) (int64, []*CashPool, error)
}
func (cashPool *CashPool) Update(data map[string]interface{}) error {
if cash, ok := data["cash"]; ok {
cashPool.Cash = cash.(float64)
}
if exchangedCash, ok := data["exchangedCash"]; ok {
cashPool.ExchangedCash = exchangedCash.(float64)
}
if unExchangeCash, ok := data["unExchangeCash"]; ok {
cashPool.UnExchangeCash = unExchangeCash.(float64)
}
if exchangedSuMoney, ok := data["exchangedSuMoney"]; ok {
cashPool.ExchangedSuMoney = exchangedSuMoney.(float64)
}
if unExchangeSuMoney, ok := data["unExchangeSuMoney"]; ok {
cashPool.UnExchangeSuMoney = unExchangeSuMoney.(float64)
}
if rate, ok := data["rate"]; ok {
cashPool.Rate = rate.(float64)
}
return nil
}
func (cashPool *CashPool) Identity() interface{} {
if cashPool.CashPoolId == 0 {
return nil
}
return cashPool.CashPoolId
}
... ...
package domain
import "time"
// 员工
type Employee struct {
// 员工ID
... ... @@ -14,6 +16,8 @@ type Employee struct {
Status int `json:"status"`
// 员工权限集合
Permissions []int `json:"permissions"`
// 创建时间
CreateTime time.Time `json:"createTime"`
}
type EmployeeRepository interface {
... ... @@ -21,6 +25,8 @@ type EmployeeRepository interface {
Remove(employee *Employee) (*Employee, error)
FindOne(queryOptions map[string]interface{}) (*Employee, error)
Find(queryOptions map[string]interface{}) (int64, []*Employee, error)
FindByIds(queryOptions map[string]interface{}) (int64, []*Employee, error)
FindAll(queryOptions map[string]interface{}) (int64, []*Employee, error)
}
func (employee *Employee) Identify() interface{} {
... ... @@ -49,6 +55,9 @@ func (employee *Employee) Update(data map[string]interface{}) error {
if permissions, ok := data["permissions"]; ok {
employee.Permissions = permissions.([]int)
}
if createTime, ok := data["createTime"]; ok && !createTime.(time.Time).IsZero() {
employee.CreateTime = createTime.(time.Time)
}
return nil
}
... ...
package domain
import (
"time"
)
// 兑换现金活动
type ExchangeCashActivity struct {
ActivityId int64 `json:"activityId"` // 兑换现金活动id
ExchangeActivityName string `json:"exchangeActivityName"` // 兑换现金活动名称
CompanyId int64 `json:"companyId"` // 公司ID
ExchangedCash float64 `json:"exchangedCash"` // 已兑换的现金
ExchangedSuMoney float64 `json:"exchangedSuMoney"` // 已兑换的素币
Deadline time.Time `json:"deadline"` // 兑换现金活动截止时间
CountDown int64 `json:"countDown"` // 兑换现金活动结束倒计时
Rate float64 `json:"rate"` // 兑换汇率
CreateTime time.Time `json:"createTime"` // 创建兑换现金活动时间
}
type ExchangeActivityRepository interface {
Save(exchangeCashActivity *ExchangeCashActivity) (*ExchangeCashActivity, error)
Remove(exchangeCashActivity *ExchangeCashActivity) (*ExchangeCashActivity, error)
FindOne(queryOptions map[string]interface{}) (*ExchangeCashActivity, error)
Find(queryOptions map[string]interface{}) (int64, []*ExchangeCashActivity, error)
FindAll(queryOptions map[string]interface{}) (int64, []*ExchangeCashActivity, error)
}
func (exchangeCashActivity *ExchangeCashActivity) Identity() interface{} {
if exchangeCashActivity.ActivityId == 0 {
return nil
}
return exchangeCashActivity.ActivityId
}
func (exchangeCashActivity *ExchangeCashActivity) Update(data map[string]interface{}) error {
if exchangeActivityName, ok := data["exchangeActivityName"]; ok && exchangeActivityName != "" {
exchangeCashActivity.ExchangeActivityName = exchangeActivityName.(string)
}
if deadline, ok := data["deadline"]; ok && deadline != "" {
exchangeCashActivity.Deadline = deadline.(time.Time)
}
if countDown, ok := data["countDown"]; ok && countDown != 0 {
exchangeCashActivity.CountDown = countDown.(int64)
}
if exchangedSuMoney, ok := data["exchangedSuMoney"]; ok && exchangedSuMoney != 0 {
exchangeCashActivity.ExchangedSuMoney = exchangedSuMoney.(float64)
}
if exchangedCash, ok := data["exchangedCash"]; ok && exchangedCash != 0 {
exchangeCashActivity.ExchangedCash = exchangedCash.(float64)
}
if exchangeRate, ok := data["exchangeRate"]; ok && exchangeRate != 0 {
exchangeCashActivity.Rate = exchangeRate.(float64)
}
if createTime, ok := data["createTime"]; ok && createTime.(time.Time).IsZero() {
exchangeCashActivity.CreateTime = createTime.(time.Time)
}
exchangeCashActivity.CreateTime = time.Now()
return nil
}
func (exchangeCashActivity *ExchangeCashActivity) TransferSuMoney(rate float64) error {
exchangeCashActivity.ExchangedSuMoney = exchangeCashActivity.ExchangedCash * rate
return nil
}
func (exchangeCashActivity *ExchangeCashActivity) TransferCountDown() error {
exchangeCashActivity.CountDown = int64(time.Until(exchangeCashActivity.Deadline))
return nil
}
... ...
package domain
import (
"fmt"
"strconv"
)
// 参与兑换现金人员
type ExchangeCashPersonList struct {
ListId int64 `json:"listId"` // 清单id
EmployeeInfo *EmployeeInfo `json:"employeeInfo"` // 兑换人信息
ExchangeCashActivityId int64 `json:"exchangeActivityId"` // 参与的兑换活动id
ExchangedSuMoney float64 `json:"suMoney"` // 已兑换的素币
ExchangedCash float64 `json:"cash"` // 已兑换的现金
}
type ExchangeCashPersonListRepository interface {
Save(exchangeCashPersonList *ExchangeCashPersonList) (*ExchangeCashPersonList, error)
Remove(exchangeCashPersonList *ExchangeCashPersonList) (*ExchangeCashPersonList, error)
FindOne(queryOptions map[string]interface{}) (*ExchangeCashPersonList, error)
Find(queryOptions map[string]interface{}) (int64, []*ExchangeCashPersonList, error)
FindAll(queryOptions map[string]interface{}) (int64, []*ExchangeCashPersonList, error)
FindById(queryOptions map[string]interface{}) (int64, []*ExchangeCashPersonList, error)
}
func (exchangeCashPersonList *ExchangeCashPersonList) Identity() interface{} {
if exchangeCashPersonList.ListId == 0 {
return nil
}
return exchangeCashPersonList.ListId
}
func (exchangeCashPersonList *ExchangeCashPersonList) Update(data map[string]interface{}) error {
if exchangedSuMoney, ok := data["exchangedSuMoney"]; ok && exchangedSuMoney != 0 {
exchangeCashPersonList.ExchangedSuMoney = exchangedSuMoney.(float64)
}
if exchangedCash, ok := data["exchangedCash"]; ok && exchangedCash != 0 {
exchangeCashPersonList.ExchangedCash, _ = strconv.ParseFloat(fmt.Sprintf("%.2F", exchangedCash.(float64)), 64)
}
return nil
}
\ No newline at end of file
... ...
package domain
import (
"time"
)
// 排行榜时间
type ListInterval struct {
ListIntervalId int `json:"listIntervalId"` // 排行榜时间id
CompanyId int `json:"companyId"` // 公司id
IntervalStartTime time.Time `json:"intervalStartTime"` // 排行榜开始时间
IntervalEndTime time.Time `json:"intervalEndTime"` // 排行榜结束时间
}
type ListIntervalRepository interface {
Save(listInterval *ListInterval) (*ListInterval, error)
Remove(listInterval *ListInterval) (*ListInterval, error)
FindOne(queryOptions map[string]interface{}) (*ListInterval, error)
Find(queryOptions map[string]interface{}) (int64, []*ListInterval, error)
FindAll(queryOptions map[string]interface{}) (int64, []*ListInterval, error)
}
func (listInterval *ListInterval) Identify() interface{} {
if listInterval.ListIntervalId == 0 {
return nil
}
return listInterval.ListIntervalId
}
func (listInterval *ListInterval) Update(data map[string]interface{}) error {
if listIntervalStartTime, ok := data["listIntervalStartTime"]; ok {
listInterval.IntervalStartTime = listIntervalStartTime.(time.Time)
}
if listIntervalEndTime, ok := data["listIntervalEndTime"]; ok {
listInterval.IntervalEndTime = listIntervalEndTime.(time.Time)
}
return nil
}
\ No newline at end of file
... ...
... ... @@ -8,5 +8,5 @@ import (
type AcceptanceTaskService interface {
coreDomain.DomainEventPublisher
Acceptance(taskId int64, operatorUid int64, participators []int64, taskPercentage []*domain.TaskPercentageItem, referenceResourceScore []*domain.ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) (*domain.Task, error)
Acceptance(taskId int64, operatorUid int64, participators []int64, suMoney float64, taskPercentage []*domain.TaskPercentageItem, referenceResourceScore []*domain.ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) (*domain.Task, error)
}
... ...
... ... @@ -3,32 +3,28 @@ package domain
import "time"
const (
SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE = iota + 1 //兑换
SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE = iota + 1 //兑换物资
SU_MONEY_TRANSACTION_RECORD_TYPE_AWARD //任务奖励
SU_MONEY_TRANSACTION_RECORD_TYPE_INCREASE //增加
SU_MONEY_TRANSACTION_RECORD_TYPE_DEDUCT //扣除
SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE_CASH //兑换现金
SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE_CASH_RESTORE // 兑换现金撤销
)
// 素币事务记录
type SuMoneyTransactionRecord struct {
// 素币事务记录ID
SuMoneyTransactionRecordId int64 `json:"suMoneyTransactionRecordId"`
// 记录类型
RecordType int `json:"recordType"`
// 记录关联员工
Employee *EmployeeInfo `json:"employee"`
// 事务处理前素币值
SuMoneyBeforeTransaction float64 `json:"suMoneyBeforeTransaction"`
// 当前素币值
CurrentSuMoney float64 `json:"currentSuMoney"`
// 事务素币值
SuMoney float64 `json:"suMoney"`
// 操作人
Operator *EmployeeInfo `json:"operator"`
// 素币事务记录描述
RecordDescription string `json:"recordDescription"`
// 创建时间
CreateTime time.Time `json:"createTime"`
SuMoneyTransactionRecordId int64 `json:"suMoneyTransactionRecordId"` // 素币事务记录ID
RecordType int `json:"recordType"` // 记录类型
Employee *EmployeeInfo `json:"employee"` // 记录关联员工
SuMoneyBeforeTransaction float64 `json:"suMoneyBeforeTransaction"` // 事务处理前素币值
CurrentSuMoney float64 `json:"currentSuMoney"` // 当前素币值
SuMoney float64 `json:"suMoney"` // 事务素币值
CashBeforeTransaction float64 `json:"cashBeforeTransaction"` // 事务处理前现金值
CurrentCash float64 `json:"currentCash"` // 当前现金值
Cash float64 `json:"cash"` // 事务现金值
Operator *EmployeeInfo `json:"operator"` // 操作人
RecordDescription string `json:"recordDescription"` // 素币事务记录描述
CreateTime time.Time `json:"createTime"` // 创建时间
}
type SuMoneyTransactionRecordRepository interface {
... ... @@ -36,6 +32,7 @@ type SuMoneyTransactionRecordRepository interface {
Remove(suMoneyTransactionRecord *SuMoneyTransactionRecord) (*SuMoneyTransactionRecord, error)
FindOne(queryOptions map[string]interface{}) (*SuMoneyTransactionRecord, error)
Find(queryOptions map[string]interface{}) (int64, []*SuMoneyTransactionRecord, error)
FindById(queryOptions map[string]interface{}) (int64, []*SuMoneyTransactionRecord, error)
}
func (suMoneyTransactionRecord *SuMoneyTransactionRecord) Identify() interface{} {
... ...
... ... @@ -24,6 +24,7 @@ const (
TASK_STATUS_COMPLETED //已完成
TASK_STATUS_CLOSED //关闭
TASK_STATUS_UNCONFIRMED //待确认
TASK_STATUS_EXPIRED //已过期
)
// 任务
... ... @@ -50,6 +51,10 @@ type Task struct {
TaskNature int `json:"taskNature"`
// 奖励素币
SuMoney float64 `json:"suMoney"`
// 最小奖励素币
MinSuMoney float64 `json:"minSuMoney"`
// 最大奖励素币
MaxSuMoney float64 `json:"maxSuMoney"`
// 验收标准
AcceptanceStandard string `json:"acceptanceStandard"`
// 任务描述
... ... @@ -98,11 +103,12 @@ type TaskStatus interface {
ChooseSuccessfulBidder(task *Task, successfulBidder *EmployeeInfo, plannedCompletionTime time.Time) error
ApplyComplete(task *Task) error
Off(task *Task) error
Acceptance(task *Task, participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error
Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error
ConfirmTask(task *Task, plannedCompletionTime time.Time) error
RejectReceiver(task *Task) error
}
// 待发布的任务
type UnReleasedStatus struct{}
func (status *UnReleasedStatus) Update(task *Task, data map[string]interface{}) error {
... ... @@ -127,6 +133,12 @@ func (status *UnReleasedStatus) Update(task *Task, data map[string]interface{})
if suMoney, ok := data["suMoney"]; ok {
task.SuMoney = suMoney.(float64)
}
if minSuMoney, ok := data["minSuMoney"]; ok {
task.MinSuMoney = minSuMoney.(float64)
}
if maxSuMoney, ok := data["maxSuMoney"]; ok {
task.MaxSuMoney = maxSuMoney.(float64)
}
if task.TaskType == TASK_TYPE_BID {
if bidStartTime, ok := data["bidStartTime"]; ok {
task.BidInfo.BidStartTime = bidStartTime.(time.Time)
... ... @@ -198,7 +210,7 @@ func (status *UnReleasedStatus) Off(task *Task) error {
return fmt.Errorf("待发布的任务不允许关闭")
}
func (status *UnReleasedStatus) Acceptance(task *Task, participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
func (status *UnReleasedStatus) Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return fmt.Errorf("待发布的任务不允许验收")
}
... ... @@ -213,7 +225,68 @@ func (status *UnReleasedStatus) RejectReceiver(task *Task) error {
type UnClaimedStatus struct{}
func (status *UnClaimedStatus) Update(task *Task, data map[string]interface{}) error {
return fmt.Errorf("待领取的任务不允许编辑")
if taskName, ok := data["taskName"]; ok {
task.TaskName = taskName.(string)
}
if referenceResourceType, ok := data["referenceResourceType"]; ok {
task.ReferenceResource.ReferenceResourceType = referenceResourceType.(int)
}
if referenceResourceItems, ok := data["referenceResourceItems"]; ok {
task.ReferenceResource.ReferenceResourceItems = referenceResourceItems.([]*ReferenceResourceItem)
}
if projectBelong, ok := data["projectBelong"]; ok {
task.ProjectBelong = projectBelong.(int)
}
if customerValues, ok := data["customerValues"]; ok {
task.CustomerValues = customerValues.([]int)
}
if taskNature, ok := data["taskNature"]; ok {
task.TaskNature = taskNature.(int)
}
if suMoney, ok := data["suMoney"]; ok {
task.SuMoney = suMoney.(float64)
}
if minSuMoney, ok := data["minSuMoney"]; ok {
task.MinSuMoney = minSuMoney.(float64)
}
if maxSuMoney, ok := data["maxSuMoney"]; ok {
task.MaxSuMoney = maxSuMoney.(float64)
}
if task.TaskType == TASK_TYPE_BID {
if bidStartTime, ok := data["bidStartTime"]; ok {
task.BidInfo.BidStartTime = bidStartTime.(time.Time)
}
if bidEndTime, ok := data["bidEndTime"]; ok {
task.BidInfo.BidEndTime = bidEndTime.(time.Time)
}
if isRemind, ok := data["isRemind"]; ok {
task.BidInfo.IsRemind = isRemind.(bool)
}
}
if acceptanceStandard, ok := data["acceptanceStandard"]; ok {
task.AcceptanceStandard = acceptanceStandard.(string)
}
if taskDescription, ok := data["taskDescription"]; ok {
task.TaskDescription = taskDescription.(string)
}
if taskPictureUrls, ok := data["taskPictureUrls"]; ok {
task.TaskPictureUrls = taskPictureUrls.([]string)
}
if isRewardTake, ok := data["isRewardTake"]; ok {
task.IsRewardTake = isRewardTake.(bool)
}
if task.TaskType == TASK_TYPE_DESIGNATE {
if plannedCompletionTime, ok := data["plannedCompletionTime"]; ok {
task.PlannedCompletionTime = plannedCompletionTime.(time.Time)
}
if assignedPerson, ok := data["assignedPerson"]; ok {
task.AssignedPerson = assignedPerson.(*EmployeeInfo)
if task.AssignedPerson.Uid == 0 {
task.AssignedPerson = nil
}
}
}
return nil
}
func (status *UnClaimedStatus) Release(task *Task) error {
... ... @@ -286,7 +359,7 @@ func (status *UnClaimedStatus) Off(task *Task) error {
return nil
}
func (status *UnClaimedStatus) Acceptance(task *Task, participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
func (status *UnClaimedStatus) Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return fmt.Errorf("待领取的任务不允许验收")
}
... ... @@ -333,7 +406,7 @@ func (status *UnderwayStatus) Off(task *Task) error {
return nil
}
func (status *UnderwayStatus) Acceptance(task *Task, participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
func (status *UnderwayStatus) Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return fmt.Errorf("进行中的任务不允许验收")
}
... ... @@ -359,6 +432,7 @@ func (status *UnderwayStatus) RejectReceiver(task *Task) error {
return nil
}
// 代验收的任务
type UnAcceptanceStatus struct{}
func (status *UnAcceptanceStatus) Update(task *Task, data map[string]interface{}) error {
... ... @@ -391,8 +465,9 @@ func (status *UnAcceptanceStatus) Off(task *Task) error {
return nil
}
func (status *UnAcceptanceStatus) Acceptance(task *Task, participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
func (status *UnAcceptanceStatus) Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
task.Participators = participators
task.SuMoney = suMoney
task.TaskPercentage = taskPercentage
task.SolveReport = solveReport
task.SolvePictureUrls = solvePictureUrls
... ... @@ -451,7 +526,7 @@ func (status *CompletedStatus) Off(task *Task) error {
return fmt.Errorf("已完成的任务不允许申请完成任务")
}
func (status *CompletedStatus) Acceptance(task *Task, participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
func (status *CompletedStatus) Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return fmt.Errorf("已完成的任务不允许验收")
}
... ... @@ -493,7 +568,7 @@ func (status *ClosedStatus) Off(task *Task) error {
return fmt.Errorf("已关闭的任务不允许关闭")
}
func (status *ClosedStatus) Acceptance(task *Task, participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
func (status *ClosedStatus) Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return fmt.Errorf("已关闭的任务不允许验收")
}
... ... @@ -505,6 +580,7 @@ func (status *ClosedStatus) RejectReceiver(task *Task) error {
return fmt.Errorf("已关闭的任务不允许驳回任务领取人")
}
// 待确认任务
type UnConfirmedStatus struct{}
func (status *UnConfirmedStatus) Update(task *Task, data map[string]interface{}) error {
... ... @@ -537,7 +613,7 @@ func (status *UnConfirmedStatus) Off(task *Task) error {
return nil
}
func (status *UnConfirmedStatus) Acceptance(task *Task, participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
func (status *UnConfirmedStatus) Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return fmt.Errorf("待确认的任务不允许验收")
}
... ... @@ -560,6 +636,113 @@ func (status *UnConfirmedStatus) RejectReceiver(task *Task) error {
return nil
}
type ExpiredStatus struct{}
func (status ExpiredStatus) Update(task *Task, data map[string]interface{}) error {
if taskName, ok := data["taskName"]; ok {
task.TaskName = taskName.(string)
}
if referenceResourceType, ok := data["referenceResourceType"]; ok {
task.ReferenceResource.ReferenceResourceType = referenceResourceType.(int)
}
if referenceResourceItems, ok := data["referenceResourceItems"]; ok {
task.ReferenceResource.ReferenceResourceItems = referenceResourceItems.([]*ReferenceResourceItem)
}
if projectBelong, ok := data["projectBelong"]; ok {
task.ProjectBelong = projectBelong.(int)
}
if customerValues, ok := data["customerValues"]; ok {
task.CustomerValues = customerValues.([]int)
}
if taskNature, ok := data["taskNature"]; ok {
task.TaskNature = taskNature.(int)
}
if suMoney, ok := data["suMoney"]; ok {
task.SuMoney = suMoney.(float64)
}
if minSuMoney, ok := data["minSuMoney"]; ok {
task.MinSuMoney = minSuMoney.(float64)
}
if maxSuMoney, ok := data["maxSuMoney"]; ok {
task.MaxSuMoney = maxSuMoney.(float64)
}
if task.TaskType == TASK_TYPE_BID {
if bidStartTime, ok := data["bidStartTime"]; ok {
task.BidInfo.BidStartTime = bidStartTime.(time.Time)
}
if bidEndTime, ok := data["bidEndTime"]; ok {
task.BidInfo.BidEndTime = bidEndTime.(time.Time)
}
if isRemind, ok := data["isRemind"]; ok {
task.BidInfo.IsRemind = isRemind.(bool)
}
}
if acceptanceStandard, ok := data["acceptanceStandard"]; ok {
task.AcceptanceStandard = acceptanceStandard.(string)
}
if taskDescription, ok := data["taskDescription"]; ok {
task.TaskDescription = taskDescription.(string)
}
if taskPictureUrls, ok := data["taskPictureUrls"]; ok {
task.TaskPictureUrls = taskPictureUrls.([]string)
}
if isRewardTake, ok := data["isRewardTake"]; ok {
task.IsRewardTake = isRewardTake.(bool)
}
if task.TaskType == TASK_TYPE_DESIGNATE {
if plannedCompletionTime, ok := data["plannedCompletionTime"]; ok {
task.PlannedCompletionTime = plannedCompletionTime.(time.Time)
}
if assignedPerson, ok := data["assignedPerson"]; ok {
task.AssignedPerson = assignedPerson.(*EmployeeInfo)
if task.AssignedPerson.Uid == 0 {
task.AssignedPerson = nil
}
}
}
return nil
}
func (status ExpiredStatus) Release(task *Task) error {
currentTime := time.Now()
task.ReleaseTime = currentTime
task.TaskStatus = TASK_STATUS_UNCLAIMED
task.CurrentStatus = &UnClaimedStatus{}
return nil
}
func (status ExpiredStatus) Rob(task *Task, receiver *EmployeeInfo) error {
return fmt.Errorf("已过期的任务不允许抢单")
}
func (status ExpiredStatus) Bib(task *Task, bidder *EmployeeInfo) error {
return fmt.Errorf("已过期的任务不允许竞标")
}
func (status ExpiredStatus) ChooseSuccessfulBidder(task *Task, successfulBidder *EmployeeInfo, plannedCompletionTime time.Time) error {
return fmt.Errorf("已过期的任务不允许选择竞标任务的中标人")
}
func (status ExpiredStatus) ApplyComplete(task *Task) error {
return fmt.Errorf("已过期的任务不允许申请完成任务")
}
func (status ExpiredStatus) Off(task *Task) error {
return fmt.Errorf("已过期的任务不允许关闭")
}
func (status ExpiredStatus) Acceptance(task *Task, participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return fmt.Errorf("已过期的任务不允许验收")
}
func (status ExpiredStatus) ConfirmTask(task *Task, plannedCompletionTime time.Time) error {
return fmt.Errorf("已过期的任务不允许确认任务领取人")
}
func (status ExpiredStatus) RejectReceiver(task *Task) error {
return fmt.Errorf("已过期的任务不允许驳回任务领取人")
}
type TaskRepository interface {
Save(task *Task) (*Task, error)
Remove(task *Task) (*Task, error)
... ... @@ -602,8 +785,8 @@ func (task *Task) Off() error {
return task.CurrentStatus.Off(task)
}
func (task *Task) Acceptance(participators []*EmployeeInfo, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return task.CurrentStatus.Acceptance(task, participators, taskPercentage, referenceResourceScore, solveReport, solvePictureUrls, actualCompletionTime)
func (task *Task) Acceptance(participators []*EmployeeInfo, suMoney float64, taskPercentage []*TaskPercentageItem, referenceResourceScore []*ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) error {
return task.CurrentStatus.Acceptance(task, participators, suMoney, taskPercentage, referenceResourceScore, solveReport, solvePictureUrls, actualCompletionTime)
}
func (task *Task) ConfirmTask(plannedCompletionTime time.Time) error {
... ...
package dao
import (
"fmt"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg/models"
)
type CashPoolDao struct {
transactionContext *pgTransaction.TransactionContext
}
// 兑换活动兑换清单已兑换素币、已兑换现金
func (dao *CashPoolDao) CalculateActivityExchangedSuMoney(activityId int64) (map[string]interface{}, error) {
var activityExchangedSuMoney float64
var activityExchangedCash float64
tx := dao.transactionContext.PgTx
exchangeCashPersonListModels := new(models.ExchangeCashPersonList)
if err := tx.Model(exchangeCashPersonListModels).
ColumnExpr("sum(exchange_cash_person_list.exchanged_su_money) AS activity_exchanged_su_money").
Where("exchange_cash_person_list.activity_id = ?", activityId).
Select(&activityExchangedSuMoney); err !=nil {
return nil, err
}
if err := tx.Model(exchangeCashPersonListModels).
ColumnExpr("sum(exchange_cash_person_list.exchanged_cash) AS activity_exchanged_cash").
Where("exchange_cash_person_list.activity_id = ?", activityId).
Select(&activityExchangedCash); err !=nil {
return nil, err
}
return map[string]interface{}{
"activityExchangedSuMoney": activityExchangedSuMoney,
"activityExchangedCash": activityExchangedCash,
}, nil
}
// 返回兑换活动清单榜单
func (dao *CashPoolDao) ExchangeCashListRanking(queryOptions map[string]interface{}) (map[string]interface{}, error) {
var retPeople []struct {
Uid int64
EmployeeName string
SuMoney float64
Cash float64
Ranking int
}
var retEmployee []struct {
Uid int64
EmployeeName string
SuMoney float64
Cash float64
Ranking int
}
tx := dao.transactionContext.PgTx
exchangeCashPersonListModels := new(models.ExchangeCashPersonList)
// 清单人员排名
queryPeople := tx.Model(exchangeCashPersonListModels)
queryPeople = queryPeople.Join("JOIN employees AS e ON e.uid = exchange_cash_person_list.uid")
queryPeople = queryPeople.ColumnExpr("exchange_cash_person_list.uid AS uid")
//queryPeople = queryPeople.ColumnExpr("exchange_cash_person_list.employee_name AS employee_name")
queryPeople = queryPeople.ColumnExpr("sum(exchange_cash_person_list.exchanged_cash) AS cash")
queryPeople = queryPeople.ColumnExpr("sum(exchange_cash_person_list.exchanged_su_money) AS su_money")
queryPeople = queryPeople.ColumnExpr("ROW_NUMBER() OVER (ORDER BY sum(exchange_cash_person_list.exchanged_su_money) DESC, e.create_time ASC) AS ranking")
//queryPeople = queryPeople.Where("e.status = ?", 1)
if companyId, ok := queryOptions["companyId"]; ok && (companyId.(int64) != 0) {
queryPeople = queryPeople.Where("e.company_id = ?", companyId)
}
if activityId, ok := queryOptions["activityId"]; ok && (activityId.(int64) != 0){
queryPeople = queryPeople.Where("exchange_cash_person_list.activity_id = ?", activityId)
}
queryPeople = queryPeople.Group("exchange_cash_person_list.uid")
queryPeople = queryPeople.Group("e.create_time")
//queryPeople = queryPeople.Group("exchange_cash_person_list.employee_name")
if offset, ok := queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
queryPeople = queryPeople.Offset(offset)
}
} else {
queryPeople = queryPeople.Offset(0)
}
if limit, ok := queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
queryPeople = queryPeople.Limit(limit)
}
} else {
queryPeople = queryPeople.Limit(20)
}
if err := queryPeople.Order("ranking ASC").Select(&retPeople); err != nil {
return nil, err
}
// 个人清单排名
queryPeopleAll := tx.Model(exchangeCashPersonListModels)
queryPeopleAll = queryPeopleAll.Join("JOIN employees AS e ON e.uid = exchange_cash_person_list.uid")
queryPeopleAll = queryPeopleAll.ColumnExpr("exchange_cash_person_list.uid AS uid")
//queryPeopleAll = queryPeopleAll.ColumnExpr("exchange_cash_person_list.employee_name AS employee_name")
queryPeopleAll = queryPeopleAll.ColumnExpr("sum(exchange_cash_person_list.exchanged_cash) AS cash")
queryPeopleAll = queryPeopleAll.ColumnExpr("sum(exchange_cash_person_list.exchanged_su_money) AS su_money")
queryPeopleAll = queryPeopleAll.ColumnExpr("ROW_NUMBER() OVER (ORDER BY sum(exchange_cash_person_list.exchanged_su_money) DESC, e.create_time ASC) AS ranking")
if companyId, ok := queryOptions["companyId"]; ok && (companyId.(int64) != 0) {
queryPeopleAll = queryPeopleAll.Where("e.company_id = ?", companyId)
}
if activityId, ok := queryOptions["activityId"]; ok && (activityId.(int64) != 0){
queryPeopleAll = queryPeopleAll.Where("exchange_cash_person_list.activity_id = ?", activityId)
}
queryPeopleAll = queryPeopleAll.Group("exchange_cash_person_list.uid")
queryPeopleAll = queryPeopleAll.Group("e.create_time")
//queryPeopleAll = queryPeopleAll.Group("exchange_cash_person_list.employee_name")
queryPeopleAllWith := queryPeopleAll.Order("su_money DESC")
queryEmployee := tx.Model()
queryEmployee = queryEmployee.With("t", queryPeopleAllWith)
queryEmployee = queryEmployee.Table("t")
queryEmployee = queryEmployee.ColumnExpr("t.uid AS uid")
//queryEmployee = queryEmployee.ColumnExpr("t.employee_name AS employee_name")
queryEmployee = queryEmployee.ColumnExpr("t.cash AS cash")
queryEmployee = queryEmployee.ColumnExpr("t.su_money AS su_money")
queryEmployee = queryEmployee.ColumnExpr("t.ranking AS ranking")
if uid, ok := queryOptions["uid"]; ok {
queryEmployee = queryEmployee.Where("t.uid::bigint = ?", uid)
}
if err := queryEmployee.Select(&retEmployee); err != nil {
return nil, err
}
var currentEmployee interface{}
if len(retEmployee) == 0 {
currentEmployee = nil
} else {
currentEmployee = retEmployee[0]
}
// 清单已兑换素币
var activityExchangedSuMoney float64
queryListSuMoney := tx.Model(exchangeCashPersonListModels)
queryListSuMoney = queryListSuMoney.Join("JOIN employees AS e ON e.uid = exchange_cash_person_list.uid")
queryListSuMoney = queryListSuMoney.ColumnExpr("sum(exchange_cash_person_list.exchanged_su_money) AS activity_exchanged_su_money")
//queryListSuMoney = queryListSuMoney.Where("e.status = ?", 1)
if companyId, ok := queryOptions["companyId"]; ok && (companyId.(int64) != 0) {
queryListSuMoney = queryListSuMoney.Where("e.company_id = ?", companyId)
}
if activityId, ok := queryOptions["activityId"]; ok && (activityId.(int64) != 0) {
queryListSuMoney = queryListSuMoney.Where("exchange_cash_person_list.activity_id = ?", activityId)
}
if err := queryListSuMoney.Select(&activityExchangedSuMoney); err != nil {
return nil, err
}
// 清单已兑换现金
var activityExchangedCash float64
queryListCash := tx.Model(exchangeCashPersonListModels)
queryListCash = queryListCash.Join("JOIN employees AS e ON e.uid = exchange_cash_person_list.uid")
queryListCash = queryListCash.ColumnExpr("sum(exchange_cash_person_list.exchanged_cash) AS activity_exchanged_cash")
//queryListCash = queryListCash.Where("e.status = ?", 1)
if companyId, ok := queryOptions["companyId"]; ok && (companyId.(int64) != 0) {
queryListCash = queryListCash.Where("e.company_id = ?", companyId)
}
if activityId, ok := queryOptions["activityId"]; ok && (activityId.(int64) != 0) {
queryListCash = queryListCash.Where("exchange_cash_person_list.activity_id = ?", activityId)
}
if err := queryListCash.Select(&activityExchangedCash); err != nil {
return nil, err
}
// 清单计数
queryCount := tx.Model(exchangeCashPersonListModels)
count, err := queryCount.Count()
if err != nil {
return nil, err
}
return map[string]interface{} {
"people": retPeople, // 员工排行榜
"count": count, // 计数
"currentEmployee": currentEmployee, // 当前员工排名
"exchangedSuMoney": activityExchangedSuMoney, // 清单已兑换素币
"exchangedCash": activityExchangedCash, // 清单已兑换现金
}, nil
}
func NewCashPoolDao(transactionContext *pgTransaction.TransactionContext) (*CashPoolDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &CashPoolDao{
transactionContext: transactionContext,
}, nil
}
}
\ No newline at end of file
... ...
... ... @@ -13,15 +13,23 @@ type EmployeeDao struct {
transactionContext *pgTransaction.TransactionContext
}
// 删除用户(stevechan: 删除员工为修改为禁用状态)
func (dao *EmployeeDao) BatchRemove(uids []int64) error {
//tx := dao.transactionContext.PgTx
//_, err := tx.QueryOne(
// pg.Scan(),
// "DELETE FROM employees WHERE uid IN (?)",
// pg.In(uids))
//return err
tx := dao.transactionContext.PgTx
_, err := tx.QueryOne(
pg.Scan(),
"DELETE FROM employees WHERE uid IN (?)",
"UPDATE employees SET status = 2 WHERE uid IN (?)",
pg.In(uids))
return err
}
// 设置用户状态
func (dao *EmployeeDao) BatchSetStatus(uids []int64, status int) error {
tx := dao.transactionContext.PgTx
_, err := tx.QueryOne(
... ... @@ -31,6 +39,7 @@ func (dao *EmployeeDao) BatchSetStatus(uids []int64, status int) error {
return err
}
// 修改用户权限
func (dao *EmployeeDao) ChangePrincipal(companyId int64, employeeAccount string) error {
tx := dao.transactionContext.PgTx
if _, err := tx.Query(
... ... @@ -48,6 +57,7 @@ func (dao *EmployeeDao) ChangePrincipal(companyId int64, employeeAccount string)
return nil
}
// 更新用户素币
func (dao *EmployeeDao) TransferSuMoney(uid int64, suMoney float64) error {
tx := dao.transactionContext.PgTx
_, err := tx.QueryOne(
... ... @@ -57,6 +67,7 @@ func (dao *EmployeeDao) TransferSuMoney(uid int64, suMoney float64) error {
return err
}
// 计算个人未读消息
func (dao *EmployeeDao) CalculatePersonUnReadNotification(uid int64) (map[string]int, error) {
var unReadSystemNotification int
var unReadInteractionNotification int
... ... @@ -86,39 +97,130 @@ func (dao *EmployeeDao) CalculatePersonUnReadNotification(uid int64) (map[string
}, nil
}
// 计算个人素币收益,昨日收益:做任务验收获得的素币+额外增加-扣除素币-兑换物资-兑换现金
func (dao *EmployeeDao) CalculatePersonSuMoney(uid int64) (map[string]interface{}, error) {
var incomeSuMoney float64
var incomeSuMoneyOfYesterday float64
var expendSuMoneyOfYesterday float64
tx := dao.transactionContext.PgTx
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
yesterday := time.Now().AddDate(0, 0, -1)
yesterday := time.Now().Local().AddDate(0, 0, -1)
// 昨日收益
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
Where(`su_money_transaction_record.record_type = ?`, 2).
Where(`su_money_transaction_record.create_time > ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, yesterday.Location())).
Where(`su_money_transaction_record.create_time < ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 0, yesterday.Location())).
Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{2, 3, 6})).
Where(`su_money_transaction_record.create_time > ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, time.Local)).
Where(`su_money_transaction_record.create_time < ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 0, time.Local)).
Select(&incomeSuMoneyOfYesterday); err != nil {
return nil, err
}
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{4, 1, 5})).
Where(`su_money_transaction_record.create_time > ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, time.Local)).
Where(`su_money_transaction_record.create_time < ?`, time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 0, time.Local)).
Select(&expendSuMoneyOfYesterday); err != nil {
return nil, err
}
// 个人收益
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
Where(`su_money_transaction_record.record_type = ?`, 2).
Select(&incomeSuMoney); err != nil {
return nil, err
}
return map[string]interface{}{
"incomeSuMoney": incomeSuMoney,
"incomeSuMoneyOfYesterday": incomeSuMoneyOfYesterday,
"incomeSuMoneyOfYesterday": incomeSuMoneyOfYesterday - expendSuMoneyOfYesterday,
}, nil
}
// 计算系统已兑换现金素币、未兑换素币
func (dao *EmployeeDao) CalculateSystemSuMoney(companyId int64) (map[string] interface{}, error) {
var systemUnExchangeSuMoney float64
var systemExchangedSuMoney float64
var systemExchangedSuMoneyRestore float64
tx := dao.transactionContext.PgTx
// 系统未兑换素币
employeeModel := new(models.Employee)
if err := tx.Model(employeeModel).
ColumnExpr("sum(employee.su_money) AS system_unExchange_su_money").
Where("employee.company_id = ?", companyId).
Where("employee.status = ?", 1).
Select(&systemUnExchangeSuMoney); err != nil {
return nil, err
}
// 系统已兑换现金素币
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
if err := tx.Model(suMoneyTransactionRecordModel).Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint").
ColumnExpr("sum(su_money_transaction_record.su_money) AS system_exchanged_su_money").
Where("e.company_id = ?", companyId).
//Where("e.status = ?", 1).
Where(`su_money_transaction_record.record_type = ?`, domain.SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE_CASH).
Select(&systemExchangedSuMoney); err != nil {
return nil, err
}
// 系统撤销的兑换现金素币
if err := tx.Model(suMoneyTransactionRecordModel).Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint").
ColumnExpr("sum(su_money_transaction_record.su_money) AS system_exchanged_su_money").
Where("e.company_id = ?", companyId).
//Where("e.status = ?", 1).
Where(`su_money_transaction_record.record_type = ?`, domain.SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE_CASH_RESTORE).
Select(&systemExchangedSuMoneyRestore); err != nil {
return nil, err
}
return map[string] interface{} {
"systemUnExchangeSuMoney": systemUnExchangeSuMoney,
"systemExchangedSuMoney": systemExchangedSuMoney - systemExchangedSuMoneyRestore,
},nil
}
// 计算现金池已兑换现金、未兑换现金
func (dao *EmployeeDao) CalculateSystemCash(companyId int64) (map[string] interface{}, error) {
tx := dao.transactionContext.PgTx
var (
systemUnExchangeCash float64
systemExchangedCash float64
)
// 系统已兑换现金
cashPool := new(models.CashPool)
if err := tx.Model(cashPool).
Column("exchanged_cash").
Where("cash_pool.company_id = ?", companyId).
Order("id DESC").
Limit(1).
Select(&systemExchangedCash) ; err != nil {
return nil, err
}
// 系统未兑换现金
if err := tx.Model(cashPool).
Column("un_exchange_cash").
Where("cash_pool.company_id = ?", companyId).
Order("id DESC").
Limit(1).
Select(&systemUnExchangeCash) ; err != nil {
return nil, err
}
return map[string] interface{} {
"systemUnExchangeCash": systemUnExchangeCash,
"systemExchangedCash": systemExchangedCash,
}, nil
}
// 计算个人素币收支(素币明细收支)
func (dao *EmployeeDao) CalculateSuMoneyTransactionRecord(uid int64, transactionStartTime time.Time, transactionEndTime time.Time) (map[string]interface{}, error) {
var incomeSuMoney float64
var expendSuMoney float64
var (
incomeSuMoney float64 // 收入的素币(2:任务奖励,3:增加)
expendSuMoney float64 // 消耗的素币(1:兑换物资,4:扣除)
expendSuMoneyExchange float64 // 5: 兑换现金
incomeSuMoneyExchangeRestore float64 // 6: 兑换素币撤回
)
tx := dao.transactionContext.PgTx
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
// 收入素币
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
... ... @@ -128,6 +230,7 @@ func (dao *EmployeeDao) CalculateSuMoneyTransactionRecord(uid int64, transaction
Select(&incomeSuMoney); err != nil {
return nil, err
}
// 支出素币
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS expend_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
... ... @@ -137,9 +240,349 @@ func (dao *EmployeeDao) CalculateSuMoneyTransactionRecord(uid int64, transaction
Select(&expendSuMoney); err != nil {
return nil, err
}
// 兑换现金的
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS expend_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
Where(`su_money_transaction_record.record_type = ?`, 5).
Where(`su_money_transaction_record.create_time > ?`, transactionStartTime).
Where(`su_money_transaction_record.create_time < ?`, transactionEndTime).
Select(&expendSuMoneyExchange); err != nil {
return nil, err
}
// 兑换现金撤回的
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS expend_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
Where(`su_money_transaction_record.record_type = ?`, 6).
Where(`su_money_transaction_record.create_time > ?`, transactionStartTime).
Where(`su_money_transaction_record.create_time < ?`, transactionEndTime).
Select(&incomeSuMoneyExchangeRestore); err != nil {
return nil, err
}
return map[string]interface{}{
"incomeSuMoney": incomeSuMoney,
"expendSuMoney": expendSuMoney,
"incomeSuMoney": incomeSuMoney, // 个人素币收入
"expendSuMoney": expendSuMoney + (expendSuMoneyExchange - incomeSuMoneyExchangeRestore), // 个人素币支出
}, nil
}
// 计算个人贡献值收支(贡献明细收支)
func (dao *EmployeeDao) CalculateContributionsTransactionRecord(uid int64, transactionStartTime time.Time, transactionEndTime time.Time) (map[string]interface{}, error) {
var (
incomeContributions float64 // 收入的贡献值(2:任务奖励,3:增加)
expendContributions float64 // 支出的贡献值 (4: 扣除)
)
tx := dao.transactionContext.PgTx
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
if transactionStartTime.IsZero() && transactionEndTime.IsZero() {
transactionStartTime = time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local)
transactionEndTime = time.Now()
}
// 收入的贡献值
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS income_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{2, 3})).
Where(`su_money_transaction_record.create_time > ?`, transactionStartTime).
Where(`su_money_transaction_record.create_time < ?`, transactionEndTime).
Select(&incomeContributions); err != nil {
return nil, err
}
// 支出的贡献值
if err := tx.Model(suMoneyTransactionRecordModel).
ColumnExpr("sum(su_money_transaction_record.su_money) AS expend_su_money").
Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid).
Where(`su_money_transaction_record.record_type = ?`, 4).
Where(`su_money_transaction_record.create_time > ?`, transactionStartTime).
Where(`su_money_transaction_record.create_time < ?`, transactionEndTime).
Select(&expendContributions); err != nil {
return nil, err
}
return map[string]interface{}{
"incomeContributions": incomeContributions, // 个人贡献值收入
"expendContributions": expendContributions, // 个人贡献支出
}, nil
}
// 贡献值、财富值总榜和年榜,
func (dao *EmployeeDao) ContributionsWealthRanking(queryOptions map[string]interface{}) (interface{}, error) {
var retWealth []struct { // 个人财富值
Uid int64
EmployeeName string
EmployeeSuMoney float64
Ranking int
}
var retEmployeeWealth []struct { // 个人贡献值
Uid int64
EmployeeName string
EmployeeSuMoney float64
Ranking int
}
var retContributions []struct { // 员工贡献值
Uid int64
EmployeeName string
EmployeesContributions float64
Ranking int
}
var retEmployeeContributions []struct { // 员工贡献值
Uid int64
EmployeeName string
EmployeesContributions float64
Ranking int
}
tx := dao.transactionContext.PgTx
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
// 财富值排行榜
queryWealth := tx.Model(suMoneyTransactionRecordModel)
queryWealth = queryWealth.Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint")
queryWealth = queryWealth.ColumnExpr("su_money_transaction_record.employee->>'uid' AS uid")
//queryWealth = queryWealth.ColumnExpr("su_money_transaction_record.employee->>'employeeName' AS employee_name")
queryWealth = queryWealth.ColumnExpr("sum(case WHEN su_money_transaction_record.record_type IN (2, 3, 6) THEN su_money_transaction_record.su_money ELSE 0 end) - sum(case WHEN su_money_transaction_record.record_type IN (4, 1, 5) THEN su_money_transaction_record.su_money ELSE 0 end) AS employee_su_money")
queryWealth = queryWealth.ColumnExpr("ROW_NUMBER() OVER (ORDER BY sum(case WHEN su_money_transaction_record.record_type IN (2, 3, 6) THEN su_money_transaction_record.su_money ELSE 0 end) - sum(case WHEN su_money_transaction_record.record_type IN (4, 1, 5) THEN su_money_transaction_record.su_money ELSE 0 end) DESC, e.create_time ASC) AS ranking")
queryWealth = queryWealth.Where(`e.status = ?`, 1)
//queryWealth = queryWealth.GroupExpr("su_money_transaction_record.employee->>'uid',su_money_transaction_record.employee->>'employeeName'")
queryWealth = queryWealth.GroupExpr("su_money_transaction_record.employee->>'uid', e.create_time")
if companyId, ok := queryOptions["companyId"]; ok && (companyId.(int64) != 0) {
queryWealth = queryWealth.Where("e.company_id = ?", companyId)
}
if startTime, ok := queryOptions["startTime"]; ok && !startTime.(time.Time).IsZero() {
queryWealth = queryWealth.Where(`su_money_transaction_record.create_time > ?`, startTime)
}
if endTime, ok := queryOptions["endTime"]; ok && !endTime.(time.Time).IsZero() {
queryWealth = queryWealth.Where(`su_money_transaction_record.create_time < ?`, endTime)
}
if offset, ok := queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
queryWealth = queryWealth.Offset(offset)
}
} else {
queryWealth = queryWealth.Offset(0)
}
if limit, ok := queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
queryWealth = queryWealth.Limit(limit)
}
} else {
queryWealth = queryWealth.Limit(20)
}
queryWealth = queryWealth.Order("ranking ASC")
if err := queryWealth.Select(&retWealth); err != nil {
return nil, err
}
// 个人财富值排名
queryWealthWith := tx.Model(suMoneyTransactionRecordModel)
queryWealthWith = queryWealthWith.Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint")
queryWealthWith = queryWealthWith.ColumnExpr("su_money_transaction_record.employee->>'uid' AS uid")
//queryWealthWith = queryWealthWith.ColumnExpr("su_money_transaction_record.employee->>'employeeName' AS employee_name")
queryWealthWith = queryWealthWith.ColumnExpr("sum(case WHEN su_money_transaction_record.record_type IN (2, 3, 6) THEN su_money_transaction_record.su_money ELSE 0 end) - sum(case WHEN su_money_transaction_record.record_type IN (4, 1, 5) THEN su_money_transaction_record.su_money ELSE 0 end) AS employee_su_money")
queryWealthWith = queryWealthWith.ColumnExpr("ROW_NUMBER() OVER (ORDER BY sum(case WHEN su_money_transaction_record.record_type IN (2, 3, 6) THEN su_money_transaction_record.su_money ELSE 0 end) - sum(case WHEN su_money_transaction_record.record_type IN (4, 1, 5) THEN su_money_transaction_record.su_money ELSE 0 end) DESC, e.create_time ASC) AS ranking")
queryWealthWith = queryWealthWith.Where(`e.status = ?`, 1)
if companyId, ok := queryOptions["companyId"]; ok && (companyId.(int64) != 0) {
queryWealthWith = queryWealthWith.Where("e.company_id = ?", companyId)
}
if startTime, ok := queryOptions["startTime"]; ok && !startTime.(time.Time).IsZero() {
queryWealthWith = queryWealthWith.Where(`su_money_transaction_record.create_time > ?`, startTime)
}
if endTime, ok := queryOptions["endTime"]; ok && !endTime.(time.Time).IsZero() {
queryWealthWith = queryWealthWith.Where(`su_money_transaction_record.create_time < ?`, endTime)
}
//queryWealthRestoreWith := queryWealthWith.GroupExpr("su_money_transaction_record.employee->>'uid',su_money_transaction_record.employee->>'employeeName', e.create_time")
queryWealthRestoreWith := queryWealthWith.GroupExpr("su_money_transaction_record.employee->>'uid', e.create_time")
querySelfWealth := tx.Model()
querySelfWealth = querySelfWealth.With("t", queryWealthRestoreWith)
querySelfWealth = querySelfWealth.Table("t")
querySelfWealth = querySelfWealth.ColumnExpr("t.uid AS uid")
//querySelfWealth = querySelfWealth.ColumnExpr("t.employee_name AS employee_name")
querySelfWealth = querySelfWealth.ColumnExpr("t.employee_su_money AS employee_su_money")
querySelfWealth = querySelfWealth.ColumnExpr("t.ranking AS ranking")
if uid, ok := queryOptions["uid"]; ok {
querySelfWealth = querySelfWealth.Where("t.uid::bigint = ?", uid)
}
if err := querySelfWealth.Select(&retEmployeeWealth); err != nil {
return nil, err
}
var retCurrentEmployeeWealth interface{}
if len(retEmployeeWealth) == 0 {
retCurrentEmployeeWealth = nil
} else {
retCurrentEmployeeWealth = retEmployeeWealth[0]
}
// 贡献值排行榜
queryContributions := tx.Model(suMoneyTransactionRecordModel)
queryContributions = queryContributions.Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint")
queryContributions = queryContributions.ColumnExpr("su_money_transaction_record.employee->>'uid' AS uid")
//queryContributions = queryContributions.ColumnExpr("su_money_transaction_record.employee->>'employeeName' AS employee_name")
queryContributions = queryContributions.ColumnExpr("sum(case WHEN su_money_transaction_record.record_type IN (2, 3) THEN su_money_transaction_record.su_money ELSE 0 end) - sum(case WHEN su_money_transaction_record.record_type = 4 THEN su_money_transaction_record.su_money ELSE 0 end) AS employees_contributions")
queryContributions = queryContributions.ColumnExpr("ROW_NUMBER() OVER (ORDER BY sum(case WHEN su_money_transaction_record.record_type IN (2, 3) THEN su_money_transaction_record.su_money ELSE 0 end) - sum(case WHEN su_money_transaction_record.record_type = 4 THEN su_money_transaction_record.su_money ELSE 0 end) DESC, e.create_time ASC) AS ranking")
queryContributions = queryContributions.Where(`e.status = ?`, 1)
//queryContributions = queryContributions.GroupExpr("su_money_transaction_record.employee->>'uid',su_money_transaction_record.employee->>'employeeName'")
queryContributions = queryContributions.GroupExpr("su_money_transaction_record.employee->>'uid', e.create_time")
if companyId, ok := queryOptions["companyId"]; ok && (companyId.(int64) != 0) {
queryContributions = queryContributions.Where("e.company_id = ?", companyId)
}
if startTime, ok := queryOptions["startTime"]; ok && !startTime.(time.Time).IsZero() {
queryContributions = queryContributions.Where(`su_money_transaction_record.create_time > ?`, startTime)
}
if endTime, ok := queryOptions["endTime"]; ok && !endTime.(time.Time).IsZero() {
queryContributions = queryContributions.Where(`su_money_transaction_record.create_time < ?`, endTime)
}
if offset, ok := queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
queryContributions = queryContributions.Offset(offset)
}
} else {
queryContributions = queryContributions.Offset(0)
}
if limit, ok := queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
queryContributions = queryContributions.Limit(limit)
}
} else {
queryContributions = queryContributions.Limit(20)
}
if err := queryContributions.Order("ranking ASC").Select(&retContributions); err != nil {
return nil, err
}
// 个人贡献值排名
queryContributionsWith := tx.Model(suMoneyTransactionRecordModel)
queryContributionsWith = queryContributionsWith.Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint")
queryContributionsWith = queryContributionsWith.ColumnExpr("su_money_transaction_record.employee->>'uid' AS uid")
//queryContributionsWith = queryContributionsWith.ColumnExpr("su_money_transaction_record.employee->>'employeeName' AS employee_name")
queryContributionsWith = queryContributionsWith.ColumnExpr("sum(case WHEN su_money_transaction_record.record_type IN (2, 3) THEN su_money_transaction_record.su_money ELSE 0 end) - sum(case WHEN su_money_transaction_record.record_type = 4 THEN su_money_transaction_record.su_money ELSE 0 end) AS employees_contributions")
queryContributionsWith = queryContributionsWith.ColumnExpr("ROW_NUMBER() OVER (ORDER BY sum(case WHEN su_money_transaction_record.record_type IN (2, 3) THEN su_money_transaction_record.su_money ELSE 0 end) - sum(case WHEN su_money_transaction_record.record_type = 4 THEN su_money_transaction_record.su_money ELSE 0 end) DESC, e.create_time ASC) AS ranking")
queryContributionsWith = queryContributionsWith.Where(`e.status = ?`, 1)
if companyId, ok := queryOptions["companyId"]; ok && (companyId.(int64) != 0) {
queryContributionsWith = queryContributionsWith.Where("e.company_id = ?", companyId)
}
if startTime, ok := queryOptions["startTime"]; ok && !startTime.(time.Time).IsZero() {
queryContributionsWith = queryContributionsWith.Where(`su_money_transaction_record.create_time > ?`, startTime)
}
if endTime, ok := queryOptions["endTime"]; ok && !endTime.(time.Time).IsZero() {
queryContributionsWith = queryContributionsWith.Where(`su_money_transaction_record.create_time < ?`, endTime)
}
//contributionsWith := queryContributionsWith.GroupExpr("su_money_transaction_record.employee->>'uid',su_money_transaction_record.employee->>'employeeName', e.create_time")
contributionsWith := queryContributionsWith.GroupExpr("su_money_transaction_record.employee->>'uid', e.create_time")
querySelfContributions := tx.Model()
querySelfContributions = querySelfContributions.With("t", contributionsWith)
querySelfContributions = querySelfContributions.Table("t")
querySelfContributions = querySelfContributions.ColumnExpr("t.uid AS uid")
//querySelfContributions = querySelfContributions.ColumnExpr("t.employee_name AS employee_name")
querySelfContributions = querySelfContributions.ColumnExpr("t.employees_contributions AS employees_contributions")
querySelfContributions = querySelfContributions.ColumnExpr("t.ranking AS ranking")
if uid, ok := queryOptions["uid"]; ok {
querySelfContributions = querySelfContributions.Where("t.uid::bigint = ?", uid)
}
if err := querySelfContributions.Select(&retEmployeeContributions); err != nil {
return nil, err
}
var retCurrentEmployeeContributions interface{}
if len(retEmployeeContributions) == 0 {
retCurrentEmployeeContributions = nil
} else {
retCurrentEmployeeContributions = retEmployeeContributions[0]
}
return map[string]interface{}{
"employeesWealth": retWealth,
"employeesContributions": retContributions,
"currentEmployeeContributions": retCurrentEmployeeContributions,
"currentEmployeeWealth": retCurrentEmployeeWealth,
}, nil
}
// 公司员工贡献值分组统计
func (dao *EmployeeDao) CalculateEmployeesContributions(companyId int, startTime time.Time, endTime time.Time) (map[string]interface{}, error) {
var ret []struct { // 员工贡献值
Uid int
EmployeeName string
EmployeesContributions float64
}
var retDecrease []struct { // 员工减少的贡献值
Uid int
EmployeeName string
EmployeesContributions float64
}
tx := dao.transactionContext.PgTx
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
// 增加的贡献值
if err := tx.Model(suMoneyTransactionRecordModel).Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint").
ColumnExpr("su_money_transaction_record.employee->>'uid' AS uid").
ColumnExpr("su_money_transaction_record.employee->>'employeeName' AS employee_name").
ColumnExpr("sum(su_money_transaction_record.su_money) AS employees_contributions").
Where(`e.company_id = ?`, companyId).
Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{2, 3})).
//Where(`e.status = ?`, 1).
Where(`su_money_transaction_record.create_time > ?`, startTime).
Where(`su_money_transaction_record.create_time < ?`, endTime).
Group("su_money_transaction_record.employee").
Order("employees_contributions DESC").
Select(&ret); err != nil {
return nil, err
}
// 减少的贡献值
if err := tx.Model(suMoneyTransactionRecordModel).Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint").
ColumnExpr("su_money_transaction_record.employee->>'uid' AS uid").
ColumnExpr("su_money_transaction_record.employee->>'employeeName' AS employee_name").
ColumnExpr("sum(su_money_transaction_record.su_money) AS employees_contributions").
Where(`e.company_id = ?`, companyId).
Where(`su_money_transaction_record.record_type = ?`, 4).
//Where(`e.status = ?`, 1).
Where(`su_money_transaction_record.create_time > ?`, startTime).
Where(`su_money_transaction_record.create_time < ?`, endTime).
Group("su_money_transaction_record.employee").
Order("employees_contributions DESC").
Select(&retDecrease); err != nil {
return nil, err
}
for i := 0; i < len(ret); i++ {
for j := 0; j < len(retDecrease); j++ {
if ret[i].Uid == retDecrease[j].Uid {
ret[i].EmployeesContributions -= retDecrease[j].EmployeesContributions
}
}
}
return map[string]interface{}{
"employeesContributions": ret,
}, nil
}
// 公司员工财富值分组统计
func (dao *EmployeeDao) CalculateEmployeesSuMoney(companyId int, startTime time.Time, endTime time.Time) (map[string]interface{}, error) {
var ret []struct {
Uid int
EmployeeName string
EmployeeSuMoney float64
}
tx := dao.transactionContext.PgTx
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
if err := tx.Model(suMoneyTransactionRecordModel).Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint").
ColumnExpr("su_money_transaction_record.employee->>'uid' AS uid").
ColumnExpr("su_money_transaction_record.employee->>'employeeName' AS employee_name").
ColumnExpr("sum(su_money_transaction_record.su_money) AS employee_su_money").
Where(`e.company_id = ?`, companyId).
//Where(`e.status = ?`, 1).
Where(`su_money_transaction_record.record_type IN (?)`, pg.In([]int{2, 3})). // 增加,任务奖励的
Where(`su_money_transaction_record.create_time > ?`, startTime).
Where(`su_money_transaction_record.create_time < ?`, endTime).
Group("su_money_transaction_record.employee").
Order("employee_su_money DESC").
Select(&ret); err != nil {
return nil, err
}
return map[string]interface{}{
"employeesSuMoney": ret,
}, nil
}
... ...
package dao
import (
"fmt"
"github.com/go-pg/pg"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
)
type ListIntervalDao struct {
transactionContext *pgTransaction.TransactionContext
}
// 榜单时间管理
func (dao *ListIntervalDao) RankPeriodCheckTime(startTime int64, endTime int64, idNot int, companyId int) bool {
fmt.Print(startTime, "\n")
fmt.Print(endTime, "\n")
var count int
tx := dao.transactionContext.PgTx
_, err := tx.QueryOne(
pg.Scan(&count),
`SELECT count(*) FROM list_intervals
WHERE id <> ?
AND company_id = ?
AND
(
( extract(epoch from list_interval_start_time) BETWEEN ? AND ?)
OR
( extract(epoch from list_interval_end_time) BETWEEN ? AND ?)
OR
(? BETWEEN extract(epoch from list_interval_start_time) AND extract(epoch from list_interval_end_time))
OR
(? BETWEEN extract(epoch from list_interval_start_time) AND extract(epoch from list_interval_end_time))
)
LIMIT 1 `,
idNot, companyId, startTime, endTime, startTime, endTime, startTime, endTime)
if err != nil {
fmt.Errorf(err.Error())
return false
}
if count > 0 {
fmt.Print(count, "\n")
return false
}
return true
}
func NewListIntervalDao(transactionContext *pgTransaction.TransactionContext) (*ListIntervalDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ListIntervalDao{
transactionContext: transactionContext,
}, nil
}
}
\ No newline at end of file
... ...
... ... @@ -14,6 +14,7 @@ type TaskDao struct {
transactionContext *pgTransaction.TransactionContext
}
// 返回接近截止时间任务
func (dao *TaskDao) ListNearThePlannedCompletionTimeTask() ([]*models.Task, error) {
tx := dao.transactionContext.PgTx
var taskModels []*models.Task
... ... @@ -31,6 +32,19 @@ func (dao *TaskDao) ListNearThePlannedCompletionTimeTask() ([]*models.Task, erro
}
}
// 更新已过期的竞标任务的状态,过期时间为竞标结束时间
func (dao *TaskDao) UpdateExpiredPlannedCompletionTimeBidTask() error {
currentTime := time.Now()
currentDay := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.Now().Location())
tx := dao.transactionContext.PgTx
_, err := tx.Query(
pg.Scan(),
"UPDATE tasks SET task_status = ? FROM bid_infos WHERE tasks.id = bid_infos.task_id AND bid_infos.bid_end_time < ? AND tasks.task_type = ? AND tasks.task_status = ?",
domain.TASK_STATUS_EXPIRED, currentDay, domain.TASK_TYPE_BID, domain.TASK_STATUS_UNCLAIMED)
return err
}
// 返回接近竞标截止时间的竞标任务
func (dao *TaskDao) ListNearBidEndTimeTask() ([]*models.Task, error) {
tx := dao.transactionContext.PgTx
var taskModels []*models.Task
... ... @@ -112,10 +126,12 @@ func (dao *TaskDao) CancelSuccessfulBidder(taskId int64) error {
return err
}
// 系统任务统计
func (dao *TaskDao) CalculateSystemTask(companyId int64) (map[string]interface{}, error) {
var released int64
var underway int64
var completed int64
var released int64 // 待领取的任务
var underway int64 // 进行中的任务
var completed int64 // 已完成任务
var reward int64 // 公司悬赏任务
tx := dao.transactionContext.PgTx
taskModel := new(models.Task)
if count, err := tx.Model(taskModel).
... ... @@ -137,19 +153,33 @@ func (dao *TaskDao) CalculateSystemTask(companyId int64) (map[string]interface{}
if count, err := tx.Model(taskModel).
Where("task.company_id = ?", companyId).
Where("task.task_status = ? ", domain.TASK_STATUS_COMPLETED).
//Where("task.task_status <> ? ", domain.TASK_STATUS_CLOSED).
//Where("task.task_status <> ? ", domain.TASK_STATUS_UNRELEASED).
Count(); err != nil {
return nil, err
} else {
completed = int64(count)
}
if count, err := tx.Model(taskModel).
Where("task.company_id = ?", companyId).
Where("task.task_status <> ? ", domain.TASK_STATUS_CLOSED).
Where("task.task_status <> ?", domain.TASK_STATUS_UNRELEASED).
Where("task.task_status = ?", domain.TASK_STATUS_UNCLAIMED).
Where("task.is_reward_take = ?", true).
Count(); err != nil {
return nil, err
} else {
reward = int64(count)
}
return map[string]interface{}{
"released": released + underway + completed,
"released": released,
"underway": underway,
"completed": completed,
"reward": reward,
}, nil
}
func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, error) {
func (dao *TaskDao) CalculatePersonTask(uid int64, companyId int) (map[string]interface{}, error) {
var underwayAsAssignedPerson int64
var unAcceptanceAsAssignedPerson int64
var completedAsAssignedPerson int64
... ... @@ -165,11 +195,13 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
var completedAsSponsor int64
var bidAsParticipator int64
var completedAsParticipator int64
var expiredAsSponsor int64
tx := dao.transactionContext.PgTx
taskModel := new(models.Task)
if count, err := tx.Model(taskModel).
Where(`task.assigned_person @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNDERWAY).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -178,6 +210,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.assigned_person @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNACCEPTANCE).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -186,6 +219,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.assigned_person @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_COMPLETED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -194,6 +228,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where("task.receiver_uid = ?", uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNCONFIRMED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -202,6 +237,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where("task.receiver_uid = ?", uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNDERWAY).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -210,6 +246,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where("task.receiver_uid = ?", uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNACCEPTANCE).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -218,6 +255,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where("task.receiver_uid = ?", uid).
Where("task.task_status = ? ", domain.TASK_STATUS_COMPLETED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -226,6 +264,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.sponsor @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNRELEASED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -234,6 +273,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.sponsor @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNCLAIMED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -242,6 +282,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.sponsor @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNCONFIRMED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -250,6 +291,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.sponsor @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNDERWAY).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -258,6 +300,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.sponsor @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNACCEPTANCE).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -266,6 +309,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.sponsor @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_COMPLETED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -274,6 +318,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).Join("JOIN bidder_infos AS bidder_info ON bidder_info.task_id = task.id").
Where(`bidder_info.bidder @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_UNCLAIMED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
... ... @@ -282,11 +327,21 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
if count, err := tx.Model(taskModel).
Where(`task.participators @> '[{"uid":?}]'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_COMPLETED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
completedAsParticipator = int64(count)
}
if count, err := tx.Model(taskModel).
Where(`task.sponsor @> '{"uid":?}'`, uid).
Where("task.task_status = ? ", domain.TASK_STATUS_EXPIRED).
Where("task.company_id = ?", companyId).
Count(); err != nil {
return nil, err
} else {
expiredAsSponsor = int64(count)
}
return map[string]interface{}{
"underwayAsAssignedPerson": underwayAsAssignedPerson,
"unAcceptanceAsAssignedPerson": unAcceptanceAsAssignedPerson,
... ... @@ -303,6 +358,7 @@ func (dao *TaskDao) CalculatePersonTask(uid int64) (map[string]interface{}, erro
"completedAsSponsor": completedAsSponsor,
"bidAsParticipator": bidAsParticipator,
"completedAsParticipator": completedAsParticipator,
"expiredAsSponsor": expiredAsSponsor,
}, nil
}
... ...
... ... @@ -2,6 +2,7 @@ package domain_service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
coreDomain "github.com/linmadan/egglib-go/core/domain"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
... ... @@ -16,10 +17,11 @@ type AcceptanceTaskService struct {
transactionContext *pgTransaction.TransactionContext
}
func (service *AcceptanceTaskService) Acceptance(taskId int64, operatorUid int64, participators []int64, taskPercentage []*domain.TaskPercentageItem, referenceResourceScore []*domain.ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) (*domain.Task, error) {
func (service *AcceptanceTaskService) Acceptance(taskId int64, operatorUid int64, participators []int64, suMoney float64, taskPercentage []*domain.TaskPercentageItem, referenceResourceScore []*domain.ReferenceResourceItem, solveReport string, solvePictureUrls []string, actualCompletionTime time.Time) (*domain.Task, error) {
var employeeRepository domain.EmployeeRepository
var taskRepository domain.TaskRepository
var suMoneyTransactionRecordRepository domain.SuMoneyTransactionRecordRepository
var employeeDao *dao.EmployeeDao
if repository, err := repository.NewEmployeeRepository(service.transactionContext); err != nil {
return nil, err
... ... @@ -36,23 +38,37 @@ func (service *AcceptanceTaskService) Acceptance(taskId int64, operatorUid int64
} else {
suMoneyTransactionRecordRepository = repository
}
if dao, err := dao.NewEmployeeDao(service.transactionContext); err != nil {
return nil, err
} else {
employeeDao = dao
}
operator, err := employeeRepository.FindOne(map[string]interface{}{
"uid": operatorUid,
"status": 1,
})
if err != nil {
return nil, err
}
if operator == nil {
return nil, fmt.Errorf("无效的操作者")
// 获取无效的发布人员信息
operatorInvalid, err := employeeRepository.FindOne(map[string]interface{}{
"uid": operatorUid,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if operatorInvalid == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的操作者")
}
return nil, fmt.Errorf("无效的操作者:" + operatorInvalid.EmployeeInfo.EmployeeName)
}
task, err := taskRepository.FindOne(map[string]interface{}{
"taskId": taskId,
})
if err != nil {
return nil, err
}
... ... @@ -64,17 +80,28 @@ func (service *AcceptanceTaskService) Acceptance(taskId int64, operatorUid int64
for _, participatorUid := range participators {
if participator, err := employeeRepository.FindOne(map[string]interface{}{
"uid": participatorUid,
"status": 1,
}); err != nil {
return nil, err
} else {
if participator == nil {
return nil, fmt.Errorf("无效的参与人")
// 获取无效的发布人员信息
participatorInvalid, err := employeeRepository.FindOne(map[string]interface{}{
"uid": participatorUid,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if participatorInvalid == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的参与人")
}
return nil, fmt.Errorf("无效的参与人:" + participatorInvalid.EmployeeInfo.EmployeeName)
}
participatorMap[participator.EmployeeInfo.Uid] = participator
participatorInfos = append(participatorInfos, participator.EmployeeInfo)
}
}
if err := task.Acceptance(participatorInfos, taskPercentage, referenceResourceScore, solveReport, solvePictureUrls, actualCompletionTime); err != nil {
if err := task.Acceptance(participatorInfos, suMoney, taskPercentage, referenceResourceScore, solveReport, solvePictureUrls, actualCompletionTime); err != nil {
return nil, err
}
for _, taskPercentageItem := range taskPercentage {
... ... @@ -93,12 +120,23 @@ func (service *AcceptanceTaskService) Acceptance(taskId int64, operatorUid int64
if taskPercentageItem.IsReceiver {
receiver, err := employeeRepository.FindOne(map[string]interface{}{
"uid": taskPercentageItem.Contributor.Uid,
"status": 1,
})
if err != nil {
return nil, err
}
if receiver == nil {
return nil, fmt.Errorf("无效的任务领取者")
// 获取无效的任务领取人员信息
receiverInvalid, err := employeeRepository.FindOne(map[string]interface{}{
"uid": operatorUid,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if receiverInvalid == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的任务领取者")
}
return nil, fmt.Errorf("无效的任务领取者:" + receiverInvalid.EmployeeInfo.EmployeeName)
}
employee = receiver
} else {
... ...
... ... @@ -18,22 +18,26 @@ type OperationSuMoneyService struct {
func (service *OperationSuMoneyService) Operation(uid int64, operatorUid int64, suMoney float64, operationType int, recordDescription string) (*domain.SuMoneyTransactionRecord, error) {
var employeeRepository domain.EmployeeRepository
var suMoneyTransactionRecordRepository domain.SuMoneyTransactionRecordRepository
var employeeDao *dao.EmployeeDao
if repository, err := repository.NewEmployeeRepository(service.transactionContext); err != nil {
return nil, err
} else {
employeeRepository = repository
}
if repository, err := repository.NewSuMoneyTransactionRecordRepository(service.transactionContext); err != nil {
return nil, err
} else {
suMoneyTransactionRecordRepository = repository
}
if dao, err := dao.NewEmployeeDao(service.transactionContext); err != nil {
return nil, err
} else {
employeeDao = dao
}
employee, err := employeeRepository.FindOne(map[string]interface{}{
"uid": uid,
})
... ... @@ -57,14 +61,31 @@ func (service *OperationSuMoneyService) Operation(uid int64, operatorUid int64,
}
var recordType int
var transferSuMoney float64
if operationType == 1 {
// 操作类型->记录类型对应:1->3: 增加 2->4: 扣除 3->1: 兑换物资 4->5: 兑换现金活动 41->6: 撤回兑换现金素币 5->2: 任务奖励
if operationType == 1 { // 增加
recordType = domain.SU_MONEY_TRANSACTION_RECORD_TYPE_INCREASE
transferSuMoney = suMoney
}
if operationType == 2 {
if operationType == 2 { // 扣除
recordType = domain.SU_MONEY_TRANSACTION_RECORD_TYPE_DEDUCT
transferSuMoney = 0 - suMoney
}
if operationType == 3 { // 兑换物资
recordType = domain.SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE
transferSuMoney = 0 - suMoney
}
if operationType == 4 { // 兑换现金
recordType = domain.SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE_CASH
transferSuMoney = 0 - suMoney
}
if operationType == 41 { // 兑换素币调整退回
recordType = domain.SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE_CASH_RESTORE
transferSuMoney = suMoney
}
if operationType == 5 { // 任务奖励
recordType = domain.SU_MONEY_TRANSACTION_RECORD_TYPE_AWARD
transferSuMoney = suMoney
}
suMoneyTransactionRecord := &domain.SuMoneyTransactionRecord{
RecordType: recordType,
Employee: employee.EmployeeInfo,
... ... @@ -73,7 +94,7 @@ func (service *OperationSuMoneyService) Operation(uid int64, operatorUid int64,
SuMoney: suMoney,
Operator: operator.EmployeeInfo,
RecordDescription: recordDescription,
CreateTime: time.Now(),
CreateTime: time.Now().Local(),
}
if err := employeeDao.TransferSuMoney(employee.EmployeeInfo.Uid, transferSuMoney); err != nil {
return nil, err
... ...
... ... @@ -31,12 +31,23 @@ func (service *ReleaseTaskService) Release(taskId int64, operatorUid int64) (*do
}
operator, err := employeeRepository.FindOne(map[string]interface{}{
"uid": operatorUid,
"status": 1,
})
if err != nil {
return nil, err
}
if operator == nil {
return nil, fmt.Errorf("无效的发布者")
// 获取无效的发布人员信息
operatorInvalid, err := employeeRepository.FindOne(map[string]interface{}{
"uid": operatorUid,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if operatorInvalid == nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "无效的发布者")
}
return nil, fmt.Errorf("无效的发布者:" + operatorInvalid.EmployeeInfo.EmployeeName)
}
task, err := taskRepository.FindOne(map[string]interface{}{
"taskId": taskId,
... ...
... ... @@ -36,6 +36,10 @@ func init() {
(*models.RejectTaskRecord)(nil),
(*models.Notification)(nil),
(*models.SentNotification)(nil),
(*models.CashPool)(nil),
(*models.ExchangeCashActivity)(nil),
(*models.ExchangeCashPersonList)(nil),
(*models.ListInterval)(nil),
} {
err := DB.CreateTable(model, &orm.CreateTableOptions{
Temp: false,
... ...
package models
import "time"
type CashPool struct {
TableName string `pg:"cash_pools,alias:cash_pool"`
Id int64 `pg:",pk"` // 现金池id
Cash float64 // 投入的现金
CompanyId int64 // 公司id
ExchangedCash float64 // 系统已兑换现金
UnExchangeCash float64 // 系统未兑换现金
ExchangedSuMoney float64 // 系统已兑换素币
UnExchangeSuMoney float64 // 系统未兑换素币
Rate float64 // 平均兑换汇率
LastRate float64 // 上期活动兑换汇率
CreateTime time.Time
}
... ...
package models
import "time"
type Employee struct {
TableName string `pg:"employees,alias:employee"`
// 员工ID
... ... @@ -22,4 +24,6 @@ type Employee struct {
Status int `pg:",notnull,default:1"`
// 员工权限集合
Permissions []int `pg:",array"`
// 创建时间
CreateTime time.Time
}
... ...
package models
import (
"time"
)
type ExchangeCashActivity struct {
TableName string `pg:"exchange_cash_activities,alias:exchange_cash_activity"`
Id int64 `pg:",pk"` // 兑换活动ID
CompanyId int64 // 公司ID
ActivityName string // 兑换活动名称
Deadline time.Time // 兑换活动结束时间
CountDown int64 // 兑换活动结束倒计时
ExchangedCash float64 // 已兑换现金
ExchangedSuMoney float64 // 已兑换素币
ExchangeRate float64 // 兑换汇率
//LastExchangeRate float64 // 上期活动兑换汇率
//ExchangeSuMoneyList []*domain.ExchangeCashPersonList `pg:",array"` // 素币兑换人员清单
//Sponsor *domain.EmployeeInfo // 活动发布人
CreateTime time.Time // 创建时间
}
\ No newline at end of file
... ...
package models
type ExchangeCashPersonList struct {
TableName string `pg:"exchange_cash_person_list,alias:exchange_cash_person_lists"`
Id int64 `pg:",pk"` // 清单id
ActivityId int64 // 兑换活动id
Uid int64 // 统一用户UID
EmployeeName string // 员工姓名
EmployeeAccount string // 员工账号
EmployeeAvatarUrl string // 员工头像URL
IsPrincipal bool `pg:",notnull,default:false"` // 是否公司负责人
ExchangedSuMoney float64 // 已兑换素币
ExchangedCash float64 // 已兑换现金
}
\ No newline at end of file
... ...
package models
import "time"
type ListInterval struct {
TableName string `pg:"list_interval,alias:list_intervals"`
Id int // 排行榜周期id
ListIntervalStartTime time.Time
ListIntervalEndTime time.Time
CompanyId int
}
... ...
... ... @@ -6,7 +6,7 @@ import (
)
type SuMoneyTransactionRecord struct {
TableName string `pg:"su_money_transaction_records,alias:su_money_transaction_record"`
TableName string `pg:",discard_unknown_columns,su_money_transaction_records,alias:su_money_transaction_record"`
// 素币事务记录ID
Id int64 `pg:",pk"`
// 记录类型
... ... @@ -19,6 +19,12 @@ type SuMoneyTransactionRecord struct {
CurrentSuMoney float64
// 事务素币值
SuMoney float64
//// 事务处理前现金值
//CashBeforeTransaction float64
//// 当前现金值
//CurrentCash float64
//// 事务现金值
//Cash float64
// 操作人
Operator *domain.EmployeeInfo
// 素币事务记录描述
... ...
... ... @@ -27,8 +27,12 @@ type Task struct {
CustomerValues []int `pg:",array"`
// 任务性质
TaskNature int
// 奖励素币
// 实际奖励素币
SuMoney float64
// 最小奖励素币
MinSuMoney float64
// 最大奖励素币
MaxSuMoney float64
// 验收标准
AcceptanceStandard string
// 任务描述
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg/models"
)
type CashPoolRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *CashPoolRepository) Save(cashPool *domain.CashPool) (*domain.CashPool, error) {
tx := repository.transactionContext.PgTx
fmt.Print(cashPool.Identity(), "\n")
if cashPool.Identity() == nil {
if _, err := tx.QueryOne(
pg.Scan(&cashPool.CashPoolId, &cashPool.Cash, &cashPool.CompanyId, &cashPool.ExchangedCash, &cashPool.UnExchangeCash, &cashPool.ExchangedSuMoney, &cashPool.UnExchangeSuMoney, &cashPool.Rate, &cashPool.LastRate, &cashPool.CreateTime),
"INSERT INTO cash_pools (cash, company_id, exchanged_cash, un_exchange_cash, exchanged_su_money, un_exchange_su_money, rate, last_rate, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, cash, company_id, exchanged_cash, un_exchange_cash, exchanged_su_money, un_exchange_su_money, rate, last_rate, create_time",
cashPool.Cash, cashPool.CompanyId, cashPool.ExchangedCash, cashPool.UnExchangeCash, cashPool.ExchangedSuMoney, cashPool.UnExchangeSuMoney, cashPool.Rate, cashPool.LastRate, cashPool.CreateTime); err != nil {
return cashPool, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(&cashPool.CashPoolId, &cashPool.Cash, &cashPool.CompanyId, &cashPool.ExchangedCash, &cashPool.UnExchangeCash, &cashPool.ExchangedSuMoney, &cashPool.UnExchangeSuMoney, &cashPool.Rate, &cashPool.LastRate),
"UPDATE cash_pools SET cash=?, company_id=?, exchanged_cash=?, un_exchange_cash=?, exchanged_su_money=?, un_exchange_su_money=?, rate=?, last_rate=? WHERE id=? RETURNING id, cash, company_id, exchanged_cash, un_exchange_cash, exchanged_su_money, un_exchange_su_money, rate, last_rate",
cashPool.Cash, cashPool.CompanyId, cashPool.ExchangedCash, cashPool.UnExchangeCash, cashPool.ExchangedSuMoney, cashPool.UnExchangeSuMoney, cashPool.Rate, cashPool.LastRate, cashPool.CashPoolId, cashPool.Identity()); err != nil {
return cashPool, err
}
}
return cashPool, nil
}
func (repository *CashPoolRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.CashPool, error) {
tx := repository.transactionContext.PgTx
var cashPoolModels []*models.CashPool
cashPools := make([]*domain.CashPool, 0)
query := tx.Model(&cashPoolModels)
// 根据公司id查找现金池
if companyId, ok := queryOptions["companyId"]; ok {
query = query.Where("cash_pool.company_id = ?", companyId)
}
if offset, ok := queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
query = query.Offset(offset)
}
} else {
query = query.Offset(0)
}
if limit, ok := queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
query = query.Limit(limit)
}
} else {
query = query.Limit(1)
}
if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
return 0, cashPools, err
} else {
for _, cashPoolModel := range cashPoolModels {
if cashPool, err := repository.transformPgModelToDomainModel(cashPoolModel); err != nil {
return 0, cashPools, err
} else {
cashPools = append(cashPools, cashPool)
}
}
return int64(count), cashPools, nil
}
}
func (repository *CashPoolRepository) FindOne(queryOptions map[string]interface{}) (*domain.CashPool, error) {
tx := repository.transactionContext.PgTx
cashPoolModel := new(models.CashPool)
query := tx.Model(cashPoolModel)
if companyId, ok := queryOptions["companyId"]; ok {
query = query.Where("cash_pool.company_id = ?", companyId)
}
//if cashPoolId, ok := queryOptions["cashPoolId"]; ok {
// query = query.Where("cash_pool.id = ?", cashPoolId)
//}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if cashPoolModel.Id == 0 {
return nil, nil
} else {
return repository.transformPgModelToDomainModel(cashPoolModel)
}
}
func (repository *CashPoolRepository) transformPgModelToDomainModel(cashPoolModel *models.CashPool) (*domain.CashPool, error) {
return &domain.CashPool{
CashPoolId: cashPoolModel.Id,
CompanyId: cashPoolModel.CompanyId,
Cash: cashPoolModel.Cash,
ExchangedCash: cashPoolModel.ExchangedCash,
UnExchangeCash: cashPoolModel.UnExchangeCash,
ExchangedSuMoney: cashPoolModel.ExchangedSuMoney,
UnExchangeSuMoney: cashPoolModel.UnExchangeSuMoney,
Rate: cashPoolModel.Rate,
LastRate: cashPoolModel.LastRate,
CreateTime: cashPoolModel.CreateTime,
}, nil
}
func NewCashPoolRepository(transactionContext *pgTransaction.TransactionContext) (*CashPoolRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为null")
} else {
return &CashPoolRepository{
transactionContext: transactionContext,
}, nil
}
}
\ No newline at end of file
... ...
... ... @@ -30,9 +30,9 @@ func (repository *EmployeeRepository) Save(employee *domain.Employee) (*domain.E
return employee, err
}
if _, err := tx.QueryOne(
pg.Scan(&employee.EmployeeId, &employee.CompanyId, &employee.EmployeeInfo.Uid, &employee.EmployeeInfo.EmployeeName, &employee.EmployeeInfo.EmployeeAccount, &employee.EmployeeInfo.EmployeeAvatarUrl, &employee.EmployeeInfo.IsPrincipal, &employee.SuMoney, &employee.Status, pg.Array(&employee.Permissions)),
"INSERT INTO employees (id, company_id, uid, employee_name, employee_account, employee_avatar_url, is_principal, su_money, status, permissions) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, company_id, uid, employee_name, employee_account, employee_avatar_url, is_principal, su_money, status, permissions",
employeeId, employee.CompanyId, employee.EmployeeInfo.Uid, employee.EmployeeInfo.EmployeeName, employee.EmployeeInfo.EmployeeAccount, employee.EmployeeInfo.EmployeeAvatarUrl, employee.EmployeeInfo.IsPrincipal, employee.SuMoney, employee.Status, pg.Array(employee.Permissions)); err != nil {
pg.Scan(&employee.EmployeeId, &employee.CompanyId, &employee.EmployeeInfo.Uid, &employee.EmployeeInfo.EmployeeName, &employee.EmployeeInfo.EmployeeAccount, &employee.EmployeeInfo.EmployeeAvatarUrl, &employee.EmployeeInfo.IsPrincipal, &employee.SuMoney, &employee.Status, pg.Array(&employee.Permissions), &employee.CreateTime),
"INSERT INTO employees (id, company_id, uid, employee_name, employee_account, employee_avatar_url, is_principal, su_money, status, permissions, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, company_id, uid, employee_name, employee_account, employee_avatar_url, is_principal, su_money, status, permissions, create_time",
employeeId, employee.CompanyId, employee.EmployeeInfo.Uid, employee.EmployeeInfo.EmployeeName, employee.EmployeeInfo.EmployeeAccount, employee.EmployeeInfo.EmployeeAvatarUrl, employee.EmployeeInfo.IsPrincipal, employee.SuMoney, employee.Status, pg.Array(employee.Permissions), employee.CreateTime); err != nil {
return employee, err
}
} else {
... ... @@ -63,9 +63,18 @@ func (repository *EmployeeRepository) FindOne(queryOptions map[string]interface{
if uid, ok := queryOptions["uid"]; ok {
query = query.Where("employee.uid = ?", uid)
}
if account, ok := queryOptions["account"]; ok {
query = query.Where("employee.employee_account = ?", account)
}
if companyId, ok := queryOptions["companyId"]; ok {
query = query.Where("employee.company_id = ?", companyId)
}
if status, ok := queryOptions["status"]; ok && status.(int) != 0 {
query = query.Where(`employee.status = ?`, status) // 筛除已离职员工
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此员工")
return nil, fmt.Errorf("无效的员工")
} else {
return nil, err
}
... ... @@ -77,6 +86,39 @@ func (repository *EmployeeRepository) FindOne(queryOptions map[string]interface{
}
}
func (repository *EmployeeRepository) FindByIds(queryOptions map[string]interface{}) (int64, []*domain.Employee, error) {
tx := repository.transactionContext.PgTx
var employeeModels []*models.Employee
employees := make([]*domain.Employee, 0)
query := tx.Model(&employeeModels)
if ids, ok := queryOptions["ids"]; ok && len(ids.([]int)) != 0 {
query = query.Where("employee.uid IN (?)", pg.In(ids.([]int)) )
}
if where, ok := queryOptions["where"]; ok && where.(map[string]interface{}) != nil {
if personNameMatch, ok := where.(map[string]interface{})["personNameMatch"]; ok && (personNameMatch != "") {
query = query.Where("employee.employee_name LIKE ?", fmt.Sprintf("%%%s%%", personNameMatch.(string)))
}
if companyId, ok := where.(map[string]interface{})["companyId"]; ok && companyId.(float64) != 0 {
query = query.Where("employee.company_id = ?", companyId)
}
}
if status, ok := queryOptions["status"]; ok && status.(int) != 0 {
query = query.Where(`employee.status = ?`, status)
}
if count, err := query.Order("uid DESC").SelectAndCount(); err != nil {
return 0, employees, err
} else {
for _, employeeModel := range employeeModels {
if employee, err := repository.transformPgModelToDomainModel(employeeModel); err != nil {
return 0, employees, err
} else {
employees = append(employees, employee)
}
}
return int64(count), employees, nil
}
}
func (repository *EmployeeRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Employee, error) {
tx := repository.transactionContext.PgTx
var employeeModels []*models.Employee
... ... @@ -88,7 +130,18 @@ func (repository *EmployeeRepository) Find(queryOptions map[string]interface{})
if employeeNameMatch, ok := queryOptions["employeeNameMatch"]; ok && (employeeNameMatch != "") {
query = query.Where("employee.employee_name LIKE ?", fmt.Sprintf("%%%s%%", employeeNameMatch.(string)))
}
if status, ok := queryOptions["status"]; ok && (status != 0) {
if ids, ok := queryOptions["ids"]; ok && len(ids.([]int)) != 0 {
query = query.Where("employee.uid IN (?)", pg.In(ids.([]int)) )
}
if where, ok := queryOptions["where"]; ok && where.(map[string]interface{}) != nil {
if personNameMatch, ok := where.(map[string]interface{})["personNameMatch"]; ok && (personNameMatch != "") {
query = query.Where("employee.employee_name LIKE ?", fmt.Sprintf("%%%s%%", personNameMatch.(string)))
}
if companyId, ok := where.(map[string]interface{})["companyId"]; ok && companyId.(float64) != 0 {
query = query.Where("employee.company_id = ?", companyId)
}
}
if status, ok := queryOptions["status"]; ok && status.(int) != 0 {
query = query.Where(`employee.status = ?`, status)
}
if isPrincipal, ok := queryOptions["isPrincipal"]; ok && isPrincipal.(bool) != false {
... ... @@ -124,6 +177,48 @@ func (repository *EmployeeRepository) Find(queryOptions map[string]interface{})
}
}
func (repository *EmployeeRepository) FindAll(queryOptions map[string]interface{}) (int64, []*domain.Employee, error) {
tx := repository.transactionContext.PgTx
var employeeModels []*models.Employee
employees := make([]*domain.Employee, 0)
query := tx.Model(&employeeModels)
if companyId, ok := queryOptions["companyId"]; ok {
query = query.Where("employee.company_id = ?", companyId)
}
if employeeNameMatch, ok := queryOptions["employeeNameMatch"]; ok && (employeeNameMatch != "") {
query = query.Where("employee.employee_name LIKE ?", fmt.Sprintf("%%%s%%", employeeNameMatch.(string)))
}
if ids, ok := queryOptions["ids"]; ok && len(ids.([]int)) != 0 {
query = query.Where("employee.uid IN (?)", pg.In(ids.([]int)) )
}
if where, ok := queryOptions["where"]; ok && where.(map[string]interface{}) != nil {
if personNameMatch, ok := where.(map[string]interface{})["personNameMatch"]; ok && (personNameMatch != "") {
query = query.Where("employee.employee_name LIKE ?", fmt.Sprintf("%%%s%%", personNameMatch.(string)))
}
if companyId, ok := where.(map[string]interface{})["companyId"]; ok && companyId.(float64) != 0 {
query = query.Where("employee.company_id = ?", companyId)
}
}
if status, ok := queryOptions["status"]; ok && status.(int) != 0 {
query = query.Where(`employee.status = ?`, status)
}
if isPrincipal, ok := queryOptions["isPrincipal"]; ok && isPrincipal.(bool) != false {
query = query.Where("employee.is_principal = ? ", isPrincipal)
}
if count, err := query.Order("uid DESC").SelectAndCount(); err != nil {
return 0, employees, err
} else {
for _, employeeModel := range employeeModels {
if employee, err := repository.transformPgModelToDomainModel(employeeModel); err != nil {
return 0, employees, err
} else {
employees = append(employees, employee)
}
}
return int64(count), employees, nil
}
}
func (repository *EmployeeRepository) transformPgModelToDomainModel(employeeModel *models.Employee) (*domain.Employee, error) {
return &domain.Employee{
EmployeeId: employeeModel.Id,
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg/models"
"time"
)
type ExchangeCashActivityRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *ExchangeCashActivityRepository) Save(exchangeCashActivity *domain.ExchangeCashActivity) (*domain.ExchangeCashActivity, error) {
tx := repository.transactionContext.PgTx
if exchangeCashActivity.Identity() == nil {
if _, err := tx.QueryOne(
pg.Scan(&exchangeCashActivity.ActivityId, &exchangeCashActivity.CompanyId, &exchangeCashActivity.ExchangeActivityName, &exchangeCashActivity.Deadline, &exchangeCashActivity.CountDown, &exchangeCashActivity.ExchangedCash, &exchangeCashActivity.ExchangedSuMoney, &exchangeCashActivity.Rate, &exchangeCashActivity.CreateTime),
"INSERT INTO exchange_cash_activities ( company_id, activity_name, deadline, count_down, exchanged_cash, exchanged_su_money, exchange_rate, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, company_id, activity_name, deadline, count_down, exchanged_cash, exchanged_su_money, exchange_rate, create_time" ,
exchangeCashActivity.CompanyId, exchangeCashActivity.ExchangeActivityName, exchangeCashActivity.Deadline, exchangeCashActivity.CountDown, exchangeCashActivity.ExchangedCash, exchangeCashActivity.ExchangedSuMoney, exchangeCashActivity.Rate, &exchangeCashActivity.CreateTime); err != nil {
return exchangeCashActivity, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(&exchangeCashActivity.ActivityId, &exchangeCashActivity.CompanyId, &exchangeCashActivity.ExchangeActivityName, &exchangeCashActivity.Deadline, &exchangeCashActivity.CountDown, &exchangeCashActivity.ExchangedCash, &exchangeCashActivity.ExchangedSuMoney, &exchangeCashActivity.Rate),
"UPDATE exchange_cash_activities SET activity_name=?, deadline=?, count_down=?, exchanged_cash=?, exchanged_su_money=?, exchange_rate=? WHERE id=? RETURNING id, company_id, activity_name, deadline, count_down, exchanged_cash, exchanged_su_money, exchange_rate",
exchangeCashActivity.ExchangeActivityName, exchangeCashActivity.Deadline, exchangeCashActivity.CountDown, exchangeCashActivity.ExchangedCash, exchangeCashActivity.ExchangedSuMoney, exchangeCashActivity.Rate, exchangeCashActivity.ActivityId); err != nil {
return exchangeCashActivity, err
}
}
return exchangeCashActivity, nil
}
func (repository *ExchangeCashActivityRepository) FindOne(queryOptions map[string]interface{}) (*domain.ExchangeCashActivity, error) {
tx := repository.transactionContext.PgTx
exchangeCashActivityModel := new(models.ExchangeCashActivity)
query := tx.Model(exchangeCashActivityModel)
if exchangeCashActivityId, ok := queryOptions["activityId"]; ok {
query = query.Where("exchange_cash_activity.id = ?", exchangeCashActivityId)
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if exchangeCashActivityModel.Id == 0 {
return nil, nil
} else {
return repository.transformPgModelToDomainModel(exchangeCashActivityModel)
}
}
func (repository *ExchangeCashActivityRepository) FindAll(queryOptions map[string]interface{}) (int64, []*domain.ExchangeCashActivity, error) {
tx := repository.transactionContext.PgTx
var exchangeCashActivityModels []*models.ExchangeCashActivity
exchangeCashActivities := make([]*domain.ExchangeCashActivity, 0)
query := tx.Model(&exchangeCashActivityModels)
if companyId, ok := queryOptions["companyId"]; ok {
query = query.Where(`exchange_cash_activity.company_id = ?`, companyId)
}
if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
return 0, exchangeCashActivities, err
} else {
for _, exchangeCashActivityModel := range exchangeCashActivityModels {
if taskNature, err := repository.transformPgModelToDomainModel(exchangeCashActivityModel); err != nil {
return 0, exchangeCashActivities, err
} else {
exchangeCashActivities = append(exchangeCashActivities, taskNature)
}
}
return int64(count), exchangeCashActivities, nil
}
}
func (repository *ExchangeCashActivityRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ExchangeCashActivity, error) {
tx := repository.transactionContext.PgTx
var exchangeCashActivityModels []*models.ExchangeCashActivity
exchangeCashActivities := make([]*domain.ExchangeCashActivity, 0)
query := tx.Model(&exchangeCashActivityModels)
//fmt.Printf("查询:%+v\n", queryOptions)
if companyId, ok := queryOptions["companyId"]; ok {
query = query.Where(`exchange_cash_activity.company_id = ?`, companyId)
}
if activityNameMatch, ok := queryOptions["activityNameMatch"]; ok && (activityNameMatch != "") {
query = query.Where(`exchange_cash_activity.activity_name LIKE ?`, fmt.Sprintf("%%%s%%", activityNameMatch.(string)))
}
if countDown, ok := queryOptions["countDown"]; ok {
query = query.Where(`exchange_cash_activity.count_down = ?`, countDown)
}
if isEnd, ok := queryOptions["isEnd"]; ok {
if isEnd.(bool) {
query = query.Where(`exchange_cash_activity.count_down = ?`, 0)
} else {
query = query.Where(`exchange_cash_activity.count_down > ?`, 0)
}
}
if nearest, ok := queryOptions["nearest"]; ok && nearest.(bool) != false {
t := time.Now().Local()
query = query.Where(`exchange_cash_activity.deadline <= ?`, t)
query = query.Where(`exchange_cash_activity.count_down = ?`, 0)
}
if deadline, ok := queryOptions["deadline"]; ok && deadline != "" {
t, _ := time.ParseInLocation("2006-01-02", deadline.(string), time.Local)
newDeadlineStart := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
newDeadlineEnd := time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, time.Local)
query = query.Where(`exchange_cash_activity.deadline >= ?`, newDeadlineStart)
query = query.Where(`exchange_cash_activity.deadline <= ?`, newDeadlineEnd)
}
if offset, ok := queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
query = query.Offset(offset)
}
} else {
query = query.Offset(0)
}
if limit, ok := queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
query = query.Limit(limit)
}
} else {
query = query.Limit(20)
}
if order, ok := queryOptions["order"]; ok && order.(string) != "" {
if count, err := query.OrderExpr("deadline DESC").SelectAndCount(); err != nil {
return 0, exchangeCashActivities, err
} else {
for _, exchangeCashActivityModel := range exchangeCashActivityModels {
if taskNature, err := repository.transformPgModelToDomainModel(exchangeCashActivityModel); err != nil {
return 0, exchangeCashActivities, err
} else {
exchangeCashActivities = append(exchangeCashActivities, taskNature)
}
}
return int64(count), exchangeCashActivities, nil
}
}
if count, err := query.OrderExpr("deadline ASC").SelectAndCount(); err != nil {
return 0, exchangeCashActivities, err
} else {
for _, exchangeCashActivityModel := range exchangeCashActivityModels {
if taskNature, err := repository.transformPgModelToDomainModel(exchangeCashActivityModel); err != nil {
return 0, exchangeCashActivities, err
} else {
exchangeCashActivities = append(exchangeCashActivities, taskNature)
}
}
return int64(count), exchangeCashActivities, nil
}
}
func (repository *ExchangeCashActivityRepository) Remove(exchangeCashActivity *domain.ExchangeCashActivity) (*domain.ExchangeCashActivity, error) {
tx := repository.transactionContext.PgTx
exchangeCashActivityModel := new(models.ExchangeCashActivity)
exchangeCashActivityModel.Id = exchangeCashActivity.ActivityId
if _, err := tx.Model(exchangeCashActivityModel).WherePK().Delete(); err != nil {
return exchangeCashActivity, err
}
return exchangeCashActivity, nil
}
func (repository *ExchangeCashActivityRepository) transformPgModelToDomainModel(exchangeCashActivity *models.ExchangeCashActivity) (*domain.ExchangeCashActivity, error) {
return &domain.ExchangeCashActivity{
ActivityId: exchangeCashActivity.Id,
ExchangeActivityName: exchangeCashActivity.ActivityName,
CompanyId: exchangeCashActivity.CompanyId,
ExchangedCash: exchangeCashActivity.ExchangedCash,
ExchangedSuMoney: exchangeCashActivity.ExchangedSuMoney,
CreateTime: exchangeCashActivity.CreateTime,
Deadline: exchangeCashActivity.Deadline,
CountDown: exchangeCashActivity.CountDown,
Rate: exchangeCashActivity.ExchangeRate,
}, nil
}
func NewExchangeCashActivityRepository(transactionContext *pgTransaction.TransactionContext) (*ExchangeCashActivityRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ExchangeCashActivityRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"strconv"
"github.com/go-pg/pg"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg/models"
)
type ExchangeCashPersonListRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *ExchangeCashPersonListRepository) Save(exchangeCashList *domain.ExchangeCashPersonList) (*domain.ExchangeCashPersonList, error) {
tx := repository.transactionContext.PgTx
if exchangeCashList.Identity() == nil {
if _, err := tx.QueryOne(
pg.Scan(&exchangeCashList.ListId, &exchangeCashList.ExchangeCashActivityId, &exchangeCashList.EmployeeInfo.Uid, &exchangeCashList.EmployeeInfo.EmployeeName, &exchangeCashList.EmployeeInfo.EmployeeAccount, &exchangeCashList.ExchangedSuMoney, &exchangeCashList.ExchangedCash),
"INSERT INTO exchange_cash_person_lists (activity_id, uid, employee_name, employee_account, exchanged_su_money, exchanged_cash) VALUES (?, ?, ?, ?, ?, ?) RETURNING id, activity_id, uid, employee_name, employee_account, exchanged_su_money, exchanged_cash",
exchangeCashList.ExchangeCashActivityId, exchangeCashList.EmployeeInfo.Uid, exchangeCashList.EmployeeInfo.EmployeeName, exchangeCashList.EmployeeInfo.EmployeeAccount, exchangeCashList.ExchangedSuMoney, exchangeCashList.ExchangedCash); err != nil {
return exchangeCashList, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(&exchangeCashList.ListId, &exchangeCashList.ExchangeCashActivityId, &exchangeCashList.EmployeeInfo.Uid, &exchangeCashList.EmployeeInfo.EmployeeName, &exchangeCashList.EmployeeInfo.EmployeeAccount, &exchangeCashList.ExchangedSuMoney, &exchangeCashList.ExchangedCash),
"UPDATE exchange_cash_person_lists SET exchanged_su_money=?, exchanged_cash=? WHERE id=? RETURNING id, activity_id, uid, employee_name, employee_account, exchanged_su_money, exchanged_cash",
exchangeCashList.ExchangedSuMoney, exchangeCashList.ExchangedCash, exchangeCashList.ListId); err != nil {
return exchangeCashList, err
}
}
return exchangeCashList, nil
}
func (repository *ExchangeCashPersonListRepository) FindOne(queryOptions map[string]interface{}) (*domain.ExchangeCashPersonList, error) {
tx := repository.transactionContext.PgTx
exchangeCashListModel := new(models.ExchangeCashPersonList)
query := tx.Model(exchangeCashListModel)
if uid, ok := queryOptions["uid"]; ok {
query = query.Where("exchange_cash_person_list.uid = ?", uid)
}
if exchangeCashListId, ok := queryOptions["listId"]; ok {
query = query.Where("exchange_cash_person_list.id = ?", exchangeCashListId)
}
if activityId, ok := queryOptions["activityId"]; ok {
query = query.Where("exchange_cash_person_list.activity_id = ?", activityId)
}
if employeeAccount, ok := queryOptions["employeeAccount"]; ok {
query = query.Where("exchange_cash_person_list.employee_account = ?", employeeAccount)
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if exchangeCashListModel.Id == 0 {
return nil, nil
} else {
return repository.transformPgModelToDomainModel(exchangeCashListModel)
}
}
func (repository *ExchangeCashPersonListRepository) FindById(queryOptions map[string]interface{}) (int64, []*domain.ExchangeCashPersonList, error) {
tx := repository.transactionContext.PgTx
var exchangeCashListModels []*models.ExchangeCashPersonList
exchangeCashPeople := make([]*domain.ExchangeCashPersonList, 0)
query := tx.Model(&exchangeCashListModels)
if ids, ok := queryOptions["ids"]; ok && len(ids.([]int)) != 0 {
query = query.Where("exchange_cash_person_list.id IN (?)", pg.In(ids.([]int)) )
}
if where, ok := queryOptions["where"]; ok && where.(map[string]interface{}) != nil {
if personNameMatch, ok := where.(map[string]interface{})["personNameMatch"]; ok && (personNameMatch != "") {
query = query.Where(`exchange_cash_person_list.employee_name LIKE ?`, fmt.Sprintf("%%%s%%", personNameMatch.(string)))
}
if activityId, ok := where.(map[string]interface{})["activityId"]; ok && activityId != "" {
float, _ := strconv.ParseFloat(activityId.(string),64)
query = query.Where("exchange_cash_person_list.activity_id = ?", float)
}
}
if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
return 0, exchangeCashPeople, err
} else {
for _, exchangeCashListModel := range exchangeCashListModels {
if taskNature, err := repository.transformPgModelToDomainModel(exchangeCashListModel); err != nil {
return 0, exchangeCashPeople, err
} else {
exchangeCashPeople = append(exchangeCashPeople, taskNature)
}
}
return int64(count), exchangeCashPeople, nil
}
}
// 获取平台所有兑换活动清单(兑换现金活动总清单)
func (repository *ExchangeCashPersonListRepository) FindAll(queryOptions map[string]interface{}) (int64, []*domain.ExchangeCashPersonList, error) {
tx := repository.transactionContext.PgTx
var exchangeCashListModels []*models.ExchangeCashPersonList
exchangeCashPeople := make([]*domain.ExchangeCashPersonList, 0)
query := tx.Model(&exchangeCashListModels)
if exchangeCashActivityIds, ok := queryOptions["exchangeCashActivityIds"]; ok && len(exchangeCashActivityIds.([]int64)) != 0 {
query = query.Where("exchange_cash_person_list.activity_id IN (?)", pg.In(exchangeCashActivityIds.([]int64)) )
}
if offset, ok := queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
query = query.Offset(offset)
}
} else {
query = query.Offset(0)
}
if limit, ok := queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
query = query.Limit(limit)
}
} else {
query = query.Limit(20)
}
if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
return 0, exchangeCashPeople, err
} else {
for _, exchangeCashListModel := range exchangeCashListModels {
if taskNature, err := repository.transformPgModelToDomainModel(exchangeCashListModel); err != nil {
return 0, exchangeCashPeople, err
} else {
exchangeCashPeople = append(exchangeCashPeople, taskNature)
}
}
return int64(count), exchangeCashPeople, nil
}
}
func (repository *ExchangeCashPersonListRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ExchangeCashPersonList, error) {
tx := repository.transactionContext.PgTx
var exchangeCashListModels []*models.ExchangeCashPersonList
exchangeCashPeople := make([]*domain.ExchangeCashPersonList, 0)
query := tx.Model(&exchangeCashListModels)
if exchangeCashActivityId, ok := queryOptions["exchangeCashActivityId"]; ok {
query = query.Where("exchange_cash_person_list.activity_id = ?", exchangeCashActivityId)
}
if personNameMatch, ok := queryOptions["exchangeCashPersonNameMatch"]; ok && (personNameMatch != ""){
query = query.Where("exchange_cash_person_list.employee_name LIKE ?", fmt.Sprintf("%%%s%%", personNameMatch.(string)))
}
if employeeAccount, ok := queryOptions["employeeAccount"]; ok && (employeeAccount != "") {
query = query.Where("exchange_cash_person_list.employee_account =?", employeeAccount)
}
if uid, ok := queryOptions["uid"]; ok {
query = query.Where("exchange_cash_person_list.uid = ?", uid)
}
if offset, ok := queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
query = query.Offset(offset)
}
} else {
query = query.Offset(0)
}
if limit, ok := queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
query = query.Limit(limit)
}
} else {
query = query.Limit(20)
}
if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
return 0, exchangeCashPeople, err
} else {
for _, exchangeCashListModel := range exchangeCashListModels {
if taskNature, err := repository.transformPgModelToDomainModel(exchangeCashListModel); err != nil {
return 0, exchangeCashPeople, err
} else {
exchangeCashPeople = append(exchangeCashPeople, taskNature)
}
}
return int64(count), exchangeCashPeople, nil
}
}
func (repository *ExchangeCashPersonListRepository) Remove(exchangeCashList *domain.ExchangeCashPersonList) (*domain.ExchangeCashPersonList, error) {
tx := repository.transactionContext.PgTx
exchangeCashListModel := new(models.ExchangeCashPersonList)
exchangeCashListModel.Id = exchangeCashList.ListId
if _, err := tx.Model(exchangeCashListModel).WherePK().Delete(); err != nil {
return exchangeCashList, err
}
return exchangeCashList, nil
}
func (repository *ExchangeCashPersonListRepository) transformPgModelToDomainModel(exchangeCashList *models.ExchangeCashPersonList) (*domain.ExchangeCashPersonList, error) {
return &domain.ExchangeCashPersonList{
ExchangedCash: exchangeCashList.ExchangedCash,
ExchangedSuMoney: exchangeCashList.ExchangedSuMoney,
ListId: exchangeCashList.Id,
ExchangeCashActivityId: exchangeCashList.ActivityId,
EmployeeInfo: &domain.EmployeeInfo{
Uid: exchangeCashList.Uid,
EmployeeName: exchangeCashList.EmployeeName,
EmployeeAccount: exchangeCashList.EmployeeAccount,
EmployeeAvatarUrl: exchangeCashList.EmployeeAvatarUrl,
IsPrincipal: exchangeCashList.IsPrincipal,
},
}, nil
}
func NewExchangeCashPersonListRepository(transactionContext *pgTransaction.TransactionContext) (*ExchangeCashPersonListRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ExchangeCashPersonListRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg/models"
)
type ListIntervalRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *ListIntervalRepository) Save(listInterval *domain.ListInterval) (*domain.ListInterval, error) {
tx := repository.transactionContext.PgTx
if listInterval.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(&listInterval.ListIntervalId, &listInterval.CompanyId, &listInterval.IntervalStartTime, &listInterval.IntervalEndTime),
"INSERT INTO list_intervals (list_interval_start_time, list_interval_end_time, company_id) VALUES (?, ?, ?) RETURNING id, company_id, list_interval_start_time, list_interval_end_time",
listInterval.IntervalStartTime, listInterval.IntervalEndTime, listInterval.CompanyId); err != nil {
return listInterval, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(&listInterval.ListIntervalId, &listInterval.CompanyId, &listInterval.IntervalStartTime, &listInterval.IntervalEndTime),
"UPDATE list_intervals SET list_interval_start_time=?, list_interval_end_time=? WHERE id=? RETURNING id, company_id, list_interval_start_time, list_interval_end_time",
listInterval.IntervalStartTime, listInterval.IntervalEndTime, listInterval.Identify()); err != nil {
return listInterval, err
}
}
return listInterval, nil
}
func (repository *ListIntervalRepository) Remove(listInterval *domain.ListInterval) (*domain.ListInterval, error) {
tx := repository.transactionContext.PgTx
listIntervalModel := new(models.ListInterval)
listIntervalModel.Id = listInterval.Identify().(int)
if _, err := tx.Model(listIntervalModel).WherePK().Delete(); err != nil {
return listInterval, err
}
return listInterval, nil
}
func (repository *ListIntervalRepository) FindOne(queryOptions map[string]interface{}) (*domain.ListInterval, error) {
tx := repository.transactionContext.PgTx
listIntervalModel := new(models.ListInterval)
query := tx.Model(listIntervalModel)
if listIntervalId, ok := queryOptions["listId"]; ok {
query = query.Where("list_interval.id = ?", listIntervalId)
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if listIntervalModel.Id == 0 {
return nil, nil
} else {
return repository.transformPgModelToDomainModel(listIntervalModel)
}
}
func (repository *ListIntervalRepository) FindAll(queryOptions map[string]interface{}) (int64, []*domain.ListInterval, error) {
tx := repository.transactionContext.PgTx
var listIntervalModels []*models.ListInterval
listIntervals := make([]*domain.ListInterval, 0)
query := tx.Model(&listIntervalModels)
if companyId, ok := queryOptions["companyId"]; ok {
query = query.Where("list_interval.company_id = ?", companyId)
}
if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
return 0, listIntervals, err
} else {
for _, listIntervalModel := range listIntervalModels {
if listInterval, err := repository.transformPgModelToDomainModel(listIntervalModel); err != nil {
return 0, listIntervals, err
} else {
listIntervals = append(listIntervals, listInterval)
}
}
return int64(count), listIntervals, nil
}
}
func (repository *ListIntervalRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ListInterval, error) {
tx := repository.transactionContext.PgTx
var listIntervalModels []*models.ListInterval
listIntervals := make([]*domain.ListInterval, 0)
query := tx.Model(&listIntervalModels)
if companyId, ok := queryOptions["companyId"]; ok {
query = query.Where("list_interval.company_id = ?", companyId)
}
if offset, ok := queryOptions["offset"]; ok {
offset := offset.(int)
if offset > -1 {
query = query.Offset(offset)
}
} else {
query = query.Offset(0)
}
if limit, ok := queryOptions["limit"]; ok {
limit := limit.(int)
if limit > -1 {
query = query.Limit(limit)
}
} else {
query = query.Limit(20)
}
if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
return 0, listIntervals, err
} else {
for _, listIntervalModel := range listIntervalModels {
if listInterval, err := repository.transformPgModelToDomainModel(listIntervalModel); err != nil {
return 0, listIntervals, err
} else {
listIntervals = append(listIntervals, listInterval)
}
}
return int64(count), listIntervals, nil
}
}
func (repository *ListIntervalRepository) transformPgModelToDomainModel(listIntervalModel *models.ListInterval) (*domain.ListInterval, error) {
return &domain.ListInterval{
ListIntervalId: listIntervalModel.Id,
CompanyId: listIntervalModel.CompanyId,
IntervalStartTime: listIntervalModel.ListIntervalStartTime,
IntervalEndTime: listIntervalModel.ListIntervalEndTime,
}, nil
}
func NewListIntervalRepository(transactionContext *pgTransaction.TransactionContext) (*ListIntervalRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ListIntervalRepository{
transactionContext: transactionContext,
}, nil
}
}
\ No newline at end of file
... ...
... ... @@ -33,6 +33,7 @@ func (repository *SuMoneyTransactionRecordRepository) Save(suMoneyTransactionRec
}
return suMoneyTransactionRecord, nil
}
func (repository *SuMoneyTransactionRecordRepository) Remove(suMoneyTransactionRecord *domain.SuMoneyTransactionRecord) (*domain.SuMoneyTransactionRecord, error) {
tx := repository.transactionContext.PgTx
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
... ... @@ -42,6 +43,7 @@ func (repository *SuMoneyTransactionRecordRepository) Remove(suMoneyTransactionR
}
return suMoneyTransactionRecord, nil
}
func (repository *SuMoneyTransactionRecordRepository) FindOne(queryOptions map[string]interface{}) (*domain.SuMoneyTransactionRecord, error) {
tx := repository.transactionContext.PgTx
suMoneyTransactionRecordModel := new(models.SuMoneyTransactionRecord)
... ... @@ -62,6 +64,36 @@ func (repository *SuMoneyTransactionRecordRepository) FindOne(queryOptions map[s
return repository.transformPgModelToDomainModel(suMoneyTransactionRecordModel)
}
}
func (repository *SuMoneyTransactionRecordRepository) FindById(queryOptions map[string]interface{}) (int64, []*domain.SuMoneyTransactionRecord, error) {
tx := repository.transactionContext.PgTx
var suMoneyTransactionRecordModels []*models.SuMoneyTransactionRecord
suMoneyTransactionRecords := make([]*domain.SuMoneyTransactionRecord, 0)
query := tx.Model(&suMoneyTransactionRecordModels)
//query = query.Join("JOIN employees AS e ON e.uid = (su_money_transaction_record.employee->>'uid')::bigint")
if iDs, ok := queryOptions["ids"]; ok && len(iDs.([]int)) != 0 {
query = query.Where(`su_money_transaction_record.id IN (?)`, pg.In(iDs.([]int)))
}
if where, ok := queryOptions["where"]; ok && where.(map[string]interface{}) != nil {
if uid, ok := where.(map[string]interface{})["uid"]; ok && (uid != int64(0)) {
query = query.Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid)
}
}
//query = query.Where(`e.status = ?`, 1)
if count, err := query.Order("id DESC").SelectAndCount(); err != nil {
return 0, suMoneyTransactionRecords, err
} else {
for _, suMoneyTransactionRecordModel := range suMoneyTransactionRecordModels {
if suMoneyTransactionRecord, err := repository.transformPgModelToDomainModel(suMoneyTransactionRecordModel); err != nil {
return 0, suMoneyTransactionRecords, err
} else {
suMoneyTransactionRecords = append(suMoneyTransactionRecords, suMoneyTransactionRecord)
}
}
return int64(count), suMoneyTransactionRecords, nil
}
}
func (repository *SuMoneyTransactionRecordRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.SuMoneyTransactionRecord, error) {
tx := repository.transactionContext.PgTx
var suMoneyTransactionRecordModels []*models.SuMoneyTransactionRecord
... ... @@ -70,6 +102,9 @@ func (repository *SuMoneyTransactionRecordRepository) Find(queryOptions map[stri
if uid, ok := queryOptions["uid"]; ok && (uid != int64(0)) {
query = query.Where(`su_money_transaction_record.employee @> '{"uid":?}'`, uid)
}
if employeeMatchName, ok := queryOptions["employeeMatchName"]; ok && (employeeMatchName != "") {
query = query.Where(`(su_money_transaction_record.employee->>'employeeName')::text LIKE ?`, fmt.Sprintf("%%%s%%", employeeMatchName.(string)))
}
if recordType, ok := queryOptions["recordType"]; ok && (recordType != 0) {
query = query.Where(`su_money_transaction_record.record_type = ?`, recordType)
}
... ... @@ -114,6 +149,7 @@ func (repository *SuMoneyTransactionRecordRepository) Find(queryOptions map[stri
return int64(count), suMoneyTransactionRecords, nil
}
}
func (repository *SuMoneyTransactionRecordRepository) transformPgModelToDomainModel(suMoneyTransactionRecordModel *models.SuMoneyTransactionRecord) (*domain.SuMoneyTransactionRecord, error) {
return &domain.SuMoneyTransactionRecord{
SuMoneyTransactionRecordId: suMoneyTransactionRecordModel.Id,
... ... @@ -127,6 +163,7 @@ func (repository *SuMoneyTransactionRecordRepository) transformPgModelToDomainMo
CreateTime: suMoneyTransactionRecordModel.CreateTime,
}, nil
}
func NewSuMoneyTransactionRecordRepository(transactionContext *pgTransaction.TransactionContext) (*SuMoneyTransactionRecordRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
... ... @@ -32,6 +32,7 @@ func (repository *TaskNatureRepository) Save(taskNature *domain.TaskNature) (*do
}
return taskNature, nil
}
func (repository *TaskNatureRepository) Remove(taskNature *domain.TaskNature) (*domain.TaskNature, error) {
tx := repository.transactionContext.PgTx
taskNatureModel := new(models.TaskNature)
... ... @@ -41,6 +42,7 @@ func (repository *TaskNatureRepository) Remove(taskNature *domain.TaskNature) (*
}
return taskNature, nil
}
func (repository *TaskNatureRepository) FindOne(queryOptions map[string]interface{}) (*domain.TaskNature, error) {
tx := repository.transactionContext.PgTx
taskNatureModel := new(models.TaskNature)
... ... @@ -61,6 +63,7 @@ func (repository *TaskNatureRepository) FindOne(queryOptions map[string]interfac
return repository.transformPgModelToDomainModel(taskNatureModel)
}
}
func (repository *TaskNatureRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.TaskNature, error) {
tx := repository.transactionContext.PgTx
var taskNatureModels []*models.TaskNature
... ... @@ -104,6 +107,7 @@ func (repository *TaskNatureRepository) Find(queryOptions map[string]interface{}
return int64(count), taskNatures, nil
}
}
func (repository *TaskNatureRepository) transformPgModelToDomainModel(taskNatureModel *models.TaskNature) (*domain.TaskNature, error) {
return &domain.TaskNature{
TaskNatureId: taskNatureModel.Id,
... ... @@ -111,6 +115,7 @@ func (repository *TaskNatureRepository) transformPgModelToDomainModel(taskNature
CompanyId: taskNatureModel.CompanyId,
}, nil
}
func NewTaskNatureRepository(transactionContext *pgTransaction.TransactionContext) (*TaskNatureRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
... ... @@ -32,9 +32,9 @@ func (repository *TaskRepository) Save(task *domain.Task) (*domain.Task, error)
return task, err
}
if _, err := tx.QueryOne(
pg.Scan(&task.TaskId, &task.CompanyId, &task.TaskName, &task.TaskType, &task.Sponsor, &task.TaskStatus, &task.ReferenceResource, &task.ProjectBelong, pg.Array(&task.CustomerValues), &task.TaskNature, &task.SuMoney, &task.AcceptanceStandard, &task.TaskDescription, pg.Array(&task.TaskPictureUrls), &task.IsRewardTake, &task.CreateTime, &task.ReleaseTime, &task.Participators, &task.TaskPercentage, &task.SolveReport, pg.Array(&task.SolvePictureUrls), &task.AssignedPerson, &task.PlannedCompletionTime, &task.ActualCompletionTime),
"INSERT INTO tasks (id, company_id, task_name, task_type, sponsor, task_status, reference_resource, project_belong, customer_values, task_nature, su_money, acceptance_standard, task_description, task_picture_urls, is_reward_take, create_time, release_time, participators, task_percentage, solve_report, solve_picture_urls, assigned_person, planned_completion_time, actual_completion_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, company_id, task_name, task_type, sponsor, task_status, reference_resource, project_belong, customer_values, task_nature, su_money, acceptance_standard, task_description, task_picture_urls, is_reward_take, create_time, release_time, participators, task_percentage, solve_report, solve_picture_urls, assigned_person, planned_completion_time, actual_completion_time",
takeId, task.CompanyId, task.TaskName, task.TaskType, task.Sponsor, task.TaskStatus, task.ReferenceResource, task.ProjectBelong, pg.Array(task.CustomerValues), task.TaskNature, task.SuMoney, task.AcceptanceStandard, task.TaskDescription, pg.Array(task.TaskPictureUrls), task.IsRewardTake, task.CreateTime, task.ReleaseTime, task.Participators, task.TaskPercentage, task.SolveReport, pg.Array(task.SolvePictureUrls), task.AssignedPerson, task.PlannedCompletionTime, task.ActualCompletionTime); err != nil {
pg.Scan(&task.TaskId, &task.CompanyId, &task.TaskName, &task.TaskType, &task.Sponsor, &task.TaskStatus, &task.ReferenceResource, &task.ProjectBelong, pg.Array(&task.CustomerValues), &task.TaskNature, &task.SuMoney, &task.MinSuMoney, &task.MaxSuMoney, &task.AcceptanceStandard, &task.TaskDescription, pg.Array(&task.TaskPictureUrls), &task.IsRewardTake, &task.CreateTime, &task.ReleaseTime, &task.Participators, &task.TaskPercentage, &task.SolveReport, pg.Array(&task.SolvePictureUrls), &task.AssignedPerson, &task.PlannedCompletionTime, &task.ActualCompletionTime),
"INSERT INTO tasks (id, company_id, task_name, task_type, sponsor, task_status, reference_resource, project_belong, customer_values, task_nature, su_money, min_su_money, max_su_money, acceptance_standard, task_description, task_picture_urls, is_reward_take, create_time, release_time, participators, task_percentage, solve_report, solve_picture_urls, assigned_person, planned_completion_time, actual_completion_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, company_id, task_name, task_type, sponsor, task_status, reference_resource, project_belong, customer_values, task_nature, su_money, min_su_money, max_su_money, acceptance_standard, task_description, task_picture_urls, is_reward_take, create_time, release_time, participators, task_percentage, solve_report, solve_picture_urls, assigned_person, planned_completion_time, actual_completion_time",
takeId, task.CompanyId, task.TaskName, task.TaskType, task.Sponsor, task.TaskStatus, task.ReferenceResource, task.ProjectBelong, pg.Array(task.CustomerValues), task.TaskNature, task.SuMoney, task.MinSuMoney, task.MaxSuMoney, task.AcceptanceStandard, task.TaskDescription, pg.Array(task.TaskPictureUrls), task.IsRewardTake, task.CreateTime, task.ReleaseTime, task.Participators, task.TaskPercentage, task.SolveReport, pg.Array(task.SolvePictureUrls), task.AssignedPerson, task.PlannedCompletionTime, task.ActualCompletionTime); err != nil {
return task, err
}
} else {
... ... @@ -49,9 +49,9 @@ func (repository *TaskRepository) Save(task *domain.Task) (*domain.Task, error)
taskReceiverUid = 0
}
if _, err := tx.QueryOne(
pg.Scan(&task.TaskId, &task.CompanyId, &task.TaskName, &task.TaskType, &task.Sponsor, &task.TaskStatus, &task.ReferenceResource, &task.ProjectBelong, pg.Array(&task.CustomerValues), &task.TaskNature, &task.SuMoney, &task.AcceptanceStandard, &task.TaskDescription, pg.Array(&task.TaskPictureUrls), &task.IsRewardTake, &task.CreateTime, &task.ReleaseTime, &task.Participators, &task.TaskPercentage, &task.SolveReport, pg.Array(&task.SolvePictureUrls), &task.AssignedPerson, &task.PlannedCompletionTime, &task.ActualCompletionTime, &task.ReceiveTime, &task.CompleteTime, &task.AcceptanceTime),
"UPDATE tasks SET company_id=?, task_name=?, task_type=?, sponsor=?, task_status=?, reference_resource=?, project_belong=?, customer_values=?, task_nature=?, su_money=?, acceptance_standard=?, task_description=?, task_picture_urls=?, is_reward_take=?, receiver_uid=?, create_time=?, release_time=?, participators=?, task_percentage=?, solve_report=?, solve_picture_urls=?, assigned_person=?, planned_completion_time=?, actual_completion_time=?, receive_time=?, complete_time=?, acceptance_time=? WHERE id=? RETURNING id, company_id, task_name, task_type, sponsor, task_status, reference_resource, project_belong, customer_values, task_nature, su_money, acceptance_standard, task_description, task_picture_urls, is_reward_take, create_time, release_time, participators, task_percentage, solve_report, solve_picture_urls, assigned_person, planned_completion_time, actual_completion_time, receive_time, complete_time, acceptance_time",
task.CompanyId, task.TaskName, task.TaskType, task.Sponsor, task.TaskStatus, task.ReferenceResource, task.ProjectBelong, pg.Array(task.CustomerValues), task.TaskNature, task.SuMoney, task.AcceptanceStandard, task.TaskDescription, pg.Array(task.TaskPictureUrls), task.IsRewardTake, taskReceiverUid, task.CreateTime, task.ReleaseTime, task.Participators, task.TaskPercentage, task.SolveReport, pg.Array(task.SolvePictureUrls), task.AssignedPerson, task.PlannedCompletionTime, task.ActualCompletionTime, task.ReceiveTime, task.CompleteTime, task.AcceptanceTime, task.Identify()); err != nil {
pg.Scan(&task.TaskId, &task.CompanyId, &task.TaskName, &task.TaskType, &task.Sponsor, &task.TaskStatus, &task.ReferenceResource, &task.ProjectBelong, pg.Array(&task.CustomerValues), &task.TaskNature, &task.SuMoney, &task.MinSuMoney, &task.MaxSuMoney, &task.AcceptanceStandard, &task.TaskDescription, pg.Array(&task.TaskPictureUrls), &task.IsRewardTake, &task.CreateTime, &task.ReleaseTime, &task.Participators, &task.TaskPercentage, &task.SolveReport, pg.Array(&task.SolvePictureUrls), &task.AssignedPerson, &task.PlannedCompletionTime, &task.ActualCompletionTime, &task.ReceiveTime, &task.CompleteTime, &task.AcceptanceTime),
"UPDATE tasks SET company_id=?, task_name=?, task_type=?, sponsor=?, task_status=?, reference_resource=?, project_belong=?, customer_values=?, task_nature=?, su_money=?, min_su_money=?, max_su_money=?, acceptance_standard=?, task_description=?, task_picture_urls=?, is_reward_take=?, receiver_uid=?, create_time=?, release_time=?, participators=?, task_percentage=?, solve_report=?, solve_picture_urls=?, assigned_person=?, planned_completion_time=?, actual_completion_time=?, receive_time=?, complete_time=?, acceptance_time=? WHERE id=? RETURNING id, company_id, task_name, task_type, sponsor, task_status, reference_resource, project_belong, customer_values, task_nature, su_money, min_su_money, max_su_money, acceptance_standard, task_description, task_picture_urls, is_reward_take, create_time, release_time, participators, task_percentage, solve_report, solve_picture_urls, assigned_person, planned_completion_time, actual_completion_time, receive_time, complete_time, acceptance_time",
task.CompanyId, task.TaskName, task.TaskType, task.Sponsor, task.TaskStatus, task.ReferenceResource, task.ProjectBelong, pg.Array(task.CustomerValues), task.TaskNature, task.SuMoney, task.MinSuMoney, task.MaxSuMoney, task.AcceptanceStandard, task.TaskDescription, pg.Array(task.TaskPictureUrls), task.IsRewardTake, taskReceiverUid, task.CreateTime, task.ReleaseTime, task.Participators, task.TaskPercentage, task.SolveReport, pg.Array(task.SolvePictureUrls), task.AssignedPerson, task.PlannedCompletionTime, task.ActualCompletionTime, task.ReceiveTime, task.CompleteTime, task.AcceptanceTime, task.Identify()); err != nil {
return task, err
}
}
... ... @@ -95,6 +95,7 @@ func (repository *TaskRepository) FindOne(queryOptions map[string]interface{}) (
return repository.transformPgModelToDomainModel(taskModel)
}
}
func (repository *TaskRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Task, error) {
tx := repository.transactionContext.PgTx
var taskModels []*models.Task
... ... @@ -115,6 +116,23 @@ func (repository *TaskRepository) Find(queryOptions map[string]interface{}) (int
if taskStatus, ok := queryOptions["taskStatus"]; ok && (taskStatus != 0) {
query = query.Where(`task.task_status = ?`, taskStatus)
}
if taskStates, ok := queryOptions["taskStates"]; ok && len(taskStates.([]int)) != 0 {
query = query.WhereGroup(func(q *orm.Query) (*orm.Query, error) {
for _, value := range taskStates.([]int) {
q = q.WhereOr("task.task_status = ?", value)
}
return q, nil
})
}
if taskStatuss, ok := queryOptions["taskStatuss"]; ok && len(taskStatuss.([]int)) != 0 {
//query = query.WhereGroup(func(q *orm.Query) (*orm.Query, error) {
// for _, value := range taskStatuss.([]int) {
// q = q.WhereOr("task.task_status = ?", value)
// }
// return q, nil
//})
query = query.Where(`task.task_status IN (?)`, pg.In(taskStatuss.([]int)))
}
if taskType, ok := queryOptions["taskType"]; ok && (taskType != 0) {
query = query.Where(`task.task_type = ?`, taskType)
}
... ... @@ -153,6 +171,9 @@ func (repository *TaskRepository) Find(queryOptions map[string]interface{}) (int
if taskContentMatch, ok := queryOptions["taskContentMatch"]; ok && (taskContentMatch != "") {
query = query.Where("task.task_name LIKE ?", fmt.Sprintf("%%%s%%", taskContentMatch.(string)))
}
if taskNameMatch, ok := queryOptions["taskNameMatch"]; ok && (taskNameMatch != "") { //
query = query.Where("task.task_name LIKE ?", fmt.Sprintf("%%%s%%", taskNameMatch.(string)))
}
if isRewardTake, ok := queryOptions["isRewardTake"]; ok && (isRewardTake != false) {
query = query.Where(`task.is_reward_take = ?`, isRewardTake)
}
... ... @@ -305,6 +326,9 @@ func (repository *TaskRepository) transformPgModelToDomainModel(taskModel *model
case domain.TASK_STATUS_UNCONFIRMED:
currentStatus = &domain.UnConfirmedStatus{}
break
case domain.TASK_STATUS_EXPIRED:
currentStatus = &domain.ExpiredStatus{}
break
}
return &domain.Task{
TaskId: taskModel.Id,
... ... @@ -318,6 +342,8 @@ func (repository *TaskRepository) transformPgModelToDomainModel(taskModel *model
CustomerValues: taskModel.CustomerValues,
TaskNature: taskModel.TaskNature,
SuMoney: taskModel.SuMoney,
MinSuMoney: taskModel.MinSuMoney,
MaxSuMoney: taskModel.MaxSuMoney,
AcceptanceStandard: taskModel.AcceptanceStandard,
TaskDescription: taskModel.TaskDescription,
TaskPictureUrls: taskModel.TaskPictureUrls,
... ...
package utils
import (
"encoding/json"
"fmt"
"time"
)
func StringSliceEqualBCE(a, b []int) bool {
if len(a) != len(b) {
return false
}
if (a == nil) != (b == nil) {
return false
}
b = b[:len(a)]
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
func IsContain(items []interface{}, item string) bool {
for _, eachItem := range items {
if eachItem == item {
return true
}
}
return false
}
func IsContainInt(items map[int64]interface{}, item int64) bool {
for _, eachItem := range items {
if eachItem == item {
return true
}
}
return false
}
type LocalTime time.Time
// MarshalJSON satify the json marshal interface
func (l LocalTime) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf("\"%s\"", time.Time(l).Format("2006-01-02 15:04:05"))
return []byte(stamp), nil
}
type LocalDate time.Time
// MarshalJSON satify the json marshal interface
func (l LocalDate) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf("\"%s\"", time.Time(l).Format("2006-01-02"))
return []byte(stamp), nil
}
func JsonToMap(jsonStr string) (map[string]string, error) {
m := make(map[string]string)
err := json.Unmarshal([]byte(jsonStr), &m)
if err != nil {
fmt.Printf("Unmarshal with error: %+v\n", err)
return nil, err
}
for k, v := range m {
fmt.Printf("%v: %v\n", k, v)
}
return m, nil
}
func InsertSlice(index int, newstr []string, src []string) (ns []string) {
ns = append(ns, src[:index]...) // 切片后加..., 相当于拆包成单个元素
ns = append(ns, newstr...)
ns = append(ns, src[index:]...)
return
}
//RankPeriodCheckTime 设置赛季时检查时间范围的合法性
//func RankPeriodCheckTime(rankTypeId int64, beginTime int64, endTime int64, idNot int64) bool {
// sql := `SELECT count(*) FROM rank_period
// WHERE rank_type_id = %d
// AND id <> %d
// AND
// (
// (UNIX_TIMESTAMP(begin_time) BETWEEN %d AND %d)
// OR
// (UNIX_TIMESTAMP(end_time) BETWEEN %d AND %d)
// OR
// (%d BETWEEN UNIX_TIMESTAMP(begin_time) AND UNIX_TIMESTAMP(end_time))
// OR
// (%d BETWEEN UNIX_TIMESTAMP(begin_time) AND UNIX_TIMESTAMP(end_time))
// )
// LIMIT 1 `
// sql = fmt.Sprintf(sql, rankTypeId, idNot, beginTime, endTime, beginTime, endTime, beginTime, endTime)
// var cnt int
// err := utils.ExecuteQueryOne(&cnt, sql)
// if err != nil {
// log.Error("SQL Execute err:%s", err)
// return false
// }
// if cnt > 0 {
// return false
// }
// return true
//}
\ No newline at end of file
... ...
package constant
//package constant
//var Logger log.Logger
// TODO 日志输出
//func init() {
// Logger = logrus.NewLogrusLogger()
// Logger.SetServiceName(constant.SERVICE_NAME)
// Logger.SetLevel(constant.LOG_LEVEL)
//}
package log
import (
"github.com/linmadan/egglib-go/log"
"github.com/linmadan/egglib-go/log/logrus"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/constant"
"path/filepath"
"strconv"
)
var Logger log.Logger
var Logger *logs.BeeLogger
func init() {
Logger = logrus.NewLogrusLogger()
Logger.SetServiceName(constant.SERVICE_NAME)
Logger.SetLevel(constant.LOG_LEVEL)
Logger = NewBeegoLogger(LoggerConfig{
Filename: constant.LOG_File,
Level: constant.LOG_LEVEL,
})
}
type LoggerConfig struct {
Level string `json:"level,omitempty"`
Filename string `json:"filename,omitempty"`
MaxSize int `json:"max_size,omitempty"`
MaxBackups int `json:"max_backups,omitempty"`
MaxAge int `json:"max_age,omitempty"`
Compress bool `json:"compress,omitempty"`
}
func NewBeegoLogger(conf LoggerConfig) *logs.BeeLogger {
filename := `{"filename":"` + filepath.ToSlash(conf.Filename) + `"}`
log := logs.GetBeeLogger()
log.SetLogger(logs.AdapterFile, filename)
ilv, err := strconv.Atoi(conf.Level)
if err != nil {
ilv = logs.LevelDebug
}
log.SetLevel(ilv)
log.EnableFuncCallDepth(true)
log.SetLogFuncCallDepth(5)
return log
}
func Debug(args ...interface{}) {
beego.Debug(args...)
}
func Info(args ...interface{}) {
beego.Info(args...)
}
func Warn(args ...interface{}) {
beego.Warn(args...)
}
func Error(args ...interface{}) {
beego.Error(args...)
}
... ...
... ... @@ -4,11 +4,20 @@ import (
"github.com/astaxie/beego"
"github.com/linmadan/egglib-go/web/beego/filters"
. "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/log"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/port/beego/middleware"
_ "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/port/beego/routers"
"time"
)
func init() {
beego.InsertFilter("/*", beego.BeforeExec, filters.CreateRequestBodyFilter())
beego.InsertFilter("/*", beego.BeforeExec, filters.CreateRequstLogFilter(Logger))
beego.InsertFilter("/*", beego.AfterExec, filters.CreateResponseLogFilter(Logger), false)
//beego.InsertFilter("/*", beego.BeforeExec, filters.CreateRequstLogFilter(Logger))
//beego.InsertFilter("/*", beego.AfterExec, filters.CreateResponseLogFilter(Logger), false)
beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequstLogFilter(Logger))
beego.InsertFilter("/*", beego.AfterExec, middleware.CreateResponseLogFilter(Logger), false)
timeLocal, _ := time.LoadLocation("Asia/Chongqing")
time.Local = timeLocal
}
... ...
... ... @@ -2,6 +2,7 @@ package controllers
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego"
"github.com/linmadan/egglib-go/web/beego/utils"
... ... @@ -85,10 +86,13 @@ func (controller *EmployeeController) ListEmployee() {
listEmployeeQuery.CompanyId = companyId
employeeNameMatch := controller.GetString("employeeNameMatch")
listEmployeeQuery.EmployeeNameMatch = employeeNameMatch
status, _ := controller.GetInt("status")
listEmployeeQuery.Status = status
offset, _ := controller.GetInt("offset")
listEmployeeQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listEmployeeQuery.Limit = limit
fmt.Print(listEmployeeQuery)
data, err := employeeService.ListEmployee(listEmployeeQuery)
var response utils.JsonResponse
if err != nil {
... ...
package controllers
import (
"encoding/json"
"github.com/astaxie/beego"
"github.com/linmadan/egglib-go/web/beego/utils"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/listInterval/command"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/listInterval/query"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/listInterval/service"
)
type ListIntervalController struct {
beego.Controller
}
// 新增榜单时间段
func (controller *ListIntervalController) CreateListInterval() {
listIntervalService := service.NewListIntervalService(nil)
createListIntervalCommand := &command.CreateListIntervalCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), createListIntervalCommand)
data, err := listIntervalService.CreateListInterval(createListIntervalCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 更新榜单时间段
func (controller *ListIntervalController) UpdateListInterval() {
listIntervalService := service.NewListIntervalService(nil)
updateListIntervalCommand := &command.UpdateListIntervalCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), updateListIntervalCommand)
listId, _ := controller.GetInt(":listId")
updateListIntervalCommand.ListIntervalId = listId
data, err := listIntervalService.UpdateListInterval(updateListIntervalCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 获取榜单时间段
func (controller *ListIntervalController) GetListInterval() {
listIntervalService := service.NewListIntervalService(nil)
getListIntervalQuery := &query.GetListIntervalQuery{}
listId, _ := controller.GetInt(":listId")
getListIntervalQuery.ListIntervalId = listId
data, err := listIntervalService.GetListInterval(getListIntervalQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 获取榜单时间段列表
func (controller *ListIntervalController) ListListInterval() {
listIntervalService := service.NewListIntervalService(nil)
listListIntervalQuery := &query.ListListIntervalQuery{}
companyId, _ := controller.GetInt("companyId")
listListIntervalQuery.CompanyId = companyId
offset, _ := controller.GetInt("offset")
listListIntervalQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listListIntervalQuery.Limit = limit
data, err := listIntervalService.ListListInterval(listListIntervalQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 移除榜单时间段
func (controller *ListIntervalController) RemoveListInterval() {
listIntervalService := service.NewListIntervalService(nil)
removeListIntervalQuery := &command.RemoveListIntervalCommand{}
listId, _ := controller.GetInt(":listId")
removeListIntervalQuery.ListIntervalId = listId
data, err := listIntervalService.RemoveListInterval(removeListIntervalQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
... ...
... ... @@ -2,6 +2,8 @@ package controllers
import (
"encoding/json"
"fmt"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/suMoney/query"
"github.com/astaxie/beego"
"github.com/linmadan/egglib-go/web/beego/utils"
... ... @@ -13,6 +15,7 @@ type StatisticsController struct {
beego.Controller
}
// 系统任务统计
func (controller *StatisticsController) SystemTaskStatistics() {
statisticsService := service.NewStatisticsService(nil)
systemTaskStatisticsCommand := &command.SystemTaskStatisticsCommand{}
... ... @@ -28,6 +31,7 @@ func (controller *StatisticsController) SystemTaskStatistics() {
controller.ServeJSON()
}
// 个人任务统计
func (controller *StatisticsController) PersonTaskStatistics() {
statisticsService := service.NewStatisticsService(nil)
personTaskStatisticsCommand := &command.PersonTaskStatisticsCommand{}
... ... @@ -43,6 +47,7 @@ func (controller *StatisticsController) PersonTaskStatistics() {
controller.ServeJSON()
}
// 个人素币统计
func (controller *StatisticsController) PersonSuMoneyStatistics() {
statisticsService := service.NewStatisticsService(nil)
personSuMoneyStatisticsCommand := &command.PersonSuMoneyStatisticsCommand{}
... ... @@ -58,6 +63,7 @@ func (controller *StatisticsController) PersonSuMoneyStatistics() {
controller.ServeJSON()
}
// 个人通知统计
func (controller *StatisticsController) PersonNotificationStatistics() {
statisticsService := service.NewStatisticsService(nil)
personNotificationStatisticsCommand := &command.PersonNotificationStatisticsCommand{}
... ... @@ -72,3 +78,84 @@ func (controller *StatisticsController) PersonNotificationStatistics() {
controller.Data["json"] = response
controller.ServeJSON()
}
// 系统素币统计
func (controller *StatisticsController) SystemSuMoneyStatistics() {
statisticsService := service.NewStatisticsService(nil)
systemSuMoneyStatisticsCommand := &command.SystemSuMoneyStatisticsCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), systemSuMoneyStatisticsCommand)
data, err := statisticsService.SystemSuMoneyStatistics(systemSuMoneyStatisticsCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 系统现金统计
func (controller *StatisticsController) SystemCashStatistics() {
statisticsService := service.NewStatisticsService(nil)
systemCashStatisticsCommand := &command.SystemCashStatisticsCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), systemCashStatisticsCommand)
data, err := statisticsService.SystemCashStatistics(systemCashStatisticsCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 获取公司员工财富值
func (controller *StatisticsController) EmployeesSuMoneyStatistics() {
statisticsService := service.NewStatisticsService(nil)
employeesSuMoneyStatisticsCommand := &command.EmployeesSuMoneyStatisticsCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), employeesSuMoneyStatisticsCommand)
fmt.Print(employeesSuMoneyStatisticsCommand, "\n")
data, err := statisticsService.EmployeesSuMoneyStatistics(employeesSuMoneyStatisticsCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 获取公司员工贡献值
func (controller *StatisticsController) EmployeesContributionsStatistics() {
statisticsService := service.NewStatisticsService(nil)
employeesContributionsStatisticsCommand := &command.EmployeesContributionsStatisticsCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), employeesContributionsStatisticsCommand)
data, err := statisticsService.EmployeesContributionsStatistics(employeesContributionsStatisticsCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 公司员工财富值、贡献值排行榜
func (controller *StatisticsController) RankingListStatistics() {
statisticsService := service.NewStatisticsService(nil)
contributionsWealthRankingQuery := &query.ContributionsWealthRankingQuery{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), contributionsWealthRankingQuery)
data, err := statisticsService.ContributionsWealthRanking(contributionsWealthRankingQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
\ No newline at end of file
... ...
... ... @@ -2,18 +2,25 @@ package controllers
import (
"encoding/json"
"fmt"
"github.com/360EntSecGroup-Skylar/excelize/v2"
"github.com/astaxie/beego"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/web/beego/utils"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/suMoney/command"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/suMoney/query"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/application/suMoney/service"
//utility "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/utils"
"os"
"path"
"strconv"
)
type SuMoneyController struct {
beego.Controller
}
// 操作素币
func (controller *SuMoneyController) OperationSuMoney() {
suMoneyService := service.NewSuMoneyService(nil)
operationSuMoneyCommand := &command.OperationSuMoneyCommand{}
... ... @@ -29,6 +36,7 @@ func (controller *SuMoneyController) OperationSuMoney() {
controller.ServeJSON()
}
// 获取素币事务记录
func (controller *SuMoneyController) GetSuMoneyTransactionRecord() {
suMoneyService := service.NewSuMoneyService(nil)
getSuMoneyTransactionRecordQuery := &query.GetSuMoneyTransactionRecordQuery{}
... ... @@ -45,6 +53,7 @@ func (controller *SuMoneyController) GetSuMoneyTransactionRecord() {
controller.ServeJSON()
}
// 兑换素币
func (controller *SuMoneyController) ExchangeSuMoney() {
suMoneyService := service.NewSuMoneyService(nil)
exchangeSuMoneyCommand := &command.ExchangeSuMoneyCommand{}
... ... @@ -60,9 +69,16 @@ func (controller *SuMoneyController) ExchangeSuMoney() {
controller.ServeJSON()
}
// 搜索素币事务
func (controller *SuMoneyController) SearchSuMoneyTransactionRecord() {
suMoneyService := service.NewSuMoneyService(nil)
searchSuMoneyTransactionRecordCommand := &command.SearchSuMoneyTransactionRecordCommand{}
employeeMatchName := controller.GetString("employeeMatchName")
searchSuMoneyTransactionRecordCommand.EmployeeMatchName = employeeMatchName
offset, _ := controller.GetInt("offset")
searchSuMoneyTransactionRecordCommand.Offset = offset
limit, _ := controller.GetInt("limit")
searchSuMoneyTransactionRecordCommand.Limit = limit
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), searchSuMoneyTransactionRecordCommand)
data, err := suMoneyService.SearchSuMoneyTransactionRecord(searchSuMoneyTransactionRecordCommand)
var response utils.JsonResponse
... ... @@ -75,6 +91,7 @@ func (controller *SuMoneyController) SearchSuMoneyTransactionRecord() {
controller.ServeJSON()
}
// 素币事务统计(个人素币收支)
func (controller *SuMoneyController) SuMoneyTransactionRecordStatistics() {
suMoneyService := service.NewSuMoneyService(nil)
suMoneyTransactionRecordStatisticsCommand := &command.SuMoneyTransactionRecordStatisticsCommand{}
... ... @@ -89,3 +106,755 @@ func (controller *SuMoneyController) SuMoneyTransactionRecordStatistics() {
controller.Data["json"] = response
controller.ServeJSON()
}
// 贡献值事务统计(个人贡献值收支)
func (controller *SuMoneyController) ContributionsTransactionRecordStatistics() {
suMoneyService := service.NewSuMoneyService(nil)
contributionsTransactionRecordStatisticsCommand := &command.ContributionsTransactionRecordStatisticsCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), contributionsTransactionRecordStatisticsCommand)
data, err := suMoneyService.ContributionsTransactionRecordStatistics(contributionsTransactionRecordStatisticsCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 投入现金池
func (controller *SuMoneyController) CashInput() {
cashPoolService := service.NewCashPoolService(nil)
createCashPoolCommand := &command.CreateCashPoolCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), createCashPoolCommand)
data, err := cashPoolService.CreateCashPool(createCashPoolCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 返回现金池
func (controller *SuMoneyController) GetCashPool() {
cashPoolService := service.NewCashPoolService(nil)
getCashPoolQuery := &query.GetCashPoolQuery{}
companyId, _ := controller.GetInt64("companyId")
getCashPoolQuery.CompanyId = companyId
data, err := cashPoolService.GetCashPool(getCashPoolQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 新增兑换活动
func (controller *SuMoneyController) CreateExchangeActivities () {
cashPoolService := service.NewCashPoolService(nil)
createExchangeCashActivityCommand := &command.CreateExchangeCashActivityCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), createExchangeCashActivityCommand)
data, err := cashPoolService.CreateExchangeCashActivity(createExchangeCashActivityCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 返回兑换活动列表
func (controller *SuMoneyController) ListExchangeActivities () {
cashPoolService := service.NewCashPoolService(nil)
listExchangeCashActivityQuery := &query.ListExchangeCashActivityQuery{}
companyId, _ := controller.GetInt64("companyId")
listExchangeCashActivityQuery.CompanyId = companyId
exchangeCashActivityNameMatch := controller.GetString("activityNameMatch")
listExchangeCashActivityQuery.ActivityNameMatch = exchangeCashActivityNameMatch
offset, _ := controller.GetInt("offset")
listExchangeCashActivityQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listExchangeCashActivityQuery.Limit = limit
isEnd, _ := controller.GetBool("isEnd")
listExchangeCashActivityQuery.IsEnd = isEnd
data, err := cashPoolService.ListExchangeCashActivity(listExchangeCashActivityQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 搜索返回兑换活动列表
func (controller *SuMoneyController) SearchExchangeActivities () {
cashPoolService := service.NewCashPoolService(nil)
searchExchangeCashActivityCommand := &command.SearchExchangeCashActivityCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), searchExchangeCashActivityCommand)
fmt.Printf("命令:%+v\n", searchExchangeCashActivityCommand)
data, err := cashPoolService.SearchExchangeCashActivity(searchExchangeCashActivityCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 返回兑换现金活动
func (controller *SuMoneyController) GetExchangeCashActivity () {
cashPoolService := service.NewCashPoolService(nil)
getExchangeCashActivityQuery := &query.GetExchangeCashActivityQuery{}
activityId, _ := controller.GetInt64(":activityId")
getExchangeCashActivityQuery.ExchangeCashActivityId = activityId
data, err := cashPoolService.GetExchangeCashActivity(getExchangeCashActivityQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 更新兑换活动信息
func (controller *SuMoneyController) UpdateExchangeActivities () {
cashPoolService := service.NewCashPoolService(nil)
updateExchangeCashActivityCommand := &command.UpdateExchangeCashActivityCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), updateExchangeCashActivityCommand)
activityId, _ := controller.GetInt64(":activityId")
updateExchangeCashActivityCommand.ExchangeCashActivityId = activityId
data, err := cashPoolService.UpdateExchangeCashActivity(updateExchangeCashActivityCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 移除兑换活动
func (controller *SuMoneyController) RemoveExchangeActivities () {
cashPoolService := service.NewCashPoolService(nil)
removeExchangeCashActivityCommand := &command.RemoveExchangeCashActivityCommand{}
activityId, _ := controller.GetInt64(":activityId")
beego.Info(activityId)
removeExchangeCashActivityCommand.ActivityId = activityId
data, err := cashPoolService.RemoveExchangeCashActivity(removeExchangeCashActivityCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 返回兑换素币清单列表
func (controller *SuMoneyController) ListExchangeList () {
cashPoolService := service.NewCashPoolService(nil)
listExchangeCashListQuery := &query.ListExchangeCashPersonQuery{}
activityId, _ := controller.GetInt64("activityId")
listExchangeCashListQuery.ExchangeCashActivityId = activityId
companyId, _ := controller.GetInt64("companyId")
listExchangeCashListQuery.CompanyId = companyId
exchangeCashPersonNameMatch := controller.GetString("personNameMatch")
listExchangeCashListQuery.ExchangeCashPersonNameMatch = exchangeCashPersonNameMatch
offset, _ := controller.GetInt("offset")
listExchangeCashListQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listExchangeCashListQuery.Limit = limit
data, err := cashPoolService.ListExchangeCashPerson(listExchangeCashListQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 新增兑换素币清单
func (controller *SuMoneyController) CreateExchangeList () {
cashPoolService := service.NewCashPoolService(nil)
createExchangeCashPersonCommand := &command.CreateExchangeCashPersonCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), createExchangeCashPersonCommand)
data, err := cashPoolService.CreateExchangeCashPerson(createExchangeCashPersonCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 更新兑换素币清单
func (controller *SuMoneyController) UpdateExchangeList () {
cashPoolService := service.NewCashPoolService(nil)
updateExchangeCashPersonCommand := &command.UpdateExchangeCashPersonCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), updateExchangeCashPersonCommand)
personId, _ := controller.GetInt64(":listId")
updateExchangeCashPersonCommand.ListId = personId
data, err := cashPoolService.UpdateExchangeCashPerson(updateExchangeCashPersonCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 移除兑换素币清单
func (controller *SuMoneyController) RemoveExchangeCashPerson() {
cashPoolService := service.NewCashPoolService(nil)
removeExchangeCashPersonCommand := &command.RemoveExchangeCashPersonCommand{}
personId, _ := controller.GetInt64(":listId")
operatorId, _ := controller.GetInt64("operator")
removeExchangeCashPersonCommand.ListId = personId
removeExchangeCashPersonCommand.Operator = operatorId
data, err := cashPoolService.RemoveExchangeCashPerson(removeExchangeCashPersonCommand)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 返回兑换素币清单
func (controller *SuMoneyController) GetExchangeCashPerson () {
cashPoolService := service.NewCashPoolService(nil)
getExchangeCashPersonQuery := &query.GetExchangeCashPersonQuery{}
listId, _ := controller.GetInt64(":listId")
getExchangeCashPersonQuery.ExchangeCashPersonId = listId
data, err := cashPoolService.GetExchangeCashPerson(getExchangeCashPersonQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 返回兑换活动截止时间列表
func (controller *SuMoneyController) ListDeadline() {
cashPoolService := service.NewCashPoolService(nil)
listExchangeCashActivityDeadlineQuery := &query.ListExchangeCashActivityDeadlineQuery{}
companyId, _ := controller.GetInt64("companyId")
listExchangeCashActivityDeadlineQuery.CompanyId = companyId
data, err := cashPoolService.ListExchangeCashActivityDeadline(listExchangeCashActivityDeadlineQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 返回兑换素币清单排行榜
func (controller *SuMoneyController) ExchangeCashListRanking() {
cashPoolService := service.NewCashPoolService(nil)
exchangeListRankingQuery := &query.ExchangeListRankingQuery{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), exchangeListRankingQuery)
data, err := cashPoolService.ExchangeListRanking(exchangeListRankingQuery)
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
// 导入兑换素币清单
func (controller *SuMoneyController) ImportExchangeList () {
cashPoolService := service.NewCashPoolService(nil)
where := controller.GetString("where")
file, h, _ := controller.GetFile("file")
jsonMap := make(map[string]interface{})
_ = json.Unmarshal([]byte(where), &jsonMap)
// 错误信息返回
var response utils.JsonResponse
// 返回字段定义
ret := map[string]interface{}{}
// 返回信息表头定义
var tableHeader = [...]string{"员工姓名", "手机号", "已兑换素币", "错误详情"}
// 文件后缀名校验
ext := path.Ext(h.Filename)
AllowExtMap := map[string]bool{
".xlsx":true,
}
if _,ok:=AllowExtMap[ext];!ok{
err := &application.ServiceError{
Code: 500,
Message: "后缀名不符合上传要求",
}
response = utils.ResponseError(controller.Ctx, err)
controller.Data["json"] = response
controller.ServeJSON()
return
}
// 打开文件
xlsx, err := excelize.OpenReader(file)
if err != nil {
fmt.Println(err)
return
}
// 文件行数校验
rows, _ := xlsx.GetRows("Sheet1")
//fmt.Print(len(rows), "\n")
if len(rows) > 303 {
err := &application.ServiceError{
Code: 500,
Message: "导入的文件超过300行",
}
response = utils.ResponseError(controller.Ctx, err)
controller.Data["json"] = response
controller.ServeJSON()
return
}
// 空表格判断
if len(rows) < 4 {
err := &application.ServiceError{
Code: 500,
Message: "当前导入的为空表格",
}
response = utils.ResponseError(controller.Ctx, err)
controller.Data["json"] = response
controller.ServeJSON()
return
}
// 必填项校验
nullLine := make([]interface{}, 0)
nullFlag := false
for i, row := range rows {
if i > 2 {
fmt.Print(len(row), "\n")
if len(row) == 3 {
var myRow []string = row
for j, cell := range row {
if cell == "" || cell == " " {
myRow[j] = ""
nullFlag = true
}
}
if nullFlag {
myRow = append(myRow, "必填项不能为空")
nullLine = append(nullLine, myRow)
nullFlag = false
}
} else if len(row) < 3 {
var myRow []string = row
for i := 0; i < 3 - len(row); i++ {
myRow = append(myRow, "")
}
myRow = append(myRow, "必填项不能为空")
nullLine = append(nullLine, myRow)
}
}
}
if len(nullLine) > 0 {
ret = map[string]interface{}{
"successCount": 0,
"fail": map[string]interface{}{
"tableHeader": tableHeader,
"tableData": nullLine,
},
}
response = utils.ResponseData(controller.Ctx, ret)
controller.Data["json"] = response
controller.ServeJSON()
return
}
// 新增失败记录
failureDataList := make([]interface{}, 0)
// 新增成功计数
var successDataCount int64
// 导入命令
var createExchangeCashPersonCommands []*command.CreateExchangeCashPersonCommand
errorLine := make([]interface{}, 0)
for i, row := range rows {
if i > 2 && len(row) > 1 {
// 创建兑换清单命令
createExchangeCashPersonCommand := &command.CreateExchangeCashPersonCommand{}
createExchangeCashPersonCommand.ExchangeCashActivityId, err = strconv.ParseInt(jsonMap["activityId"].(string), 10, 64 )
createExchangeCashPersonCommand.Operator = int64(jsonMap["uid"].(float64))
createExchangeCashPersonCommand.PersonName = row[0]
createExchangeCashPersonCommand.PersonAccount = row[1]
r2, err := strconv.ParseFloat(row[2], 64)
if err != nil { // 已兑换素币格式不正确
var myRow []string = row
myRow = append(myRow, "已兑换素币格式不正确")
errorLine = append(errorLine, myRow)
continue
}
createExchangeCashPersonCommand.ExchangedSuMoney = r2
createExchangeCashPersonCommands = append(createExchangeCashPersonCommands, createExchangeCashPersonCommand)
}
}
if len(errorLine) > 0 {
ret = map[string]interface{}{
"successCount": 0,
"fail": map[string]interface{}{
"tableHeader": tableHeader,
"tableData": errorLine,
},
}
response = utils.ResponseData(controller.Ctx, ret)
controller.Data["json"] = response
controller.ServeJSON()
return
}
// 创建兑换素币清单
failureDataList, err = cashPoolService.ImportCreateExchangeCashPerson(createExchangeCashPersonCommands, failureDataList)
if err != nil { // 导入失败处理
response = utils.ResponseError(controller.Ctx, err)
controller.Data["json"] = response
controller.ServeJSON()
return
} else {
if len(failureDataList) > 0 { // 导入失败返回
successDataCount = 0
ret = map[string]interface{}{
"successCount": successDataCount,
"fail": map[string]interface{}{
"tableHeader": tableHeader,
"tableData": failureDataList,
},
}
} else { // 导入成功返回
successDataCount = int64(len(rows) - 3 - len(failureDataList))
if successDataCount == int64(len(rows) - 3) {
ret = map[string]interface{}{
"successCount": successDataCount,
"fail": nil,
}
}
}
}
response = utils.ResponseData(controller.Ctx, ret)
controller.Data["json"] = response
controller.ServeJSON()
return
}
// 下载日志
func (controller *SuMoneyController) LogFile() {
controller.Ctx.Output.Download("logs/app.log","app.log")
}
// 导出素币兑换清单,选择导出(ids),增加导出失败信息
func (controller *SuMoneyController) ExportExchangeList() {
cashPoolService := service.NewCashPoolService(nil)
exportExchangeCashListCommand := &command.ExportExchangeCashListCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), exportExchangeCashListCommand)
// 列标题
titles := []string{
"姓名","手机账号","已兑换现金","已兑换素币",
}
// 列单元
cells := []string{
"A","B","C","D",
}
// 数据源
var data []map[string]interface{}
people, err := cashPoolService.ListExchangeCashPersonById(exportExchangeCashListCommand)
for _, person := range people {
p := map[string]interface{} {
"name": person.EmployeeInfo.EmployeeName,
"account": person.EmployeeInfo.EmployeeAccount,
"exchanged_cash": person.ExchangedCash,
"exchanged_su_money": person.ExchangedSuMoney,
}
data = append(data, p)
}
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
controller.Data["json"] = response
controller.ServeJSON()
} else {
// 新建文件
f := excelize.NewFile()
// 新建工作簿
index := f.NewSheet("Sheet1")
//列标题赋值
for column, v := range titles {
f.SetCellValue("Sheet1", cells[column] + "1", v)
}
for lineNum, v := range data { //行数 lineNum 行内容 v
for columnNum := 0; columnNum < len(v); columnNum ++ {
cell := cells[columnNum]
row := strconv.Itoa(lineNum + 2)
switch cell {
case "A":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["name"])
break
case "B":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["account"])
break
case "C":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["exchanged_cash"])
break
case "D":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["exchanged_su_money"])
break
}
}
}
f.SetActiveSheet(index)
// 创建下载文件夹
mkErr :=os.Mkdir("download", os.ModePerm)
if err!=nil{
fmt.Println(mkErr)
}
//保存为文件
f.Path="download/素币兑换清单.xlsx"
if err := f.Save(); err != nil {
fmt.Println(err)
}
controller.Ctx.Output.Download(f.Path,"素币兑换清单.xlsx")
// 下载完成删除文件
removeErr := os.Remove(f.Path)
if err != nil {
fmt.Println(removeErr)
}
}
}
// 导出素币流水
func (controller *SuMoneyController) ExportSuMoney() {
suMoneyService := service.NewSuMoneyService(nil)
exportSuMoneyCommand := &command.ExportSuMoneyCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), exportSuMoneyCommand)
// 列标题
titles := []string{
"员工姓名","手机账号","当前素币",
}
// 列单元
cells := []string{
"A","B","C",
}
var response utils.JsonResponse
var data []map[string]interface{}
records, err := suMoneyService.ListSuMoneyById(exportSuMoneyCommand)
for _, record := range records {
p := map[string]interface{} {
"name": record.EmployeeInfo.EmployeeName,
"account": record.EmployeeInfo.EmployeeAccount,
"current_su_money": record.SuMoney,
}
data = append(data, p)
}
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
controller.Data["json"] = response
controller.ServeJSON()
} else {
// 新建文件
f := excelize.NewFile()
// 新建工作簿
index := f.NewSheet("Sheet1")
//列标题赋值
for column, v := range titles {
f.SetCellValue("Sheet1", cells[column]+"1", v)
}
for lineNum, v := range data { //行数 lineNum 行内容 v
for columnNum := 0; columnNum < len(v); columnNum ++ {
cell := cells[columnNum]
row := strconv.Itoa(lineNum + 2)
switch cell {
case "A":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["name"])
break
case "B":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["account"])
break
case "C":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["current_su_money"])
break
}
}
}
f.SetActiveSheet(index)
// 创建下载文件夹
mkErr :=os.Mkdir("download", os.ModePerm)
if err!=nil{
fmt.Println(mkErr)
}
//保存为文件
f.Path="download/素币流水.xlsx"
if err := f.Save(); err != nil {
fmt.Println(err)
}
controller.Ctx.Output.Download(f.Path,"素币流水.xlsx")
// 下载完成删除文件
removeErr := os.Remove(f.Path)
if err != nil {
fmt.Println(removeErr)
}
}
}
// 导出素币流水记录
func (controller *SuMoneyController) ExportSuMoneyTransactionRecord() {
suMoneyService := service.NewSuMoneyService(nil)
exportTransactionRecordCommand := &command.ExportTransactionRecordCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), exportTransactionRecordCommand)
// 列标题
titles := []string{
"员工姓名","当前素币","素币流水","操作时间","操作人",
}
// 列单元
cells := []string{
"A","B","C","D","E",
}
var response utils.JsonResponse
var data []map[string]interface{}
records, err := suMoneyService.ListSuMoneyTransactionRecordById(exportTransactionRecordCommand)
for _, record := range records {
p := map[string]interface{}{}
if record.RecordType == 2 || record.RecordType == 3 || record.RecordType == 6 {
p = map[string]interface{} {
"name": record.Employee.EmployeeName,
"current_su_money": record.CurrentSuMoney,
"record": "+" + fmt.Sprintf("%.2f", record.SuMoney),
"create_time": record.CreateTime.Local().Format("2006/01/02 15:04:05"),
"operator": record.Operator.EmployeeName,
}
} else {
p = map[string]interface{} {
"name": record.Employee.EmployeeName,
"current_su_money": record.CurrentSuMoney,
"record": "-" + fmt.Sprintf("%.2f", record.SuMoney),
"create_time": record.CreateTime.Local().Format("2006/01/02 15:04:05"),
"operator": record.Operator.EmployeeName,
}
}
data = append(data, p)
}
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
controller.Data["json"] = response
controller.ServeJSON()
} else {
// 新建文件
f := excelize.NewFile()
// 新建工作簿
index := f.NewSheet("Sheet1")
//列标题赋值
for column, v := range titles {
f.SetCellValue("Sheet1", cells[column]+"1", v)
}
for lineNum, v := range data { //行数 lineNum 行内容 v
for columnNum := 0; columnNum < len(v); columnNum ++ {
cell := cells[columnNum]
row := strconv.Itoa(lineNum + 2)
switch cell {
case "A":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["name"])
break
case "B":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["current_su_money"])
break
case "C":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["record"])
break
case "D":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["create_time"])
break
case "E":
sheetPosition := cell + row
f.SetCellValue("Sheet1", sheetPosition, v["operator"])
break
}
}
}
f.SetActiveSheet(index)
// 创建下载文件夹
mkErr :=os.Mkdir("download", os.ModePerm)
if err!=nil{
fmt.Println(mkErr)
}
//保存为文件
f.Path="download/素币流水记录.xlsx"
if err := f.Save(); err != nil {
fmt.Println(err)
}
controller.Ctx.Output.Download(f.Path,"素币流水记录.xlsx")
// 下载完成删除文件
removeErr := os.Remove(f.Path)
if err != nil {
fmt.Println(removeErr)
}
}
}
... ...
... ... @@ -214,6 +214,22 @@ func (controller *TaskController) UpdateTask() {
controller.ServeJSON()
}
// 更新过期任务状态
func (controller *TaskController) UpdateTaskStatus() {
taskService := service.NewTaskService(nil)
updateTaskCommand := &command.UpdateTaskCommand{}
json.Unmarshal(controller.Ctx.Input.GetData("requestBody").([]byte), updateTaskCommand)
data, err := taskService.UpdateTaskStatus()
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(controller.Ctx, err)
} else {
response = utils.ResponseData(controller.Ctx, data)
}
controller.Data["json"] = response
controller.ServeJSON()
}
func (controller *TaskController) GetTask() {
taskService := service.NewTaskService(nil)
getTaskQuery := &query.GetTaskQuery{}
... ...
package middleware
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
"io/ioutil"
"net/http"
"time"
)
func CreateRequstLogFilter(logger *logs.BeeLogger) func(ctx *context.Context) {
return func(ctx *context.Context) {
requestId := fmt.Sprintf("%v.%v.%v ", ctx.Input.Method(), ctx.Input.URI(), time.Now().UnixNano())
ctx.Request.Header.Add("requestId", requestId)
var body string = "{}"
if ctx.Input.GetData("requestBody") != nil {
body = string(ctx.Input.GetData("requestBody").([]byte))
}
logger.Debug(fmt.Sprintf("====>Recv User:%v RequestId:%s \n Auth=%v \n BodyData:%s", ctx.Input.GetData("UserId"), requestId, ctx.Input.Header("x-mmm-accesstoken"), body))
}
}
func CreateResponseLogFilter(logger *logs.BeeLogger) func(ctx *context.Context) {
return func(ctx *context.Context) {
requestId := ctx.Request.Header.Get("requestId")
body, _ := json.Marshal(ctx.Input.GetData("outputData"))
if len(body) > 100000 {
body = body[:100000]
}
logger.Debug(fmt.Sprintf("<====Send RequestId:%v BodyData:%s", requestId, body))
}
}
func CreateRequestBodyFilter() func(ctx *context.Context) {
return func(ctx *context.Context) {
if ctx.Request.Method == http.MethodPost || ctx.Request.Method == http.MethodPut {
body, _ := ioutil.ReadAll(ctx.Request.Body)
if len(body) == 0 {
body = []byte("{}")
}
ctx.Input.SetData("requestBody", body)
ctx.Request.Body.Close()
}
}
}
... ...
... ... @@ -11,4 +11,5 @@ func init() {
beego.Router("/employees/:uid", &controllers.EmployeeController{}, "Get:GetEmployee")
beego.Router("/employees/:uid", &controllers.EmployeeController{}, "Delete:RemoveEmployee")
beego.Router("/employees/", &controllers.EmployeeController{}, "Get:ListEmployee")
//beego.Router("/employees/export", &controllers.EmployeeController{}, "Post:ExportSuMoney") // 导出员工素币情况列表
}
... ...
package routers
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/port/beego/controllers"
)
func init() {
beego.Router("/list-interval/", &controllers.ListIntervalController{}, "Post:CreateListInterval")
beego.Router("/list-interval/:listId", &controllers.ListIntervalController{}, "Put:UpdateListInterval")
beego.Router("/list-interval/:listId", &controllers.ListIntervalController{}, "Get:GetListInterval")
beego.Router("/list-interval/:listId", &controllers.ListIntervalController{}, "Delete:RemoveListInterval")
beego.Router("/list-interval/", &controllers.ListIntervalController{}, "Get:ListListInterval")
}
\ No newline at end of file
... ...
... ... @@ -6,8 +6,13 @@ import (
)
func init() {
beego.Router("/statistics/system-task", &controllers.StatisticsController{}, "Post:SystemTaskStatistics")
beego.Router("/statistics/person-task", &controllers.StatisticsController{}, "Post:PersonTaskStatistics")
beego.Router("/statistics/person-su-money", &controllers.StatisticsController{}, "Post:PersonSuMoneyStatistics")
beego.Router("/statistics/person-notification", &controllers.StatisticsController{}, "Post:PersonNotificationStatistics")
beego.Router("/statistics/system-task", &controllers.StatisticsController{}, "Post:SystemTaskStatistics") // 系统任务统计
beego.Router("/statistics/person-task", &controllers.StatisticsController{}, "Post:PersonTaskStatistics") // 个人任务统计
beego.Router("/statistics/person-su-money", &controllers.StatisticsController{}, "Post:PersonSuMoneyStatistics") // 个人素币统计
beego.Router("/statistics/person-notification", &controllers.StatisticsController{}, "Post:PersonNotificationStatistics") // 个人通知统计
beego.Router("/statistics/system-su-money", &controllers.StatisticsController{}, "Post:SystemSuMoneyStatistics") // 系统素币统计
beego.Router("/statistics/system-cash", &controllers.StatisticsController{}, "Post:SystemCashStatistics") // 系统现金统计
beego.Router("/statistics/employees-su-money", &controllers.StatisticsController{}, "Post:EmployeesSuMoneyStatistics") // 员工财富值统计
beego.Router("/statistics/employees-contributions", &controllers.StatisticsController{}, "Post:EmployeesContributionsStatistics") // 员工贡献值统计
beego.Router("/statistics/employees-ranking-list", &controllers.StatisticsController{}, "Post:RankingListStatistics") // 员工财富值、贡献值排行榜
}
... ...
... ... @@ -6,9 +6,38 @@ import (
)
func init() {
beego.Router("/su-money/operation", &controllers.SuMoneyController{}, "Post:OperationSuMoney")
beego.Router("/su-money/su-money-transaction-records/:suMoneyTransactionRecordId", &controllers.SuMoneyController{}, "Get:GetSuMoneyTransactionRecord")
beego.Router("/su-money/exchange", &controllers.SuMoneyController{}, "Post:ExchangeSuMoney")
beego.Router("/su-money/search-su-money-transaction-record", &controllers.SuMoneyController{}, "Post:SearchSuMoneyTransactionRecord")
beego.Router("/su-money/su-money-transaction-record-statistics", &controllers.SuMoneyController{}, "Post:SuMoneyTransactionRecordStatistics")
/**********************************************素币流水******************************************/
beego.Router("/su-money/operation", &controllers.SuMoneyController{}, "Post:OperationSuMoney") // 操作素币(增加,扣除,兑换)
beego.Router("/su-money/su-money-transaction-records/:suMoneyTransactionRecordId", &controllers.SuMoneyController{}, "Get:GetSuMoneyTransactionRecord") // 返回素币事务记录
beego.Router("/su-money/exchange", &controllers.SuMoneyController{}, "Post:ExchangeSuMoney") // 兑换素币
beego.Router("/su-money/search-su-money-transaction-record", &controllers.SuMoneyController{}, "Post:SearchSuMoneyTransactionRecord") // 搜索素币事务记录
beego.Router("/su-money/su-money-transaction-record-statistics", &controllers.SuMoneyController{}, "Post:SuMoneyTransactionRecordStatistics") // 返回素币事务记录统计(个人素币收支)
beego.Router("/su-money/contributions-transaction-record-statistics", &controllers.SuMoneyController{}, "Post:ContributionsTransactionRecordStatistics") // 返回贡献值事务记录统计(个人贡献值收支)
beego.Router("/su-money/su-money-transaction-records/export-records", &controllers.SuMoneyController{}, "Post:ExportSuMoneyTransactionRecord") // 导出素币事务记录(素币流水记录)
beego.Router("/su-money/su-money-transaction-records/export-su-money", &controllers.SuMoneyController{}, "Post:ExportSuMoney") // 导出员工素币流水
/**********************************************现金池*******************************************/
beego.Router("/cash-pool/input", &controllers.SuMoneyController{}, "Post:CashInput") // 现金池投入
beego.Router("/cash-pool/cash-pool", &controllers.SuMoneyController{}, "Get:GetCashPool") // 返回现金池统计
/********************************************素币兑换活动***************************************/
beego.Router("/cash-pool/activity/", &controllers.SuMoneyController{}, "Get:ListExchangeActivities") // 返回兑换活动列表
beego.Router("/cash-pool/activity/:activityId", &controllers.SuMoneyController{}, "Get:GetExchangeCashActivity") // 返回兑换活动
beego.Router("/cash-pool/activity/:activityId", &controllers.SuMoneyController{}, "Put:UpdateExchangeActivities") // 编辑兑换活动
beego.Router("/cash-pool/activity", &controllers.SuMoneyController{}, "Post:CreateExchangeActivities") // 新增兑换活动
beego.Router("/cash-pool/activity/:activityId", &controllers.SuMoneyController{}, "Delete:RemoveExchangeActivities") // 删除兑换活动
beego.Router("/cash-pool/activity/deadline-list", &controllers.SuMoneyController{}, "Get:ListDeadline") // 返回兑换活动截止时间列表
beego.Router("/cash-pool/activity/search-activity", &controllers.SuMoneyController{}, "Post:SearchExchangeActivities") // 搜索兑换活动列表
/********************************************素币兑换清单*************************************/
beego.Router("/cash-pool/activity/exchange-list", &controllers.SuMoneyController{}, "Get:ListExchangeList") // 返回素币兑换清单
beego.Router("/cash-pool/activity/exchange-list/:listId", &controllers.SuMoneyController{}, "Get:GetExchangeCashPerson") // 返回素币兑换人员
beego.Router("/cash-pool/activity/exchange-list", &controllers.SuMoneyController{}, "Post:CreateExchangeList") // 新增素币兑换清单
beego.Router("/cash-pool/activity/exchange-list/:listId", &controllers.SuMoneyController{}, "Put:UpdateExchangeList") // 编辑素币兑换清单
beego.Router("/cash-pool/activity/exchange-list/:listId", &controllers.SuMoneyController{}, "Delete:RemoveExchangeCashPerson") // 删除素币兑换清单
beego.Router("/cash-pool/activity/exchange-list/import", &controllers.SuMoneyController{}, "Post:ImportExchangeList") // 导入素币兑换清单
beego.Router("/cash-pool/activity/exchange-list/export", &controllers.SuMoneyController{}, "Post:ExportExchangeList") // 导出素币兑换清单
beego.Router("/cash-pool/activity/exchange-list/ranking", &controllers.SuMoneyController{}, "Post:ExchangeCashListRanking") // 兑换素币清单排行榜
beego.Router("/log", &controllers.SuMoneyController{}, "Get:LogFile") // 系统日志
}
... ...
... ... @@ -21,4 +21,5 @@ func init() {
beego.Router("/tasks/:taskId", &controllers.TaskController{}, "Get:GetTask")
beego.Router("/tasks/:taskId", &controllers.TaskController{}, "Delete:RemoveTask")
beego.Router("/tasks/", &controllers.TaskController{}, "Get:ListTask")
beego.Router("/tasks/test/expired", &controllers.TaskController{}, "Put:UpdateTaskStatus")
}
... ...
package cash_pool
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg"
)
var _ = Describe("投入现金", func() {
Describe("投入现金并更新现金池数据", func() {
Context("提交正确的现金值(>=已兑换的现金)", func() {
It("返回现金池数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"cashAmount": 100,
}
httpExpect.POST("/cash_pool/input").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM ")
Expect(err).NotTo(HaveOccurred())
})
})
\ No newline at end of file
... ...
package cash_pool
import (
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
"net/http"
"net/http/httptest"
"testing"
"github.com/astaxie/beego"
_ "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/port/beego"
)
func TestConfig(t *testing.T) {
gomega.RegisterFailHandler(ginkgo.Fail)
ginkgo.RunSpecs(t, "Beego Port Cash Pool Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = ginkgo.BeforeSuite(func() {
handler = beego.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = ginkgo.AfterSuite(func() {
server.Close()
})
\ No newline at end of file
... ...