作者 yangfu

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

### 接口完成进度
| 功能 | 完成状态 | 时间 | 接口路径 | 请求方式 |
| ---------------- | ------------------ | --------------- | -------------------------- | -------- |
| ---------------- | -------- | ---------- | -------------------------- | -------- |
| 登录获取 token | 完成 | 2018/12/11 | /auth/login | post |
| 短信验证码 | 未开始 | | |
| 刷新 token | 完成 | 2018/12/11 | /v1/auth/refresh_token | get |
| 切换公司 | 完成 | 2018/12/11 | /v1/auth/change_company | post |
| 获取个人基础数据 | 未开始 | | /v1/auth/me | get |
| 获取个人基础数据 | (暂停) | | /v1/auth/me | get |
| 获取角色列表 | 完成 | | /v1/rbac/role | get |
| 添加角色 | 完成 | 2019.11.26 | /v1/rbac/role/add | post |
| 编辑角色 | 完成 | 2019.11.26 | /v1/rbac/role/edit | post |
| ~~删除角色~~ | ~~完成(待变更)~~ | ~~ 2019.11.26~~ | /v1/rbac/role/delete | post |
| 删除角色 | 完成 | 2019.12.04 | /v1/rbac/role/delete | post |
| 添加角色组 | 完成 | 2019.12.04 | /v1/rbac/role_group/add | post |
| 编辑角色组 | 完成 | 2019.12.04 | /v1/rbac/role_group/edit | post |
... ... @@ -18,7 +17,6 @@
| 获取部门列表 | 完成 | 2019.12.5 | /v1/department | get |
| 添加部门 | 完成 | 2019.11.28 | /v1/department/add | post |
| 编辑部门 | 完成 | 2019.11.29 | /v1/department/edit | post |
| ~~删除部门~~ | ~~完成(待变更)~~ | ~~2019.11.29~~ | ~~/v1/department~~ | post |
| 删除部门 | 完成 | 2019.12.2 | /v1/department/delete | post |
| 获取职位列表 | 进行中 | | /v1/position | get |
| 添加职位 | 完成 | 2019.12.2 | /v1/position/add | post |
... ...
... ... @@ -96,13 +96,16 @@ func (c *AuthController) ChangeCompany() {
return
}
//me
//@router /me [get]
func (c *AuthController) Me() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
// userid := c.GetUserId()
// companyid := c.GetCompanyId()
userid := c.GetUserId()
companyid := c.GetCompanyId()
userinfo, err := serveauth.UserBaseInfo(userid, companyid)
msg = protocol.NewReturnResponse(userinfo, err)
return
}
... ...
... ... @@ -63,7 +63,7 @@ func (c *CompanyController) DepartmentOne() {
}
// DepartmentAdd 添加部门
// @router /department [post]
// @router /department/add [post]
func (c *CompanyController) DepartmentAdd() {
var msg *protocol.ResponseMessage
defer func() {
... ... @@ -87,7 +87,7 @@ func (c *CompanyController) DepartmentAdd() {
}
// DepartmentUpdate 更新部门
// @router /department [put]
// @router /department/edit [post]
func (c *CompanyController) DepartmentUpdate() {
var msg *protocol.ResponseMessage
defer func() {
... ... @@ -112,7 +112,7 @@ func (c *CompanyController) DepartmentUpdate() {
}
// DepartmentUpdate 删除部门
// @router /department [delete]
// @router /department/delete [post]
func (c *CompanyController) DepartmentDelete() {
var msg *protocol.ResponseMessage
defer func() {
... ... @@ -132,7 +132,7 @@ func (c *CompanyController) DepartmentDelete() {
}
// PositionAdd 添加职位
// @router /position [post]
// @router /position/add [post]
func (c *CompanyController) PositionAdd() {
var msg *protocol.ResponseMessage
defer func() {
... ... @@ -152,7 +152,7 @@ func (c *CompanyController) PositionAdd() {
}
// PositionEdit 编辑职位
// @router /position [put]
// @router /position/edit [post]
func (c *CompanyController) PositionEdit() {
var msg *protocol.ResponseMessage
defer func() {
... ... @@ -171,7 +171,7 @@ func (c *CompanyController) PositionEdit() {
}
// PositionDelete 删除职位
// @router /position [delete]
// @router /position/delete [post]
func (c *CompanyController) PositionDelete() {
var msg *protocol.ResponseMessage
defer func() {
... ... @@ -213,7 +213,40 @@ func (c *CompanyController) PositionList() {
return
}
//获取公司的基本信息
func (c *CompanyController) BaseInfo() {
//UserAdd 添加用户
//@Router /user/add [post]
func (c *CompanyController) UserAdd() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestUserAdd
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
param.CompanyId = c.GetCompanyId()
err := servecompany.UserAdd(param)
msg = protocol.NewReturnResponse(nil, err)
return
}
//UserAdd 添加用户
//@Router /user/edit [post]
func (c *CompanyController) UserEdit() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestUserEdit
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
param.CompanyId = c.GetCompanyId()
err := servecompany.UserEdit(param)
msg = protocol.NewReturnResponse(nil, err)
return
}
... ...
... ... @@ -3,6 +3,7 @@ module oppmg
go 1.13
require (
github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2
github.com/astaxie/beego v1.11.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-redis/redis v6.15.6+incompatible
... ... @@ -11,7 +12,6 @@ require (
github.com/onsi/ginkgo v1.10.3 // indirect
github.com/onsi/gomega v1.7.1 // indirect
github.com/satori/go.uuid v1.2.0
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
github.com/sony/sonyflake v1.0.0
golang.org/x/crypto v0.0.0-20191119213627-4f8c1d86b1ba // indirect
google.golang.org/appengine v1.6.5 // indirect
... ...
github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2 h1:StMrA6UQ5Cm6206DxXGuV/NMqSIOIDoMXMYt8JPe1lE=
github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2/go.mod h1:EfRHD2k+Kd7ijnqlwOrH1IifwgWB9yYJ0pdXtBZmlpU=
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/OwnLocal/goes v1.0.0/go.mod h1:8rIFjBGTue3lCU0wplczcUgt9Gxgrkkrw7etMIcn8TM=
github.com/astaxie/beego v1.10.0 h1:s0OZ1iUO0rl8+lwWZfPK/0GhQi1tFUcIClTevyz48Pg=
github.com/astaxie/beego v1.10.0/go.mod h1:0R4++1tUqERR0WYFWdfkcrsyoVBCG4DgpDGokT3yb+U=
github.com/astaxie/beego v1.11.1 h1:6DESefxW5oMcRLFRKi53/6exzup/IR6N4EzzS1n6CnQ=
github.com/astaxie/beego v1.11.1/go.mod h1:i69hVzgauOPSw5qeyF4GVZhn7Od0yG5bbCGzmhbWxgQ=
github.com/astaxie/beego v1.12.0 h1:MRhVoeeye5N+Flul5PoVfD9CslfdoH+xqC/xvSQ5u2Y=
github.com/astaxie/beego v1.12.0/go.mod h1:fysx+LZNZKnvh4GED/xND7jWtjCR6HzydR2Hh2Im57o=
github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ=
github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU=
github.com/belogik/goes v0.0.0-20151229125003-e54d722c3aff/go.mod h1:PhH1ZhyCzHKt4uAasyx+ljRCgoezetRNf59CUtwUkqY=
... ... @@ -16,10 +13,15 @@ github.com/couchbase/go-couchbase v0.0.0-20181122212707-3e9b6e1258bb/go.mod h1:T
github.com/couchbase/gomemcached v0.0.0-20181122193126-5125a94a666c/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c=
github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs=
github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/deckarep/golang-set v1.7.1 h1:SCQV0S6gTtp6itiFrTqI+pfmJ4LN85S1YzhDf9rTHJQ=
github.com/deckarep/golang-set v1.7.1/go.mod h1:93vsz/8Wt4joVM7c2AVqh+YRMiUSc14yDtF28KmMOgQ=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk=
github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
... ... @@ -39,8 +41,10 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK860o=
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v2.0.0+incompatible h1:+afSeuaczjy4ZUN55wuDe1bCaAFBu0hg5Cf2Zw2ar0s=
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/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.3 h1:OoxbjfXVZyod1fmWYhI7SEyaD8B00ynP3T+D5GiyHOY=
github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
... ... @@ -48,16 +52,19 @@ github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
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/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
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/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=
github.com/sony/sonyflake v1.0.0 h1:MpU6Ro7tfXwgn2l5eluf9xQvQJDROTBImNCfRXn/YeM=
github.com/sony/sonyflake v1.0.0/go.mod h1:Jv3cfhf/UFtolOTTRd3q4Nl6ENqM+KfyZ5PseKfZGF4=
github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc=
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85 h1:et7+NAX3lLIk5qUCTA9QelBjGE/NkhzYw/mhnr0s7nI=
... ... @@ -65,6 +72,8 @@ golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85/go.mod h1:6SG95UA2DQfeDnf
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191119213627-4f8c1d86b1ba h1:9bFeDpN3gTqNanMVqNcoR/pJQuP5uroC3t1D7eXozTE=
golang.org/x/crypto v0.0.0-20191119213627-4f8c1d86b1ba/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a h1:gHevYm0pO4QUbwy8Dmdr01R5r1BuKtfYqRqF0h/Cbh0=
golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
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=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
... ...
package models
import (
"errors"
"fmt"
"time"
... ... @@ -43,6 +42,13 @@ func (t *User) IsEnable() bool {
return false
}
func (t *User) IsDelete() bool {
if t.DeleteAt.Unix() < 0 {
return false
}
return true
}
func init() {
orm.RegisterModel(new(User))
}
... ... @@ -90,12 +96,13 @@ func UpdateUserById(m *User) (err error) {
func GetUserByPhone(phone string) (v *User, err error) {
o := orm.NewOrm()
v = &User{Phone: phone}
if err = o.Read(v, "Phone"); err == nil {
err = o.QueryTable(&User{}).
Filter("phone", phone).
Filter("delete_at", 0).
One(v)
if err == nil {
return v, nil
}
if v.DeleteAt.Unix() > 0 {
return nil, errors.New("user is deleted")
}
return nil, err
}
... ...
package models
import (
"errors"
"fmt"
"oppmg/common/log"
"time"
... ... @@ -54,8 +55,10 @@ func init() {
// AddUserCompany insert a new UserCompany into database and returns
// last inserted Id on success.
func AddUserCompany(m *UserCompany) (id int64, err error) {
o := orm.NewOrm()
func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) {
m.CreateAt = time.Now()
m.DeleteAt = time.Unix(0, 0)
m.UpdateAt = time.Now()
id, err = o.Insert(m)
return
}
... ... @@ -77,13 +80,15 @@ func UpdateUserCompanyById(m *UserCompany) (err error) {
func GetUserCompanyBy(userid int64, companyId int64) (*UserCompany, error) {
o := orm.NewOrm()
v := &UserCompany{
UserId: userid,
CompanyId: companyId,
}
err := o.Read(v, "UserId", "CompanyId")
var data []*UserCompany
_, err := o.QueryTable(&UserCompany{}).Filter("UserId", userid).
Filter("CompanyId", companyId).
All(&data)
if err != nil {
return nil, err
}
return v, nil
if len(data) == 0 {
return nil, errors.New("UserCompany not found")
}
return data[0], nil
}
... ...
... ... @@ -8,10 +8,10 @@ import (
)
type UserDepartment struct {
Id int `orm:"column(id);auto" description:"主键"`
Id int64 `orm:"column(id);auto" description:"主键"`
UserId int64 `orm:"column(user_id)" description:"用户id"`
CompanyId int `orm:"column(company_id)" description:"公司id"`
DepartmentId int `orm:"column(department_id)" description:"部门id"`
CompanyId int64 `orm:"column(company_id)" description:"公司id"`
DepartmentId int64 `orm:"column(department_id)" description:"部门id"`
CreateTime time.Time `orm:"column(create_time);type(timestamp);null" description:"创建时间"`
EnableStatus int8 `orm:"column(enable_status)" description:"是否有效"`
}
... ... @@ -20,6 +20,34 @@ func (t *UserDepartment) TableName() string {
return "user_department"
}
//EnableStatus 是否有效
const (
USER_DEPARTMENT_ENABLE_YES int8 = 1 //有效
USER_DEPARTMENT_ENABLE_NO int8 = 2 //无效
)
func (t *UserDepartment) IsEnable() bool {
switch t.EnableStatus {
case USER_DEPARTMENT_ENABLE_YES:
return true
case USER_DEPARTMENT_ENABLE_NO:
return false
}
return false
}
func (t *UserDepartment) ValidCompanyDepart() error {
depart, err := GetDepartmentById(t.DepartmentId)
if err != nil {
return err
}
if depart.CompanyId != t.CompanyId {
e := fmt.Errorf(" depart.CompanyId != param.CompanyId ")
return e
}
return nil
}
func init() {
orm.RegisterModel(new(UserDepartment))
}
... ... @@ -34,7 +62,7 @@ func AddUserDepartment(m *UserDepartment) (id int64, err error) {
// GetUserDepartmentById retrieves UserDepartment by Id. Returns error if
// Id doesn't exist
func GetUserDepartmentById(id int) (v *UserDepartment, err error) {
func GetUserDepartmentById(id int64) (v *UserDepartment, err error) {
o := orm.NewOrm()
v = &UserDepartment{Id: id}
if err = o.Read(v); err == nil {
... ... @@ -60,7 +88,7 @@ func UpdateUserDepartmentById(m *UserDepartment) (err error) {
// DeleteUserDepartment deletes UserDepartment by Id and returns error if
// the record to be deleted doesn't exist
func DeleteUserDepartment(id int) (err error) {
func DeleteUserDepartment(id int64) (err error) {
o := orm.NewOrm()
v := UserDepartment{Id: id}
// ascertain id exists in the database
... ...
... ... @@ -8,18 +8,46 @@ import (
)
type UserPosition struct {
Id int `orm:"column(id);pk" description:"唯一键值"`
Id int64 `orm:"column(id);pk" description:"唯一键值"`
UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"`
PositionId int `orm:"column(position_id)" description:"表position.id 职位编号"`
PositionId int64 `orm:"column(position_id)" description:"表position.id 职位编号"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
CompanyId int `orm:"column(company_id)" description:"表company.id 公司编号"`
EnableStatus int8 `orm:"column(enable_status);null" description:"是否有效 1:有效 0:无效"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
EnableStatus int8 `orm:"column(enable_status);null" description:"是否有效 1:有效 2:无效"`
}
func (t *UserPosition) TableName() string {
return "user_position"
}
//EnableStatus 是否有效
const (
USER_POSITION_ENABLE_YES int8 = 1 //有效
USER_POSITION_ENABLE_NO int8 = 2 //无效
)
func (t *UserPosition) IsEnable() bool {
switch t.EnableStatus {
case USER_POSITION_ENABLE_YES:
return true
case USER_POSITION_ENABLE_NO:
return false
}
return false
}
func (t *UserPosition) ValidCompanyPosition() error {
depart, err := GetPositionById(t.PositionId)
if err != nil {
return err
}
if depart.CompanyId != t.CompanyId {
e := fmt.Errorf(" position.CompanyId != param.CompanyId ")
return e
}
return nil
}
func init() {
orm.RegisterModel(new(UserPosition))
}
... ... @@ -34,7 +62,7 @@ func AddUserPosition(m *UserPosition) (id int64, err error) {
// GetUserPositionById retrieves UserPosition by Id. Returns error if
// Id doesn't exist
func GetUserPositionById(id int) (v *UserPosition, err error) {
func GetUserPositionById(id int64) (v *UserPosition, err error) {
o := orm.NewOrm()
v = &UserPosition{Id: id}
if err = o.Read(v); err == nil {
... ... @@ -60,7 +88,7 @@ func UpdateUserPositionById(m *UserPosition) (err error) {
// DeleteUserPosition deletes UserPosition by Id and returns error if
// the record to be deleted doesn't exist
func DeleteUserPosition(id int) (err error) {
func DeleteUserPosition(id int64) (err error) {
o := orm.NewOrm()
v := UserPosition{Id: id}
// ascertain id exists in the database
... ...
package models
import (
"fmt"
"github.com/astaxie/beego/orm"
)
type UserRole struct {
Id int `orm:"column(id);pk"`
RoleId int64 `orm:"column(role_id)"`
UserId int64 `orm:"column(user_id)"`
EnableStatus int8 `orm:"column(enable_status)" description:"是否有效"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
}
func (t *UserRole) TableName() string {
return "user_role"
}
//EnableStatus 是否有效
const (
USER_ROLE_ENABLE_YES int8 = 1 //有效
USER_ROLE_ENABLE_NO int8 = 2 //无效
)
func (t *UserRole) IsEnable() bool {
switch t.EnableStatus {
case USER_ROLE_ENABLE_YES:
return true
case USER_ROLE_ENABLE_NO:
return false
}
return false
}
func (t *UserRole) ValidCompanyRole() error {
depart, err := GetRoleById(t.RoleId)
if err != nil {
return err
}
if depart.CompanyId != t.CompanyId {
e := fmt.Errorf("role.CompanyId != param.CompanyId ")
return e
}
return nil
}
func init() {
orm.RegisterModel(new(UserRole))
}
// AddUserRole insert a new UserRole into database and returns
// last inserted Id on success.
func AddUserRole(m *UserRole) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetUserRoleById retrieves UserRole by Id. Returns error if
// Id doesn't exist
func GetUserRoleById(id int) (v *UserRole, err error) {
o := orm.NewOrm()
v = &UserRole{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateUserRole updates UserRole by Id and returns error if
// the record to be updated doesn't exist
func UpdateUserRoleById(m *UserRole) (err error) {
o := orm.NewOrm()
v := UserRole{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteUserRole deletes UserRole by Id and returns error if
// the record to be deleted doesn't exist
func DeleteUserRole(id int) (err error) {
o := orm.NewOrm()
v := UserRole{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&UserRole{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
... ... @@ -2,8 +2,8 @@ package protocol
//RequestPageInfo 分页获取数据
type RequestPageInfo struct {
PageIndex int `json:"page"`
PageSize int `json:"pageSize"`
PageIndex int `json:"page_index"`
PageSize int `json:"page_size"`
}
//ResponsePageInfo 分页信息
... ...
... ... @@ -70,6 +70,7 @@ type RequestPositionDelete struct {
IDs []int64 `json:"ids"`
}
//RequestUserAdd 添加用户
type RequestUserAdd struct {
Name string `json:"name"`
CompanyId int64 `json:"company_id"`
... ... @@ -79,7 +80,29 @@ type RequestUserAdd struct {
Roles []int64 `json:"roles"`
}
//RequestUserEdit 编辑用户
type RequestUserEdit struct {
ID int64 `json:"id"`
RequestUserAdd
}
//RequestUserList 获取用户列表
type RequestUserList struct {
RequestPageInfo
NickName string `json:"nick_name"`
}
//ResponseUserList 响应的用户列表
type ResponseUserList struct {
ResponsePageInfo
List []UserListItem `json:"list"`
}
type UserListItem struct {
Id int64 `json:"id"`
NickName string `json:"nick_name"`
Position string `json:"position"`
Role string `json:"role"`
Department string `json:"department"`
Status int8 `json:"status"`
}
... ...
package protocol
import (
"encoding/json"
)
//CustomErrParse 解析自定义错误结构体
type CustomErrParse interface {
ParseToMessage() *ResponseMessage
... ... @@ -72,8 +68,8 @@ func NewErrWithMessage(code string, eRR ...error) *ErrWithMessage {
//Error 实现接口error 中的方法
//将ErrorCode转为json数据,建议用于日志记录
func (e ErrWithMessage) Error() string {
bt, _ := json.Marshal(e.ErrorCode)
return string(bt)
return e.Errmsg
}
//Unwrap 接口实现
... ...
... ... @@ -17,6 +17,10 @@ var errmessge ErrorMap = map[string]string{
"10025": "该账号已在其他地方登录",
"10026": "登录凭证过期",
"10027": "无操作权限",
//用户相关
"10031": "无效角色",
"10032": "无效部门",
"10033": "无效职位",
}
//错误码转换 ,兼容需要
... ...
... ... @@ -34,6 +34,12 @@ func init() {
beego.NSRouter("/role_group/delete", &controllers.RbacController{}, "post:RoleGroupDelete"),
beego.NSRouter("/role", &controllers.RbacController{}, "get:RoleList"),
),
beego.NSNamespace("/user/",
// beego.NSRouter("/list", &controllers.CompanyController{}, "post:UserList"),
beego.NSRouter("/add", &controllers.CompanyController{}, "post:UserAdd"),
beego.NSRouter("/edit", &controllers.CompanyController{}, "post:UserEdit"),
// beego.NSRouter("/delete", &controllers.CompanyController{}, "post:PositionDelete"),
),
beego.NSNamespace("/auth",
beego.NSRouter("/change_company", &controllers.AuthController{}, "post:ChangeCompany"),
beego.NSRouter("/refresh_token", &controllers.AuthController{}, "get:RefreshToken"),
... ...
... ... @@ -43,44 +43,44 @@ func validatePassword(from, to string) bool {
//LoginAuth 登录认证
//TODO 登录校验逻辑修改
func LoginAuthByPassword(account, password string) (protocol.LoginAuthToken, error) {
var (
user *models.User
companys []models.Company
mcompany models.Company
loginToken protocol.LoginAuthToken
err error
)
user, err = models.GetUserByPhone(account)
if err != nil {
log.Error(err.Error())
return loginToken, protocol.NewErrWithMessage("10021", err)
}
if ok := validatePassword(password, user.Passwd); !ok {
return loginToken, protocol.NewErrWithMessage("10021", err)
}
if ok := user.IsEnable(); !ok {
return loginToken, protocol.NewErrWithMessage("10022")
}
companys, err = models.GetCompanyByUser(user.Id)
if err != nil {
e := fmt.Errorf("GetCompanyByUser(%d) err:%s", user.Id, err)
log.Error(e.Error())
return loginToken, protocol.NewErrWithMessage("1")
}
if len(companys) <= 0 {
log.Error("can not found company")
return loginToken, protocol.NewErrWithMessage("1")
}
mcompany = companys[0]
loginToken, err = GenerateAuthToken(user.Id, mcompany.Id)
if err != nil {
e := fmt.Errorf("GenerateAuthToken err:%s", err)
log.Error(e.Error())
return loginToken, protocol.NewErrWithMessage("1")
}
return loginToken, nil
}
// func LoginAuthByPassword(account, password string) (protocol.LoginAuthToken, error) {
// var (
// user *models.User
// companys []models.Company
// mcompany models.Company
// loginToken protocol.LoginAuthToken
// err error
// )
// user, err = models.GetUserByPhone(account)
// if err != nil {
// log.Error(err.Error())
// return loginToken, protocol.NewErrWithMessage("10021", err)
// }
// if ok := validatePassword(password, user.Passwd); !ok {
// return loginToken, protocol.NewErrWithMessage("10021", err)
// }
// if ok := user.IsEnable(); !ok {
// return loginToken, protocol.NewErrWithMessage("10022")
// }
// companys, err = models.GetCompanyByUser(user.Id)
// if err != nil {
// e := fmt.Errorf("GetCompanyByUser(%d) err:%s", user.Id, err)
// log.Error(e.Error())
// return loginToken, protocol.NewErrWithMessage("1")
// }
// if len(companys) <= 0 {
// log.Error("can not found company")
// return loginToken, protocol.NewErrWithMessage("1")
// }
// mcompany = companys[0]
// loginToken, err = GenerateAuthToken(user.Id, mcompany.Id)
// if err != nil {
// e := fmt.Errorf("GenerateAuthToken err:%s", err)
// log.Error(e.Error())
// return loginToken, protocol.NewErrWithMessage("1")
// }
// return loginToken, nil
// }
//ResetLoginToken token存数据库
func ResetLoginToken(loginToken protocol.LoginAuthToken) error {
... ... @@ -236,6 +236,10 @@ func LoginAuthByUCenter(account, password string) (protocol.LoginAuthToken, erro
log.Debug("GetUserByPhone(%s) err:%s", account, err)
return logintoken, protocol.NewErrWithMessage("10021")
}
if ok := userdata.IsDelete(); ok {
log.Debug("userdata.IsDelete()==true")
return logintoken, protocol.NewErrWithMessage("10021")
}
if ok := userdata.IsEnable(); !ok {
log.Debug("userdata.IsEnable()==false")
return logintoken, protocol.NewErrWithMessage("10021")
... ...
... ... @@ -5,83 +5,343 @@ import (
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/utils"
"time"
"github.com/astaxie/beego/orm"
)
func UserAdd(param protocol.RequestUserAdd) error {
var (
// user models.User
// userRoles []models.RoleRelated
// userPositions []models.UserPosition
// userDeparts []models.UserPosition
userm *models.User
err error
)
//校验角色
validCompanyRole(param.CompanyId, param.Roles)
err = validCompanyRole(param.CompanyId, param.Roles)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10031")
}
//校验部门
validCompanyDepart(param.CompanyId, param.Departments)
err = validCompanyDepart(param.CompanyId, param.Departments)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10032")
}
//校验职位
validCompanyPositions(param.CompanyId, param.Positions)
//添加用户
err = validCompanyPosition(param.CompanyId, param.Positions)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10033")
}
userm = &models.User{
NickName: param.Name,
Phone: param.Phone,
}
o := orm.NewOrm()
o.Begin()
err = registUser(userm, param.CompanyId, o)
if err != nil {
o.Rollback()
log.Error("registUser err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加角色
err = editUserRole(userm.Id, param.CompanyId, param.Roles, o)
if err != nil {
o.Rollback()
log.Error("editUserRole err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加部门
err = editUserDepart(userm.Id, param.CompanyId, param.Departments, o)
if err != nil {
o.Rollback()
log.Error("editUserDepart err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加职位
err = editUserDepart(userm.Id, param.CompanyId, param.Positions, o)
if err != nil {
o.Rollback()
log.Error("editUserDepart err:%s", err)
return protocol.NewErrWithMessage("1")
}
o.Commit()
return nil
}
func validCompanyRole(companyid int64, roleid []int64) error {
var (
err error
)
for _, v := range roleid {
ur := models.UserRole{
CompanyId: companyid,
RoleId: v,
EnableStatus: models.USER_ROLE_ENABLE_YES,
}
err = ur.ValidCompanyRole()
if err != nil {
e := fmt.Errorf("ValidCompanyRole err:%s [company:%d,role:%d]", err, companyid, v)
log.Error(e.Error())
return protocol.NewErrWithMessage("10031")
}
}
return nil
}
func validCompanyRole(companyId int64, roleIds []int64) error {
for _, v := range roleIds {
role, err := models.GetRoleById(v)
func validCompanyDepart(companyid int64, departid []int64) error {
var (
err error
)
for _, v := range departid {
ud := models.UserDepartment{
CompanyId: companyid,
DepartmentId: v,
EnableStatus: models.USER_DEPARTMENT_ENABLE_YES,
}
err = ud.ValidCompanyDepart()
if err != nil {
e := fmt.Errorf("GetRoleById(%d) err:%s", v, err)
e := fmt.Errorf("ValidCompanyDepart err:%s [company:%d,department:%d]", err, companyid, v)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", err)
return protocol.NewErrWithMessage("10032")
}
}
return nil
}
func validCompanyPosition(companyid int64, positionid []int64) error {
var (
err error
)
for _, v := range positionid {
ud := models.UserPosition{
CompanyId: companyid,
PositionId: v,
EnableStatus: models.USER_DEPARTMENT_ENABLE_YES,
}
if role.CompanyId != companyId {
e := fmt.Errorf(" role.CompanyId != param.CompanyId ")
err = ud.ValidCompanyPosition()
if err != nil {
e := fmt.Errorf("ValidCompanyPosition err:%s [company:%d,department:%d]", err, companyid, v)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", err)
return protocol.NewErrWithMessage("10033")
}
}
return nil
}
func validCompanyDepart(companyId int64, departIds []int64) error {
for _, v := range departIds {
depart, err := models.GetDepartmentById(v)
//registUser 注册用户
func registUser(userIn *models.User, companyid int64, o orm.Ormer) error {
var (
err error
// usrData *models.User
)
_, err = models.GetUserByPhone(userIn.Phone)
if err == nil {
return nil
}
if err != nil && err != orm.ErrNoRows {
return err
}
if err == orm.ErrNoRows {
_, err := models.AddUser(userIn, o)
if err != nil {
e := fmt.Errorf("GetDepartmentById(%d) err:%s", v, err)
return err
}
}
musercompany := &models.UserCompany{
CompanyId: companyid,
UserId: userIn.Id,
}
_, err = models.AddUserCompany(musercompany, o)
if err != nil {
return err
}
//更新
return nil
}
func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Ormer) error {
var (
oldDepartIds []int64
err error
delDepartIds []int64
addDepartIds []int64
)
dataSql := `SELECT department_id FROM user_department WHERE enable_status=1 AND company_id=? AND user_id=?`
dataSql2 := `UPDATE user_department SET enable_status = 2 WHERE company_id = ? AND user_id=? AND department_id=?`
datasql3 := `INSERT INTO user_department (user_id,department_id,company_id,enable_status,create_at) VALUES (?,?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldDepartIds, dataSql, companyid, userid)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", err)
return e
}
if depart.CompanyId != companyId {
e := fmt.Errorf(" depart.CompanyId != param.CompanyId ")
delDepartIds = utils.ArrayInt64Diff(oldDepartIds, departids)
addDepartIds = utils.ArrayInt64Diff(departids, oldDepartIds)
for _, v := range delDepartIds {
err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return e
}
}
nowTime := time.Now().String()
for _, v := range addDepartIds {
err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", err)
return e
}
}
return nil
}
func validCompanyPositions(companyId int64, positionIds []int64) error {
for _, v := range positionIds {
pos, err := models.GetPositionById(v)
func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.Ormer) error {
var (
oldPositionIds []int64
err error
delPositionIds []int64
addPositionIds []int64
)
dataSql := `SELECT position_id FROM user_position WHERE enable_status=1 AND company_id=? AND user_id=?`
dataSql2 := `UPDATE user_position SET enable_status = 2 WHERE company_id = ? AND user_id=? AND position_id=?`
datasql3 := `INSERT INTO user_position (user_id,position_id,company_id,enable_status,create_at) VALUES (?,?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldPositionIds, dataSql, companyid, userid)
if err != nil {
e := fmt.Errorf("GetDepartmentById(%d) err:%s", v, err)
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", err)
return e
}
if pos.CompanyId != companyId {
e := fmt.Errorf("pos.CompanyId != pos.CompanyId")
delPositionIds = utils.ArrayInt64Diff(oldPositionIds, positionids)
addPositionIds = utils.ArrayInt64Diff(positionids, oldPositionIds)
for _, v := range delPositionIds {
err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return e
}
}
nowTime := time.Now().String()
for _, v := range addPositionIds {
err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", err)
return e
}
}
return nil
}
func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) error {
var (
oldRoleIds []int64
err error
delRoleIds []int64
addRoleIds []int64
)
dataSql := `SELECT role_id FROM user_role WHERE enable_status=1 AND company_id=? AND user_id=?`
dataSql2 := `UPDATE user_position SET enable_status = 2 WHERE company_id =? AND user_id=? AND role_id=?`
datasql3 := `INSERT INTO user_role (user_id,role_id,company_id,enable_status) VALUES (?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldRoleIds, dataSql, companyid, userid)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return e
}
delRoleIds = utils.ArrayInt64Diff(oldRoleIds, roleids)
addRoleIds = utils.ArrayInt64Diff(roleids, oldRoleIds)
for _, v := range delRoleIds {
err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return e
}
}
for _, v := range addRoleIds {
err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
return e
}
}
return nil
}
func UserEdit(param protocol.RequestUserEdit) error {
var (
userm *models.User
err error
)
//校验角色
err = validCompanyRole(param.CompanyId, param.Roles)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10031")
}
//校验部门
err = validCompanyDepart(param.CompanyId, param.Departments)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10032")
}
//校验职位
err = validCompanyPosition(param.CompanyId, param.Positions)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10033")
}
userm = &models.User{
Id: param.ID,
NickName: param.Name,
Phone: param.Phone,
}
o := orm.NewOrm()
o.Begin()
// err = registUser(userm, param.CompanyId, o)
// if err != nil {
// o.Rollback()
// log.Error("registUser err:%s", err)
// return protocol.NewErrWithMessage("1")
// }
//添加角色
err = editUserRole(userm.Id, param.CompanyId, param.Roles, o)
if err != nil {
o.Rollback()
log.Error("editUserRole err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加部门
err = editUserDepart(userm.Id, param.CompanyId, param.Departments, o)
if err != nil {
o.Rollback()
log.Error("editUserDepart err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加职位
err = editUserDepart(userm.Id, param.CompanyId, param.Positions, o)
if err != nil {
o.Rollback()
log.Error("editUserDepart err:%s", err)
return protocol.NewErrWithMessage("1")
}
o.Commit()
return nil
}
func UserDelete(param protocol.RequestUserAdd) error {
return nil
}
func UserList() error {
return nil
}
... ...
... ... @@ -9,6 +9,9 @@ type ArrayCmpare interface {
//ArrayInt64Diff 返回切片的差集:arr1-arr2
func ArrayInt64Diff(arr1 []int64, arr2 []int64) []int64 {
if len(arr2) == 0 {
return arr1
}
setmap := make(map[int64]bool)
for i := range arr2 {
setmap[arr1[i]] = true
... ...
package exceltool
import (
"errors"
"fmt"
"math/rand"
"time"
excelize "github.com/360EntSecGroup-Skylar/excelize/v2"
"github.com/astaxie/beego/orm"
)
//(新)ExcelMaker 构建excel文档
type ExcelMaker struct {
Xlsx *excelize.File
FileName string
}
//NewExcelMaker ....
func NewExcelMaker() *ExcelMaker {
return &ExcelMaker{
Xlsx: excelize.NewFile(),
}
}
//MakeListExcel 根据列表形式的数据创建excel文档
//@sourData []map[string]string; 原始数据,要输入excel文档的数据
//@xlsxHeader [][]string{ {"数据字段英文名",""excel字段中文描述"},{"数据字段英文名",""excel字段中文描述"} }
func (e *ExcelMaker) MakeListExcel(sourData []map[string]string, xlsxHeader [][]string) (err error) {
if len(xlsxHeader) == 0 {
return errors.New("xlsHeader 数据格式错误")
}
headEn := []string{} //数据字段英文名
headCn := []string{} //excel字段中文描述
alphaSlice := []string{} //excel列字母索引
for key, val := range xlsxHeader {
if len(val) != 2 {
return errors.New("xlsHeader 数据格式错误")
}
headEn = append(headEn, xlsxHeader[key][0])
headCn = append(headCn, xlsxHeader[key][1])
alpha, err := excelize.ColumnNumberToName(key)
if err != nil {
return err
}
alphaSlice = append(alphaSlice, alpha)
}
//设置excel文档第一行的字段中文描述
for index, _ := range headCn {
//索引转列名,索引从0开始
cellAlpha := fmt.Sprintf("%s%d", alphaSlice[index], 1) // 单元格行坐标从1开始,如:a1,指第一行a列。
e.Xlsx.SetCellStr("Sheet1", cellAlpha, headCn[index])
}
//从excel第二行开始设置实际数据的值
for key1, _ := range sourData {
for i := 0; i < len(headEn); i++ {
cellAlpha := fmt.Sprintf("%s%d", alphaSlice[i], key1+2) // 单元格行坐标从1开始,如:a1,指第一行a列。
e.Xlsx.SetCellStr("Sheet1", cellAlpha, sourData[key1][headEn[i]])
}
}
e.FileName = GetRandomString(8) + ".xlsx"
return nil
}
//MakeListExcel 根据数据创建列表形式的excel文档
//@sourData []orm.Params; 原始数据,要输入excel文档的数据
//@xlsxHeader [][]string{ {"数据字段英文名",""excel字段中文描述"},{"数据字段英文名",""excel字段中文描述"} }
func (e *ExcelMaker) MakeListExcelForBeego(sourData []orm.Params, xlsxHeader [][]string) (err error) {
if len(xlsxHeader) == 0 {
return errors.New("xlsHeader 数据格式错误")
}
headEn := []string{} //数据字段英文名
headCn := []string{} //excel字段中文描述
alphaSlice := []string{} //excel列字母索引
for key, val := range xlsxHeader {
if len(val) != 2 {
return errors.New("xlsHeader 数据格式错误")
}
headEn = append(headEn, xlsxHeader[key][0])
headCn = append(headCn, xlsxHeader[key][1])
alpha, err := excelize.ColumnNumberToName(key)
if err != nil {
return err
}
alphaSlice = append(alphaSlice, alpha)
}
//设置excel文档第一行的字段中文描述
for index, _ := range headCn {
//索引转列名,索引从0开始
cellAlpha := fmt.Sprintf("%s%d", alphaSlice[index], 1) // 单元格行坐标从1开始,如:a1,指第一行a列。
e.Xlsx.SetCellStr("Sheet1", cellAlpha, headCn[index])
}
//从excel第二行开始设置实际数据的值
for key1, _ := range sourData {
for i := 0; i < len(headEn); i++ {
cellAlpha := fmt.Sprintf("%s%d", alphaSlice[i], key1+2) // 单元格行坐标从1开始,如:a1,指第一行a列。
if sourData[key1][headEn[i]] == nil {
sourData[key1][headEn[i]] = ""
}
e.Xlsx.SetCellStr("Sheet1", cellAlpha, fmt.Sprintf("%s", sourData[key1][headEn[i]]))
}
}
e.FileName = GetRandomString(8) + ".xlsx"
return nil
}
//生成随机字符串
func GetRandomString(lenght int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes := []byte(str)
result := []byte{}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < lenght; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
return string(result)
}
... ...