Commit 1af36708 by zhangjie

1

parent ad253400
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/data_db_cache/dbcurd/u_we_customer.go" dialect="GenericSQL" />
<file url="PROJECT" dialect="PostgreSQL" />
</component>
</project>
\ No newline at end of file
c18e885783a60274ab3edc848f6ef538
\ No newline at end of file
package api_admin
//// CreateArea 创建一个学校
//// @Tags 管理后台
//// @Summary 创建一个学校
//// @Description 目前仅用于填充数据,暂未做权限校验
//// @Accept json
//// @Produce json
//// @Param data body dbcurd.TableBaseArea true "学校信息"
//// @Success 0 {object} integer
//// @Router /ad/area [POST]
//// @Security ApiKeyAuth
//func CreateArea(c *gin.Context) {
// var reqData dbcurd.TableBaseArea
// err := c.ShouldBindJSON(&reqData)
// if err != nil {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqParaFormat,
// "message": api.CodeMsg[api.ErrorReqParaFormat],
// })
// return
// }
// if reqData.CountyID == 0 || reqData.CountyID < 543 || reqData.CountyID > 3423 { // todoN 这里最好改成动态调整的
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqPara,
// "message": api.CodeMsg[api.ErrorReqPara] + " county_id不正确",
// })
// return
// }
//
// insertRes := dbcurd.InsertBaseArea(&reqData) //插入数据库
// if insertRes == 1 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqInsertDuplicate,
// "data": api.CodeMsg[api.ErrorReqInsertDuplicate] + "(名字不可重复)",
// })
// return
// } else if insertRes == 9 || reqData.ID == 0 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemErr,
// "data": api.CodeMsg[api.ErrorSystemErr],
// })
// return
// }
//
// areaList := cache.GetCountyAreaMap(reqData.CountyID)
// areaList = append(areaList, reqData.ID)
// cache.CountyAreaMap.Store(reqData.CountyID, areaList) // 更新CountyAreaMap
// cache.AreaMap.Store(reqData.ID, model.CacheBAreaStruct{ // AreaMap缓存,添加该校区
// Name: reqData.Name,
// Longitude: reqData.Longitude,
// Latitude: reqData.Latitude,
// // CountyID: reqData.CountyID,
// Status: reqData.Status,
// })
//
// c.JSON(http.StatusOK, gin.H{
// "code": api.Success,
// "data": reqData.ID,
// })
//}
package api_cache
//// GetCacheBDistrictMap 获取行政区域缓存
//// @Tags 管理后台
//// @Summary 测试用
//// @Description 先返回所有数据再说
//// -- @Param provinceID path integer true "省份id"
//// @Product json
//// -- @Success 0 {object} []cache.DistrictStruct "按首字母排序好的列表,可直接用作展示"
//// @Router /base/city/{provinceID} [GET]
//// @Security ApiKeyAuth
//func GetCacheBDistrictMap(c *gin.Context) {
// para, _ := strconv.ParseUint(c.Param("id"),10,32)
// v, _ := cache.CityMap.Load(uint32(para)) // 如果查不到就直接返回空data
// // data, _ := v.([]cache.DistrictStruct)
// c.JSON(http.StatusOK, gin.H{
// "code": api.Success,
// "data": v,
// })
//}
package api_cache
//// GetCacheBDistrictMap 获取行政区域缓存
//// @Tags 管理后台
//// @Summary 测试用
//// @Description 先返回所有数据再说
//// -- @Param provinceID path integer true "省份id"
//// @Product json
//// -- @Success 0 {object} []cache.DistrictStruct "按首字母排序好的列表,可直接用作展示"
//// @Router /base/city/{provinceID} [GET]
//// @Security ApiKeyAuth
//func GetCacheBDistrictMap(c *gin.Context) {
// para, _ := strconv.ParseUint(c.Param("id"),10,32)
// v, _ := cache.CityMap.Load(uint32(para)) // 如果查不到就直接返回空data
// // data, _ := v.([]cache.DistrictStruct)
// c.JSON(http.StatusOK, gin.H{
// "code": api.Success,
// "data": v,
// })
//}
package api_cache
//// GetCountyAreaMap 获取行政区域缓存
//// @Tags 管理后台
//// @Summary 测试用
//// @Description 先返回所有数据再说
//// -- @Param provinceID path integer true "省份id"
//// @Product json
//// -- @Success 0 {object} []cache.DistrictStruct "按首字母排序好的列表,可直接用作展示"
//// @Router /base/city/{provinceID} [GET]
//// @Security ApiKeyAuth
//func GetCountyAreaMap(c *gin.Context) {
// para, _ := strconv.ParseUint(c.Param("id"),10,32)
// v, _ := cache.CityMap.Load(uint32(para)) // 如果查不到就直接返回空data
// // data, _ := v.([]cache.DistrictStruct)
// c.JSON(http.StatusOK, gin.H{
// "code": api.Success,
// "data": v,
// })
//}
......@@ -3,7 +3,6 @@ package api_public
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
......@@ -22,7 +21,7 @@ import (
func GetProvinceList(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": cache.ProvinceMap,
"data": cache.GetProvinceMap(),
})
}
......@@ -72,7 +71,9 @@ type countyAreaRes struct {
// GetAreaByCounty 根据区县ID获取学校列表
// @Tags 公用接口
// @Summary 根据区县ID获取学校列表 [complete]
// @Description 根据区县ID获取学校列表
// @Description 1.根据区县ID查询{区县学校列表缓存 countyAreaMap}[]校区ID
// @Description 2.根据微信用户ID查询{微信用户缓存 wechatCustomerMap.TestRole}获取是否有测试校区权限
// @Description 3.遍历 []校区ID 查询WechatCustomerMap.TestRole满足的{校区缓存 areaMap.Name}
// @Param countyID path integer true "区县id" default(2725)
// @Product json
// @Success 0 {object} []countyAreaRes "排序好的学校列表,可直接用作展示"
......@@ -125,24 +126,18 @@ func GetAreaByCounty(c *gin.Context) {
})
}
type locationAreaRes struct {
Name string `json:"name" example:"海科学校"`
District string `json:"district" example:"四川省成都市温江区"`
ID int `json:"id" example:"1"`
}
// GetAreaByLocation 根据经纬度获取附近学校列表
// @Tags 公用接口
// @Summary 根据经纬度获取附近20所学校列表 [can test]
// @Summary 根据经纬度获取附近20所学校列表[complete]
// @Description 根据经纬度获取附近20所学校列表
// @Param longitude query integer true "经度*1000000" default(103000000)
// @Param latitude query integer true "纬度*1000000" default(30000000)
// @Product json
// @Success 0 {object} []locationAreaRes "排序好的学校列表,可直接用作展示"
// @Success 0 {object} cache.LocList "排序好的学校列表,可直接用作展示"
// @Router /base/locarea [GET]
// @Security ApiKeyAuth
func GetAreaByLocation(c *gin.Context) {
longitude, err := strconv.Atoi(c.Query("longitude"))
longitude, err := strconv.ParseInt(c.Query("longitude"), 10, 32) //strconv.Atoi(c.Query("longitude"))
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 2001,
......@@ -157,7 +152,7 @@ func GetAreaByLocation(c *gin.Context) {
})
return
}
latitude, err := strconv.Atoi(c.Query("latitude"))
latitude, err := strconv.ParseInt(c.Query("latitude"), 10, 32) //strconv.Atoi(c.Query("latitude"))
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 2001,
......@@ -173,20 +168,27 @@ func GetAreaByLocation(c *gin.Context) {
return
}
var data []locationAreaRes
v, _ := cache.AreaMap.Load(uint32(14)) // todo 根据经纬度计算距离 还要看status 和 用户的权限
if a, ok := v.(model.CacheBAreaStruct); ok { //类型断言正确
data = append(data, locationAreaRes{
a.Name,
"温江区",
14,
userID, ok := c.Get("userID")
if ok == false {
logger.Log.Error("userID在Context里面居然没填对,遇到鬼了",
zap.String("Src", "GetAreaByLocation"))
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
testRole, ok := cache.GetWechatCustomerTestRole(userID.(uint32))
if ok == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTokenWrong,
"message": api.CodeMsg[api.ErrorTokenWrong],
})
} else {
cache.AreaMap.Delete(uint32(14))
return
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": data,
"data": cache.GetAreaIdAndNameListByLocAndTestRole(longitude, latitude, testRole),
})
}
package api_server_ops
import (
"dc_golang_server_1/api"
"dc_golang_server_1/dev_product/dcphone20"
"dc_golang_server_1/logger"
"dc_golang_server_1/util"
"github.com/gin-gonic/gin"
"net/http"
)
type apiGetSystemRunParaStruct struct {
util.Server
PhoneTcpSocketNo int32 `json:"phoneSocketNo"` // 电话机Socket连接数
HttpReqNo int32 `json:"httpReqNo"` // 当前http请求数
}
// GetSystemRunPara 获取当前程序运行状态
// @Tags 运维-系统状态
// @Summary 获取当前系统运行状态
// @Description 返回当前系统运行状态
// @Product json
// @Success 0 {object} apiGetSystemRunParaStruct "系统运行状态"
// @Router /serverops/sysstate [GET]
// @Security ApiKeyAuth
func GetSystemRunPara(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ // todo 这个接口改成ADMIN的token调用,然后改成不要server的东西,供后台调用
"code": api.Success,
"data": apiGetSystemRunParaStruct{
util.Server{
Os: util.GetOSInfo(),
Cpu: util.GetCpuInfo(),
Ram: util.GetRamInfo(),
Disk: util.GetDiskInfo(),
},
dcphone20.TCP.ConnSocketCount,
logger.GinHttpReqNum,
},
})
}
// todo 暂停web响应,传递同意messge过来,gin都直接返回这个message 同时这个接口可开启正常响应
// todo 暂停硬件链接并关闭所有的socket 同时这个接口可开启正常链接
// todo 停止服务,通过1个channel到主函数,如果停止,等所有web响应结束了停止
\ No newline at end of file
package api_we
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
"strconv"
"time"
)
//type getPhoneCardStatusRes struct {
// Status uint8 // 状态 0未绑定卡 1 正常使用 2 服务已到期 3 已挂失
// SimID string `json:"simID"` // 卡号
// ExpiryAt time.Time // 到期时间
// MonthMin uint16 `json:"monthMin"` // 月套餐使用分钟数
// MonthPack uint16 `json:"monthPack"` // 月套餐分钟数
// Changeable uint8 `json:"changeable"` // 本月可修改亲情号次数
// Family []familyNumStruct `json:"family"` // 亲情号列表
//}
type getPhoneCardStatusRes struct {
SimID string `json:"simID"` // 卡号
model.CacheSimInfoStruct
}
// GetPhoneCardStatus 获取学生公话卡状态
// @Tags 家长微信
// @Summary 获取学生公话卡状态(含亲情号信息) [complete]
// @Description 传学生ID至后台,后台返回卡状态
// @Produce json
// @Param id path integer true "学生ID"
// @Success 0 {object} getPhoneCardStatusRes "公话卡状态信息"
// @Router /we/phonecardstatus/{id} [GET]
// @Security ApiKeyAuth
func GetPhoneCardStatus(c *gin.Context) {
cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
cardUserID := uint32(cardUserIDInt)
if cardUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " id不正确",
})
return
}
// 取微信用户
v, ok := c.Get("userID")
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("GetCardUserTrend",
zap.Reflect("c.Get(\"userID\")", v))
return
}
// 校验weUserID是否有cardUserID权限
if cache.CheckCardUserMaserAndSlaveWeID(cardUserID, weUserID) < 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
})
return
}
// 查出该学生信息
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
if cardUserInfo.SimCardID == "" {
c.JSON(
http.StatusOK,
gin.H{
"code": api.Success,
"data": getPhoneCardStatusRes{}, //学生未绑卡
},
)
return
}
res := cache.GetSimInfo(cardUserInfo.SimCardID)
// 服务已过期
if time.Now().After(res.ExpiryAt) && res.Status == 1 {
res.Status = 3
}
if res != nil {
c.JSON(
http.StatusOK,
gin.H{
"code": api.Success,
"data": getPhoneCardStatusRes{
cardUserInfo.SimCardID,
*res,
},
},
)
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
}
}
package api_we
package api_we_card_operate
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
......@@ -17,7 +19,7 @@ type apiCardBindStruct struct {
}
// CardBind 绑定卡
// @Tags 家长微信
// @Tags 家长微信-卡操作
// @Summary 绑定卡 [complete]
// @Description 传学生id及卡类型、卡号至后台,后台返回成功失败
// @Produce json
......@@ -42,8 +44,8 @@ func CardBind(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("CardBind",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -54,8 +56,8 @@ func CardBind(c *gin.Context) {
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r < 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
......@@ -70,7 +72,7 @@ func CardBind(c *gin.Context) {
return
}
if reqData.Type != 1 {
if reqData.Type != 1 { // 校验卡类型
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " type暂时只支持1",
......@@ -78,7 +80,7 @@ func CardBind(c *gin.Context) {
return
}
if len(reqData.Code) == 0 {
if len(reqData.Code) == 0 { // 校验卡号是否为空
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " code不能为空",
......@@ -86,14 +88,14 @@ func CardBind(c *gin.Context) {
return
}
if len(cardUserInfo.SimCardID) > 0 {
if cardUserInfo.SimCardID == reqData.Code {
if len(cardUserInfo.SimCardID) > 0 { // 用户已经绑卡
if cardUserInfo.SimCardID == reqData.Code { // 用户绑定的卡是一样的,直接返回成功
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
return
}
c.JSON(http.StatusOK, gin.H{
c.JSON(http.StatusOK, gin.H{ // 用户绑的卡不一致,直接返回失败
"code": api.ErrorReqPara,
"message": "错误:已绑卡号" + cardUserInfo.SimCardID,
})
......@@ -101,7 +103,7 @@ func CardBind(c *gin.Context) {
}
// 获取sim卡信息
simInfo := cache.GetSimInfo(reqData.Code)
simInfo := cache.GetSimInfo(reqData.Code) // 根据请求的卡号,获取系统中卡的信息
if simInfo == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
......@@ -111,10 +113,13 @@ func CardBind(c *gin.Context) {
}
// 如果已经绑定了学生,则不可绑定
if simInfo.CardUserID != 0 {
if simInfo.CardUserID == cardUserID {
if simInfo.CardUserID == cardUserID { // 已经绑定的学生就是请求的学生,那学生那边的缓存就有问题,异常情况
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
logger.Log.Error("api_we_card_operate.CardBind 学生缓存没有用户卡ID,卡缓存居然有学生ID",
zap.Uint32("cardUserID", cardUserID),
zap.String("cardID", reqData.Code))
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
......@@ -123,9 +128,9 @@ func CardBind(c *gin.Context) {
}
return
}
// 校区对不上,不允许绑定
areaServiceInfo := cache.GetAreaServiceInfo(simInfo.AreaServiceID)
if areaServiceInfo == nil {
if areaServiceInfo == nil { // 请求绑定的校区服务,居然系统里面没有,异常情况
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
......@@ -134,7 +139,7 @@ func CardBind(c *gin.Context) {
zap.Uint32("simInfo.AreaServiceID", simInfo.AreaServiceID))
return
}
if areaServiceInfo.AreaID != cardUserInfo.AreaID { // 卡号跟绑定的校区不对应
if areaServiceInfo.AreaID != cardUserInfo.AreaID { // 卡在系统里面绑定的校区服务跟请求的学生所在的校区服务对不上,不允许绑定 // todo 改成区域服务,接口请求增加区域服务
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": "输入的卡号错误:非运营商绑定的本校区卡号",
......@@ -144,19 +149,23 @@ func CardBind(c *gin.Context) {
// 操作数据库
if dbcurd.UpdateUSimInfoCardUserID(reqData.Code, cardUserID) {
// CardUserMap SimInfoMap 并发不安全
cardUserInfo.SimCardID = reqData.Code
cache.CardUserMap.Store(cardUserID, *cardUserInfo) // todo 并发不安全 所有的store delete都封装一下
simInfo.CardUserID = cardUserID
cache.SimInfoMap.Store(reqData.Code, *simInfo)
// 写 cardUserMap
if cache.UpdateCardUserMap(cardUserID, &model.CacheUpdateCardUserStruct{
SimCardID: &reqData.Code,
}) {
fmt.Println("CardBind 写缓存失败", cardUserID, reqData.Code)
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
})
if cache.UpdateSimInfo(reqData.Code, &model.CacheUpdateSimInfoStruct{CardUserID: &cardUserID}) {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
return
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
}
package api_we
package api_we_card_operate
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
......@@ -17,7 +18,7 @@ type apiCardLossStruct struct {
}
// CardLoss 卡挂失/解挂
// @Tags 家长微信
// @Tags 家长微信-卡操作
// @Summary 卡挂失/解挂 [complete]
// @Description 传学生id及卡类型至后台,后台返回成功失败
// @Produce json
......@@ -42,8 +43,8 @@ func CardLoss(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("CardLoss",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -79,46 +80,43 @@ func CardLoss(c *gin.Context) {
userInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r < 2 { // 校验weUserID是否有cardUserID权限
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
//if userInfo == nil { //查不到用户信息 只要r>0,肯定不为nil
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemErr,
// "data": api.CodeMsg[api.ErrorSystemErr],
// "message": api.CodeMsg[api.ErrorSystemErr],
// })
// return
//}
if len(userInfo.SimCardID) == 0 { //用户没绑卡
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserNotHavePhoneCard,
"data": api.CodeMsg[api.ErrorUserNotHavePhoneCard],
"code": api.ErrorUserNotHavePhoneCard,
"message": api.CodeMsg[api.ErrorUserNotHavePhoneCard],
})
return
}
if dbcurd.UpdateUSimInfoStatus(userInfo.SimCardID, reqData.Loss) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
simInfo := cache.GetSimInfo(userInfo.SimCardID)
if simInfo != nil { // 这里并发不安全
simInfo.Status = reqData.Loss
cache.SimInfoMap.Store(userInfo.SimCardID, *simInfo)
if cache.UpdateSimInfo(userInfo.SimCardID, &model.CacheUpdateSimInfoStruct{Status: reqData.Loss}) {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
}
}
package api_we
package api_we_card_operate
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
......@@ -16,7 +18,7 @@ type apiDeleteCardBindStruct struct {
}
// DeleteCardBind 解绑卡
// @Tags 家长微信
// @Tags 家长微信-卡操作
// @Summary 解绑卡 [complete]
// @Description 传学生id及卡类型至后台,后台返回成功失败
// @Produce json
......@@ -41,8 +43,8 @@ func DeleteCardBind(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("CardLoss",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -53,8 +55,8 @@ func DeleteCardBind(c *gin.Context) {
cardUserInfo, role := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if role < 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
......@@ -97,17 +99,26 @@ func DeleteCardBind(c *gin.Context) {
if dbcurd.UpdateUSimInfoCardUserID(cardUserInfo.SimCardID, 0) { // 数据库将sim卡信息里对应的学生ID置0
simID := cardUserInfo.SimCardID
cardUserInfo.SimCardID = ""
cache.CardUserMap.Store(cardUserID, *cardUserInfo) // todo 并发不安全 所有的store delete都封装一下
simInfoP.CardUserID = 0
cache.SimInfoMap.Store(simID, *simInfoP)
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
})
// 写 cardUserMap
if cache.UpdateCardUserMap(cardUserID, &model.CacheUpdateCardUserStruct{
SimCardID: &cardUserInfo.SimCardID,
}) {
fmt.Println("DeleteCardBind 写缓存失败", cardUserID)
}
upCID := uint32(0)
if cache.UpdateSimInfo(simID, &model.CacheUpdateSimInfoStruct{CardUserID: &upCID}) {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
return
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
}
package api_we_card_operate
import (
"dc_golang_server_1/api"
"dc_golang_server_1/util"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
// Qr2CardID 根据二维码,返回卡号信息
// @Tags 家长微信-卡操作
// @Summary 根据二维码,返回卡号信息[complete]
// @Description 根据二维码,返回卡号信息
// @Produce json
// @Param qrcode path string true "QR内容"
// @Success 0 {object} string "卡号"
// @Router /we/qr2cardid/{qrcode} [GET]
// @Security ApiKeyAuth
func Qr2CardID(c *gin.Context) {
qrCode := c.Param("qrcode")
if len(qrCode) != 36 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " 二维码长度错误",
})
return
}
cardID,err := util.DecryptBase64URLToBytes(qrCode, "keyQR123@dcrym01")
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " 无效二维码",
})
return
}
for i:=0;i<26;i++ {
cardID[i] -= uint8(i)%3 + 0x18
}
cardID[11],cardID[25],cardID[20],cardID[22],cardID[9],cardID[24],cardID[21],cardID[12],cardID[0] = cardID[0],cardID[9],cardID[11],cardID[12],cardID[20],cardID[21],cardID[22],cardID[24],cardID[25]
if cardID[20] != 0x16 || cardID[21] != 0x11 || cardID[22] != 0x03 || !util.CheckCRC(cardID) {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " 无效二维码",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": string(cardID[:20]),
})
}
// CardID2Qr 根据卡号返回二维码
// @Tags 家长微信-卡操作
// @Summary 根据卡号返回二维码[complete]-测试用,正式上线此接口关闭或移至后台管理系统
// @Description 根据卡号返回二维码
// @Produce json
// @Param cardid path string true "cardID"
// @Success 0 {object} string "卡号"
// @Router /we/cardid2qr/{cardid} [GET]
// @Security ApiKeyAuth
func CardID2Qr(c *gin.Context) {
cardID := []byte(c.Param("cardid"))
if len(cardID) != 20 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " 卡号长度错误",
})
return
}
cardID = append(cardID,[]byte{0x16,0x11,0x03,uint8(time.Now().UnixNano()),0,0}...)
util.GetCRC(cardID,24)
cardID[0],cardID[9],cardID[11],cardID[12],cardID[20],cardID[21],cardID[22],cardID[24],cardID[25] = cardID[11],cardID[25],cardID[20],cardID[22],cardID[9],cardID[24],cardID[21],cardID[12],cardID[0]
for i:=0;i<26;i++ {
cardID[i] += uint8(i)%3 + 0x18
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": util.EncryptBytesToBase64URL(cardID, "keyQR123@dcrym01"),
})
}
\ No newline at end of file
package api_we
package api_we_login_we_info
import (
"dc_golang_server_1/api"
......@@ -12,7 +12,7 @@ import (
"time"
)
const tokenExpiryTimeS = uint32(22 * 60)
const tokenExpiryTimeS = uint32(48 * 3600)
type weLoginRes struct {
// weUserListStruct
......@@ -28,13 +28,13 @@ type weLoginReq struct {
}
// WeLogin 微信登录
// @Tags 家长微信
// @Tags 家长微信-登录及微信信息上传
// @Summary 登录(真实code) [complete]
// @Description 微信code传至后台,后台返回token,token有效时长:48小时
// @Param data body weLoginReq true "登录信息"
// @Product json
// @Success 0 {object} weLoginRes
// @Router /we/login/{code} [POST]
// @Router /we/login [POST]
func WeLogin(c *gin.Context) {
var reqData weLoginReq
err := c.ShouldBindJSON(&reqData)
......@@ -46,7 +46,7 @@ func WeLogin(c *gin.Context) {
return
}
var userID uint32
var weUserID uint32
nowTime := time.Now().UnixMicro()
var tokenInfo api.TokenResult
......@@ -55,31 +55,32 @@ func WeLogin(c *gin.Context) {
if tokenInfo.UserType == 1 {
api.CheckTokenExit(&tokenInfo)
if tokenInfo.CheckResult == api.Success {
userID = tokenInfo.UserID
weUserID = tokenInfo.UserID
}
}
}
var userInfo *model.CacheWeCustomerStruct
if userID != 0 {
userInfo = cache.GetWechatCustomerInfoAndCacheUpdateTokenTime(userID, nowTime)
//if userInfo != nil {
// dbcurd.UpdateUWeCustomerLoginTime(userID) todo 改成每天半夜来记录
//}
var weUserInfo *model.CacheWeCustomerStruct
if weUserID != 0 {
weUserInfo = cache.GetWeUserInfoFromMapAndDB(weUserID) //cache.GetWechatCustomerInfoAndCacheUpdateTokenTime(weUserID, nowTime)
cache.WechatCustomerTokenCreateTime.Store(weUserID, nowTime)
if weUserInfo != nil {
dbcurd.UpdateUWeCustomerLoginTime(weUserID) // todo 改成每天半夜来记录
}
}
if userInfo == nil { // 微信服务器登录
unionID, _, _ := tencent.WechatCode2Session(reqData.Code) //也不去校验reqData.Code长度了,对半是对的
if len(unionID) == 0 {
if weUserInfo == nil { // 微信服务器登录
unionID, openID, _ := tencent.WechatCode2Session(reqData.Code) //也不去校验reqData.Code长度了,对半是对的
if len(unionID) == 0 || len(openID) == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr],
})
return
}
userID = cache.GetWechatCustomerUserIDByUnionID(unionID)
if userID == 0 { // 原来没有,只有注册
weUserID = cache.GetWechatCustomerUserIDByUnionID(unionID)
if weUserID == 0 { // 原来没有,只有注册
var res uint8
userID, res = dbcurd.InsertUWeCustomerUnionID(unionID) //插入
weUserID, res = dbcurd.InsertUWeCustomerUnionID(unionID, openID) //插入
if res == dbcurd.InsertSysErr {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
......@@ -88,28 +89,29 @@ func WeLogin(c *gin.Context) {
return
}
if res == dbcurd.InsertDuplicate {
userInfo, userID = dbcurd.SelectUWeCustomerByUnionIDToCacheModel(unionID)
weUserInfo, weUserID = dbcurd.SelectUWeCustomerByUnionIDToCacheModel(unionID)
}
if userID == 0 {
if weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
userInfo = &model.CacheWeCustomerStruct{
TokenCreatTime: nowTime,
weUserInfo = &model.CacheWeCustomerStruct{
OpenID: openID,
}
cache.WechatCustomerUnionIDToIDMAP.Store(unionID, userID)
cache.WechatCustomerMap.Store(userID, *userInfo)
cache.CreatWechatCustomerMap(weUserID, weUserInfo) //cache.wechatCustomerMap.Store(weUserID, *weUserInfo)
cache.WechatCustomerUnionIDToIDMAP.Store(unionID, weUserID)
cache.WechatCustomerTokenCreateTime.Store(weUserID, nowTime)
} else { // 已有用户
userInfo = cache.GetWechatCustomerInfoAndCacheUpdateTokenTime(userID, nowTime)
if userInfo != nil {
// dbcurd.UpdateUWeCustomerLoginTime(userID) todo 改成每天半夜来记录
weUserInfo = cache.GetWeUserInfoFromMapAndDB(weUserID)
cache.WechatCustomerTokenCreateTime.Store(weUserID, nowTime)
if weUserInfo != nil {
dbcurd.UpdateUWeCustomerLoginTime(weUserID) // todo 改成每天半夜来记录
} else {
cache.WechatCustomerMap.Delete(userID)
fmt.Println(time.Now(), "严重错误:微信用户ID", unionID, weUserID, "在WechatCustomerUnionIDToIDMAP有,而其他地方没有,已删除")
cache.WechatCustomerUnionIDToIDMAP.Delete(unionID)
fmt.Println(time.Now(), "严重错误:微信用户ID", userID, "在WechatCustomerUnionIDToIDMAP有,而其他地方没有,已删除")
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
......@@ -120,29 +122,29 @@ func WeLogin(c *gin.Context) {
}
//// 保存昵称头像
//saveNickname := len(reqData.Nickname) > 0 && reqData.Nickname != userInfo.Nickname // 要更新数据
//saveURL := len(reqData.AvatarURL) > 0 && reqData.AvatarURL != userInfo.AvatarURL // 要更新数据
//saveNickname := len(reqData.Nickname) > 0 && reqData.Nickname != weUserInfo.Nickname // 要更新数据
//saveURL := len(reqData.AvatarURL) > 0 && reqData.AvatarURL != weUserInfo.AvatarURL // 要更新数据
//
//if saveNickname || saveURL { // 要更新数据
// if saveNickname {
// userInfo.Nickname = reqData.Nickname
// weUserInfo.Nickname = reqData.Nickname
// }
// if saveURL {
// userInfo.AvatarURL = reqData.AvatarURL
// weUserInfo.AvatarURL = reqData.AvatarURL
// }
// if dbcurd.UpdateUWeCustomerNicknameAndURL(userID, userInfo.Nickname, userInfo.AvatarURL) { // 更新数据库
// cache.WechatCustomerMap.Store(userID, *userInfo) // 更新缓存
// if dbcurd.UpdateUWeCustomerNicknameAndURL(weUserID, weUserInfo.Nickname, weUserInfo.AvatarURL) { // 更新数据库
// cache.wechatCustomerMap.Store(weUserID, *weUserInfo) // 更新缓存
// }
//}
var res weLoginRes
res.Expiry = uint32(nowTime/1000000) + tokenExpiryTimeS
res.Token = api.CreateToken(nowTime, userID, 1, res.Expiry)
if len(userInfo.WePhone) > 0 {
res.Token = api.CreateToken(nowTime, weUserID, 1, res.Expiry)
if len(weUserInfo.WePhone) > 0 {
res.WePhone = true
}
if len(userInfo.Nickname) > 0 && len(userInfo.AvatarURL) > 0 {
if len(weUserInfo.Nickname) > 0 /* && len(weUserInfo.AvatarURL) > 0 */ { // 有些人本来就没得头像
res.WeInfo = true
}
......
package api_we_login_we_info
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/thirdapi/tencent"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
// WeLoginTest 微信登录(测试的假code)
// @Tags 家长微信-登录及微信信息上传
// @Summary 登录(测试的假code) [complete]
// @Description 微信code传至后台,后台返回token,token有效时长:48小时
// @Param data body weLoginReq true "登录信息"
// @Product json
// @Success 0 {object} weLoginRes
// @Router /we/logintest [POST]
func WeLoginTest(c *gin.Context) {
var reqData weLoginReq
err := c.ShouldBindJSON(&reqData)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqParaFormat,
"message": api.CodeMsg[api.ErrorReqParaFormat],
})
return
}
var weUserID uint32
nowTime := time.Now().UnixMicro()
var tokenInfo api.TokenResult
if len(reqData.Token) > 0 {
tokenInfo = api.DecryptToken(reqData.Token)
if tokenInfo.UserType == 1 {
api.CheckTokenExit(&tokenInfo)
if tokenInfo.CheckResult == api.Success {
weUserID = tokenInfo.UserID
}
}
}
var weUserInfo *model.CacheWeCustomerStruct
if weUserID != 0 {
weUserInfo = cache.GetWeUserInfoFromMapAndDB(weUserID) //cache.GetWechatCustomerInfoAndCacheUpdateTokenTime(weUserID, nowTime)
cache.WechatCustomerTokenCreateTime.Store(weUserID,nowTime)
if weUserInfo != nil {
dbcurd.UpdateUWeCustomerLoginTime(weUserID) // todo 改成每天半夜来记录
}
}
if weUserInfo == nil { // 微信服务器登录
unionID,openID,_ := tencent.WechatCode2SessionTest(reqData.Code) //也不去校验reqData.Code长度了,多半是对的
if len(unionID) == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr],
})
return
}
weUserID = cache.GetWechatCustomerUserIDByUnionID(unionID)
if weUserID == 0 { // 原来没有,只有注册
var res uint8
weUserID, res = dbcurd.InsertUWeCustomerUnionID(unionID,openID) //插入
if res == dbcurd.InsertSysErr {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
if res == dbcurd.InsertDuplicate {
weUserInfo, weUserID = dbcurd.SelectUWeCustomerByUnionIDToCacheModel(unionID)
}
if weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
weUserInfo = &model.CacheWeCustomerStruct{
OpenID: openID,
}
cache.CreatWechatCustomerMap(weUserID, weUserInfo) //cache.wechatCustomerMap.Store(weUserID, *weUserInfo)
cache.WechatCustomerUnionIDToIDMAP.Store(unionID, weUserID)
cache.WechatCustomerTokenCreateTime.Store(weUserID,nowTime)
} else { // 已有用户
weUserInfo = cache.GetWeUserInfoFromMapAndDB(weUserID)
cache.WechatCustomerTokenCreateTime.Store(weUserID,nowTime)
if weUserInfo != nil {
dbcurd.UpdateUWeCustomerLoginTime(weUserID) //todo 改成每天半夜来记录
} else {
fmt.Println(time.Now(), "严重错误:微信用户ID",unionID, weUserID, "在WechatCustomerUnionIDToIDMAP有,而其他地方没有,已删除")
cache.WechatCustomerUnionIDToIDMAP.Delete(unionID)
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
}
}
// 保存昵称头像
//saveNickname := len(reqData.Nickname) > 0 && reqData.Nickname != weUserInfo.Nickname // 要更新数据
//saveURL := len(reqData.AvatarURL) > 0 && reqData.AvatarURL != weUserInfo.AvatarURL // 要更新数据
//
//if saveNickname || saveURL { // 要更新数据
// if saveNickname {
// weUserInfo.Nickname = reqData.Nickname
// }
// if saveURL {
// weUserInfo.AvatarURL = reqData.AvatarURL
// }
// if dbcurd.UpdateUWeCustomerNicknameAndURL(weUserID, weUserInfo.Nickname, weUserInfo.AvatarURL) { // 更新数据库
// cache.wechatCustomerMap.Store(weUserID, *weUserInfo) // 更新缓存
// }
//}
var res weLoginRes
res.Expiry = uint32(nowTime/1000000) + tokenExpiryTimeS
res.Token = api.CreateToken(nowTime, weUserID, 1, res.Expiry)
if len(weUserInfo.WePhone) > 0 {
res.WePhone = true
}
if len(weUserInfo.Nickname)>0 && len(weUserInfo.AvatarURL) > 0 {
res.WeInfo = true
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": res,
})
}
package api_we_login_we_info
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
)
type wechatUserBindWeInfoStruct struct {
Nickname string `json:"nickname"` // 用户昵称
AvatarURL string `json:"avatarurl" example:""` // 用户头像URL
}
// WechatUserBindWeInfo 上传微信用户信息
// @Tags 家长微信-登录及微信信息上传
// @Summary 上传微信用户头像昵称 [complete]
// @Description 上传用户授权获取到的微信头像昵称
// @Produce json
// @Param data body wechatUserBindWeInfoStruct true "头像昵称信息"
// @Success 0
// @Router /we/webindinfo [POST]
// @Security ApiKeyAuth
func WechatUserBindWeInfo(c *gin.Context){
var reqData wechatUserBindWeInfoStruct
err := c.ShouldBindJSON(&reqData)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqParaFormat,
"message": api.CodeMsg[api.ErrorReqParaFormat],
})
return
}
// 取微信用户
v, ok := c.Get("userID")
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("WechatUserBindWePhone",
zap.Reflect("c.Get(\"userID\")", v))
return
}
userInfo := cache.GetWeUserInfoFromMapAndDB(weUserID)
// 保存昵称头像
saveNickname := len(reqData.Nickname) > 0 && reqData.Nickname != userInfo.Nickname // 要更新数据
saveURL := len(reqData.AvatarURL) > 0 && reqData.AvatarURL != userInfo.AvatarURL // 要更新数据
if saveNickname || saveURL { // 要更新数据
if saveNickname {
userInfo.Nickname = reqData.Nickname
}
if saveURL {
userInfo.AvatarURL = reqData.AvatarURL
}
if dbcurd.UpdateUWeCustomerNicknameAndURL(weUserID, userInfo.Nickname, userInfo.AvatarURL) { // 更新数据库
cache.UpdateUWeCustomerMapNicknameAndURLAndPhone(weUserID, &userInfo.Nickname, &userInfo.AvatarURL,nil) // 更新缓存
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
}
\ No newline at end of file
package api_we_login_we_info
import (
"crypto/aes"
"crypto/cipher"
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/logger"
"dc_golang_server_1/thirdapi/tencent"
"encoding/base64"
"encoding/json"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
)
type wechatUserBindWePhoneStruct struct {
Code string `json:"code"`
IV string `json:"iv"`
EncryptedData string `json:"encryptedData"`
}
// WechatUserBindWePhone 上传微信用户手机号
// @Tags 家长微信-登录及微信信息上传
// @Summary 上传微信用户手机号 [complete]
// @Description 上传用户授权获取到的微信手机号
// @Produce json
// @Param data body wechatUserBindWePhoneStruct true "手机号"
// @Success 0
// @Router /we/webindphone [POST]
// @Security ApiKeyAuth
func WechatUserBindWePhone(c *gin.Context) {
var reqData wechatUserBindWePhoneStruct
err := c.ShouldBindJSON(&reqData)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqParaFormat,
"message": api.CodeMsg[api.ErrorReqParaFormat],
})
return
}
// 取微信用户
v, ok := c.Get("userID")
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("WechatUserBindWePhone",
zap.Reflect("c.Get(\"userID\")", v))
return
}
if len(reqData.EncryptedData) == 0 || len(reqData.Code) == 0 || len(reqData.IV) == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara],
})
return
}
_, _, sessionKey := tencent.WechatCode2Session(reqData.Code) //也不去校验reqData.Code长度了,对半是对的
if len(sessionKey) == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr] + "1",
})
return
}
aesKey := make([]byte, base64.StdEncoding.DecodedLen(len(sessionKey)))
aesKeyLen, err := base64.StdEncoding.Decode(aesKey, []byte(sessionKey))
if err != nil || aesKeyLen != 16 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr] + "2",
})
return
}
cipherText := make([]byte, base64.StdEncoding.DecodedLen(len(reqData.EncryptedData)))
cipherTextLen, err := base64.StdEncoding.Decode(cipherText, []byte(reqData.EncryptedData))
if err != nil || cipherTextLen == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr] + "3",
})
return
}
iv := make([]byte, base64.StdEncoding.DecodedLen(len(reqData.IV)))
ivLen, err := base64.StdEncoding.Decode(iv, []byte(reqData.IV))
if err != nil || ivLen == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr] + "4",
})
return
}
// 拿aesKey cipherText iv 解密
block, err := aes.NewCipher(aesKey[:16])
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
blockMode := cipher.NewCBCDecrypter(block, iv[:ivLen])
plainText := make([]byte, cipherTextLen)
blockMode.CryptBlocks(plainText, cipherText[:cipherTextLen])
plainText = plainText[:len(plainText)-int(plainText[len(plainText)-1])] // 删除填充
var autoGenerated struct {
PurePhoneNumber string `json:"purePhoneNumber"`
}
err = json.Unmarshal(plainText, &autoGenerated)
if err != nil {
logger.LogHttpClient.Error("腾讯解密电话号码的JSON,解析失败",
zap.String("sessionKey", sessionKey),
zap.String("EncryptedData", reqData.EncryptedData),
zap.String("IV", reqData.IV),
zap.String("plainText", string(plainText)),
zap.Error(err))
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr] + "4",
})
return
}
userInfo := cache.GetWeUserInfoFromMapAndDB(weUserID)
if len(autoGenerated.PurePhoneNumber) > 0 && autoGenerated.PurePhoneNumber != userInfo.WePhone {
userInfo.WePhone = autoGenerated.PurePhoneNumber
if dbcurd.UpdateUWeCustomerWePhone(weUserID, userInfo.WePhone) { // 更新数据库
cache.UpdateUWeCustomerMapNicknameAndURLAndPhone(weUserID, nil,nil,&userInfo.WePhone) // 更新缓存
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
}
package api_we
package api_we_phone_card
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"dc_golang_server_1/thirdapi/chinamobile"
"dc_golang_server_1/thirdapi/smsCaptcha"
"dc_golang_server_1/util/setting"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
......@@ -15,18 +16,19 @@ import (
)
// AddFamilyNum 添加亲情号
// @Tags 家长微信
// @Tags 家长微信-公话卡
// @Summary 添加亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限
// @Description 家长绑定亲情号接口
// @Accept json
// @Produce json
// @Param id path integer true "学生ID"
// @Param data body model.CacheFamilyOnePerson true "亲情号内容"
// @Param data body reqAddFamilyNumTestStruct true "亲情号内容"
// @Success 0
// @Failure 40 {object} string "验证码无效"
// @Router /we/familynum/{id} [POST]
// @Security ApiKeyAuth
func AddFamilyNum(c *gin.Context) {
var reqData model.CacheFamilyOnePerson
var reqData reqAddFamilyNumTestStruct
err := c.ShouldBindJSON(&reqData)
if err != nil {
c.JSON(http.StatusOK, gin.H{
......@@ -42,6 +44,23 @@ func AddFamilyNum(c *gin.Context) {
})
return
}
if reqData.SmsCaptcha < 100000 || reqData.SmsCaptcha > 999999 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSmsCaptchaErr,
"message": api.CodeMsg[api.ErrorSmsCaptchaErr],
})
return
}
// 找短信验证码服务器验证验证码是否有效
tempStr := smsCaptcha.Verify(reqData.Phone, reqData.SmsCaptcha)
if len(tempStr) > 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSmsCaptchaErr,
"message": tempStr,
})
return
}
cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
cardUserID := uint32(cardUserIDInt)
......@@ -57,8 +76,8 @@ func AddFamilyNum(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("AddFamilyNum",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -68,8 +87,8 @@ func AddFamilyNum(c *gin.Context) {
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r != 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
......@@ -77,8 +96,8 @@ func AddFamilyNum(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": api.ErrorUserNotHavePhoneCard,
"data": api.CodeMsg[api.ErrorUserNotHavePhoneCard] + ",请先绑定共话卡",
"code": api.ErrorUserNotHavePhoneCard,
"message": api.CodeMsg[api.ErrorUserNotHavePhoneCard] + ",请先绑定共话卡",
},
)
return
......@@ -94,11 +113,11 @@ func AddFamilyNum(c *gin.Context) {
return
}
if len(simInfoP.FamilyNum) > 2 {
fmt.Println("居然已经>=3个号了还在添加", cardUserInfo.SimCardID, simInfoP)
if len(simInfoP.FamilyNum) >= setting.MaxFamilyNum {
fmt.Println("居然已经>=", setting.MaxFamilyNum, "个号了还在添加", cardUserInfo.SimCardID, simInfoP)
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": "一张卡最多可绑定3个亲情号码,请删除一个已有的再添加",
"message": "一张卡最多可绑定" + strconv.FormatUint(uint64(setting.MaxFamilyNum), 10) + "个亲情号码,请删除一个已有的再添加",
})
return
}
......@@ -124,19 +143,19 @@ func AddFamilyNum(c *gin.Context) {
}
// 写库
if dbcurd.InsertUSimFamilyNum(cardUserInfo.SimCardID, reqData.Phone, reqData.Nickname) == dbcurd.InsertSysErr {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
if dbcurd.InsertUSimFamilyNum(cardUserInfo.SimCardID, reqData.Phone, reqData.Nickname) == dbcurd.InsertOK {
err = cache.AddFamilyNumInSimInfoMap(cardUserInfo.SimCardID, &reqData.CacheFamilyOnePerson) // 写缓存
if err == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
return
}
}
// 写缓存
simInfoP.FamilyNum = append(simInfoP.FamilyNum, reqData) // 并发不安全
cache.SimInfoMap.Store(cardUserInfo.SimCardID, *simInfoP)
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
package api_we_phone_card
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"dc_golang_server_1/thirdapi/smsCaptcha"
"dc_golang_server_1/util/setting"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
"strconv"
)
type reqAddFamilyNumTestStruct struct {
model.CacheFamilyOnePerson
SmsCaptcha uint32 // 短信验证码
}
// AddFamilyNumTest 添加亲情号(不向移动添加)
// @Tags 家长微信-公话卡
// @Summary 添加亲情号(仅主家长有权限) [complete] 用于测试卡的添加
// @Description 家长绑定亲情号接口
// @Accept json
// @Produce json
// @Param id path integer true "学生ID"
// @Param data body reqAddFamilyNumTestStruct true "亲情号内容"
// @Success 0
// @Failure 40 {object} string "验证码无效"
// @Router /we/familynumtest/{id} [POST]
// @Security ApiKeyAuth
func AddFamilyNumTest(c *gin.Context) {
var reqData reqAddFamilyNumTestStruct
err := c.ShouldBindJSON(&reqData)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqParaFormat,
"message": api.CodeMsg[api.ErrorReqParaFormat],
})
return
}
if len(reqData.Phone) < 3 || len(reqData.Nickname) == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara],
})
return
}
if reqData.SmsCaptcha < 100000 || reqData.SmsCaptcha > 999999 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSmsCaptchaErr,
"message": api.CodeMsg[api.ErrorSmsCaptchaErr],
})
return
}
// 找短信验证码服务器验证验证码是否有效
tempStr := smsCaptcha.Verify(reqData.Phone, reqData.SmsCaptcha)
if len(tempStr) > 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSmsCaptchaErr,
"message": tempStr,
})
return
}
cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
cardUserID := uint32(cardUserIDInt)
if cardUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " id不正确",
})
return
}
// 取微信用户
v, ok := c.Get("userID")
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("AddFamilyNum",
zap.Reflect("c.Get(\"userID\")", v))
return
}
// 校验weUserID是否有cardUserID权限
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r != 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
if len(cardUserInfo.SimCardID) == 0 { // 学生未绑卡
c.JSON(
http.StatusOK,
gin.H{
"code": api.ErrorUserNotHavePhoneCard,
"message": api.CodeMsg[api.ErrorUserNotHavePhoneCard] + ",请先绑定共话卡",
},
)
return
}
// 查卡的信息
simInfoP := cache.GetSimInfo(cardUserInfo.SimCardID)
if simInfoP == nil {
fmt.Println("居然查不到卡信息 cardUserInfo.SimCardID:", cardUserInfo.SimCardID)
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr] + "查不到sim卡信息",
})
return
}
if len(simInfoP.FamilyNum) >= setting.MaxFamilyNum {
fmt.Println("居然已经>=" ,setting.MaxFamilyNum , "个号了还在添加", cardUserInfo.SimCardID, simInfoP)
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": "一张卡最多可绑定" + strconv.FormatUint(uint64(setting.MaxFamilyNum),10) + "个亲情号码,请删除一个已有的再添加",
})
return
}
// 判断亲情号是否重复
for _, family := range simInfoP.FamilyNum {
if family.Phone == reqData.Phone {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": family.Phone + "已绑定亲情号:" + family.Nickname,
})
return
}
}
// 找移动添加亲情号
//if err = chinamobile.AddMemberVoiceWhiteList(cardUserInfo.SimCardID,reqData.Phone);err != nil {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemBusy,
// "message": err.Error(),
// })
// return
//}
// 写库
if dbcurd.InsertUSimFamilyNum(cardUserInfo.SimCardID, reqData.Phone, reqData.Nickname) == dbcurd.InsertOK {
err = cache.AddFamilyNumInSimInfoMap(cardUserInfo.SimCardID, &reqData.CacheFamilyOnePerson) // 写缓存
if err == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
return
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
package api_we
package api_we_phone_card
import (
"dc_golang_server_1/api"
......@@ -17,7 +17,7 @@ type apiDeleteFamilyNumStruct struct {
}
// DeleteFamilyNum 删除亲情号
// @Tags 家长微信
// @Tags 家长微信-公话卡
// @Summary 删除亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限
// @Description 删除亲情号接口
// @Accept json
......@@ -42,8 +42,8 @@ func DeleteFamilyNum(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("AddFamilyNum",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -53,8 +53,8 @@ func DeleteFamilyNum(c *gin.Context) {
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r != 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
......@@ -62,8 +62,8 @@ func DeleteFamilyNum(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": api.ErrorUserNotHavePhoneCard,
"data": api.CodeMsg[api.ErrorUserNotHavePhoneCard] + ",请先绑定共话卡",
"code": api.ErrorUserNotHavePhoneCard,
"message": api.CodeMsg[api.ErrorUserNotHavePhoneCard] + ",请先绑定共话卡",
},
)
return
......@@ -96,7 +96,7 @@ func DeleteFamilyNum(c *gin.Context) {
return
}
for i, family := range simInfoP.FamilyNum {
for _, family := range simInfoP.FamilyNum {
if family.Phone == reqData.Phone {
// 本月删除亲情号次数加1
newCount := dbcurd.UpdateUSimInfoAddFamilyDeleteCount(cardUserInfo.SimCardID)
......@@ -115,14 +115,21 @@ func DeleteFamilyNum(c *gin.Context) {
})
return
}
simInfoP.FamilyNum = append(simInfoP.FamilyNum[:i], simInfoP.FamilyNum[i+1:]...)
cache.SimInfoMap.Store(cardUserInfo.SimCardID, *simInfoP)
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
err = cache.DelFamilyNumInSimInfoMap(cardUserInfo.SimCardID, reqData.Phone)
if err == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
}
return
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + "未找到号码" + reqData.Phone,
......
package api_we
package api_we_phone_card
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
......@@ -12,23 +14,20 @@ import (
)
// GetCallRecord 查询通话记录
// @Tags 家长微信
// @Tags 家长微信-公话卡
// @Summary 查询通话记录 [complete]
// @Description 传学生ID至后台,后台返回通话记录列表
// @Produce json
// @Param id path integer true "学生ID"
// @Param pnum query integer false "页数,选填,不填则默认第0页"
// @Param psize query integer false "页条数,选填,不填则不分页全部返回"
// @Param start query string false "起始时间时间和结束时间同时填或同时不填,可以是纯年月日2021-10-01,也可以是带时间年月日时分2021-10-01 10:00或年月日时分秒2021-10-01 10:00:00,年月日时分秒没带全的默认后面为00" default(2021-10-01)
// @Param end query string false "起始时间时间和结束时间同时填或同时不填,可以是纯年月日2021-10-01,也可以是带时间年月日时分2021-10-01 10:00或年月日时分秒2021-10-01 10:00:00,年月日时分秒没带全的默认后面为00" default(2021-10-31 23:59:59)
// @Param asc query bool false "是否升序,选填,不填则是降序" default(false)
// @Param data query model.SelectWeGetCallRecordCriteria false "查询条件"
// @Success 0 {object} []model.SelectWeGetCallRecordStruct "通话记录列表"
// @Router /we/callrecord/{id} [GET]
// @Security ApiKeyAuth
func GetCallRecord(c *gin.Context) {
var reqData model.SelectWeGetCallRecordCriteria
cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
cardUserID := uint32(cardUserIDInt)
if cardUserID == 0 {
reqData.ID = uint32(cardUserIDInt)
if reqData.ID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " id不正确",
......@@ -36,13 +35,23 @@ func GetCallRecord(c *gin.Context) {
return
}
err := c.ShouldBindQuery(&reqData)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqParaFormat,
"message": api.CodeMsg[api.ErrorReqParaFormat],
})
fmt.Println(err)
return
}
// 取微信用户
v, ok := c.Get("userID")
masterWeUserID := v.(uint32)
if ok != true || masterWeUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("GetCallRecord",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -50,25 +59,25 @@ func GetCallRecord(c *gin.Context) {
}
// 校验weUserID是否有cardUserID权限
if cache.CheckCardUserMaserAndSlaveWeID(cardUserID, masterWeUserID) < 2 {
if cache.CheckCardUserMaserAndSlaveWeID(reqData.ID, masterWeUserID) < 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
pNum, _ := strconv.ParseUint(c.Query("pnum"), 10, 32)
pSize, _ := strconv.ParseUint(c.Query("psize"), 10, 32)
startTime := c.Query("start")
endTime := c.Query("end")
desc := "desc"
if c.Query("asc") == "true" {
desc = "asc"
}
//pNum, _ := strconv.ParseUint(c.Query("pnum"), 10, 32)
//pSize, _ := strconv.ParseUint(c.Query("psize"), 10, 32)
//startTime := c.Query("start")
//endTime := c.Query("end")
//desc := "desc"
//if c.Query("asc") == "true" {
// desc = "asc"
//}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": dbcurd.SelectWeGetCallRecord(cardUserID, startTime, endTime, desc, pNum, pSize),
"data": dbcurd.SelectWeGetCallRecord(&reqData),
})
}
package api_we_phone_card
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"dc_golang_server_1/util"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
"strconv"
)
type getPhoneCardStatusRes struct {
SimID string `json:"simID"` // 卡号
model.CacheSimInfoStruct
ExpiryAtString string `json:"expiryAt"` // 给前端返回年月日
MaxFamily uint8 `json:"maxFamily"` // 最多可以添加几个亲情号
}
// GetPhoneCardStatus 获取学生公话卡状态
// @Tags 家长微信-公话卡
// @Summary 获取学生公话卡状态(含亲情号信息) [complete]
// @Description 传学生ID至后台,后台返回卡状态
// @Produce json
// @Param id path integer true "学生ID"
// @Success 0 {object} getPhoneCardStatusRes "公话卡状态信息"
// @Router /we/phonecardstatus/{id} [GET]
// @Security ApiKeyAuth
func GetPhoneCardStatus(c *gin.Context) { // 以后要改成根据区域服务查
cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
cardUserID := uint32(cardUserIDInt)
if cardUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " id不正确",
})
return
}
// 取微信用户
v, ok := c.Get("userID")
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("GetCardUserTrend",
zap.Reflect("c.Get(\"userID\")", v))
return
}
// 校验weUserID是否有cardUserID权限
if cache.CheckCardUserMaserAndSlaveWeID(cardUserID, weUserID) < 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
// 查出该学生信息
cardUserInfo := cache.GetCardUserInfo(cardUserID)
//if cardUserInfo == nil {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemErr,
// "message": api.CodeMsg[api.ErrorSystemErr],
// })
// return
//}
//if cardUserInfo.PhoneExpiry == *new(time.Time) { // 未缴费
// c.JSON(
// http.StatusOK,
// gin.H{
// "code": api.Success,
// "data": getPhoneCardStatusRes{
// CacheSimInfoStruct: model.CacheSimInfoStruct{
// Status: 4, //0未绑卡但在有效期 1 正常使用 2 已挂失 3 服务已到期 4 未充值(即从未充过值) 5 已销号,请补卡 //(3、4、5数据库无该状态,仅微信API接口该状态)
// },
// },
// },
// )
// return
//}
//
//var status uint8
//if time.Now().After(cardUserInfo.PhoneExpiry) { // 服务已到期
// status = 3 // 0未绑卡但在有效期 1 正常使用 2 已挂失 3 服务已到期 4 未充值(即从未充过值) 5 已销号,请补卡 //(3、4、5数据库无该状态,仅微信API接口该状态)
//}
//
//if cardUserInfo.SimCardID == "" { //学生未绑卡 Status: 0或3, 没绑卡,到期也也返回已到期,好先充值
// c.JSON(
// http.StatusOK,
// gin.H{
// "code": api.Success,
// "data": getPhoneCardStatusRes{
// CacheSimInfoStruct: model.CacheSimInfoStruct{
// ExpiryAt: cardUserInfo.PhoneExpiry,
// Status: status,
// },
// },
// },
// )
// return
//}
//
//res := cache.GetSimInfo(cardUserInfo.SimCardID)
//if res != nil {
// // 服务已过期
// if status > 0 {
// res.Status = status
// }
// res.ExpiryAt = cardUserInfo.PhoneExpiry
// c.JSON(
// http.StatusOK,
// gin.H{
// "code": api.Success,
// "data": getPhoneCardStatusRes{
// SimID: cardUserInfo.SimCardID,
// CacheSimInfoStruct: *res,
// },
// },
// )
//} else {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemErr,
// "message": api.CodeMsg[api.ErrorSystemErr],
// })
//}
res := PhoneCardStatus(cardUserInfo)
if res == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
} else {
c.JSON(
http.StatusOK, gin.H{
"code": api.Success,
"data": getPhoneCardStatusRes{
SimID: cardUserInfo.SimCardID,
CacheSimInfoStruct: *res,
ExpiryAtString: res.ExpiryAt.Format("2006-01-02"),
MaxFamily: 2,
},
})
}
}
// PhoneCardStatus 获取卡状态信息,1.status状态整巴适,2.expiryAt时间要替换成学生支付的到期时间
func PhoneCardStatus(cardUserInfo *model.CacheCardUserStruct) *model.CacheSimInfoStruct { //nil 系统错误 0未绑卡但在有效期 1 正常使用 2 已挂失 3 服务已到期 4 未充值(即从未充过值) 5 已销号,请补卡 //(3、4、5数据库无该状态,仅微信API接口该状态)
if cardUserInfo == nil {
return nil
}
status := util.JudgeCardCancel(cardUserInfo.PhoneExpiry)
//if cardUserInfo.PhoneExpiry == *new(time.Time) { // 从未缴过费
// return &model.CacheSimInfoStruct{Status: 4}
//}
//var status uint8
//if time.Now().After(cardUserInfo.PhoneExpiry) { // 服务已到期
// status = 3 // 0未绑卡但在有效期 1 正常使用 2 已挂失 3 服务已到期 4 未充值(即从未充过值) 5 已销号,请补卡 //(3、4、5数据库无该状态,仅微信API接口该状态)
//}
if cardUserInfo.SimCardID == "" { //学生未绑卡 Status: 0或3, 没绑卡,到期也也返回已到期,好先充值
return &model.CacheSimInfoStruct{
ExpiryAt: cardUserInfo.PhoneExpiry,
Status: status} // Status: 0或3, 没绑卡,到期也也返回已到期,好先充值
}
res := cache.GetSimInfo(cardUserInfo.SimCardID)
if res == nil { // 有simID,取不到sim卡信息,系统错误
logger.Log.Error("phoneCardStatus cache.GetSimInfo res == nil",
zap.String("SimCardID", cardUserInfo.SimCardID))
return nil
}
if status > 0 {
res.Status = status
}
res.ExpiryAt = cardUserInfo.PhoneExpiry
return res
}
package api_we
package api_we_phone_card
import (
"dc_golang_server_1/api"
......@@ -14,7 +14,7 @@ import (
)
// PutFamilyNickName 修改亲情号的昵称
// @Tags 家长微信
// @Tags 家长微信-公话卡
// @Summary 修改亲情号的昵称(注:号码本身不可修改,只能删除和添加,仅主家长有权限) [complete] 最新调整为仅主家长有权限
// @Description 修改亲情号接口
// @Accept json
......@@ -39,8 +39,8 @@ func PutFamilyNickName(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("PutFamilyNickName",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -50,8 +50,8 @@ func PutFamilyNickName(c *gin.Context) {
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r != 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
......@@ -59,8 +59,8 @@ func PutFamilyNickName(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": api.ErrorUserNotHavePhoneCard,
"data": api.CodeMsg[api.ErrorUserNotHavePhoneCard] + ",请先绑定共话卡",
"code": api.ErrorUserNotHavePhoneCard,
"message": api.CodeMsg[api.ErrorUserNotHavePhoneCard] + ",请先绑定共话卡",
},
)
return
......@@ -93,7 +93,7 @@ func PutFamilyNickName(c *gin.Context) {
return
}
for i, family := range simInfoP.FamilyNum {
for _, family := range simInfoP.FamilyNum {
if family.Phone == reqData.Phone {
// 写库
if dbcurd.UpdateUSimFamilyNumNickname(cardUserInfo.SimCardID, reqData.Phone, reqData.Nickname) == false {
......@@ -104,11 +104,17 @@ func PutFamilyNickName(c *gin.Context) {
return
}
family.Nickname = reqData.Nickname
simInfoP.FamilyNum[i] = family
cache.SimInfoMap.Store(cardUserInfo.SimCardID, *simInfoP)
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
err = cache.UpdateFamilyNumNicknameInSimInfoMap(cardUserInfo.SimCardID, &family)
if err == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
}
return
}
}
......
package api_we_phone_pay
import (
"dc_golang_server_1/api"
"dc_golang_server_1/api/api_we/api_we_phone_card"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/util"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
type resCardUserGetPayAmountList struct {
CardFee struct{
Type uint8 `json:"type"` // 1开卡费/2补卡费
Amount int32 `json:"amount"` // 金额:单位分
Required uint8 `json:"required"` // 1 必选项 2 可选项默认不勾选 3 可选项默认勾选
Describe string `json:"describe" example:"完成充值后生活老师会将电话卡配发给学生"` // 描述
} `json:"cardFee"` // 卡费
Charges []struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
} `json:"charges"`
ChargeRequired uint8 `json:"chargeRequired"` // 充值项是否必选 1 必选项 2 可选项默认不勾选 3 可选项默认勾选
}
// GetPayList 查询缴费说明及可选金额列表
// @Tags 家长微信-缴费
// @Summary 查询缴费说明及可选金额列表[complete]
// @Description 查询缴费说明及可选金额列表
// @Produce json
// @Param aid path integer true "areaServiceID,获取学生公话卡状态接口返回了这个ID的"
// @Param id path integer true "学生ID,新增加学生ID用来判断其当前是否需要开卡费或补卡费"
// @Success 0 {object} resCardUserGetPayAmountList "缴费说明及可选金额列表"
// @Router /we/paylist/{aid}/{id} [GET]
// @Security ApiKeyAuth
func GetPayList(c *gin.Context) {
aid, _ := strconv.ParseUint(c.Param("aid"), 10, 32)
if aid == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " aid不正确",
})
return
}
cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
cardUserID := uint32(cardUserIDInt)
if cardUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " cid不正确",
})
return
}
areaServiceInfo := cache.GetAreaServiceInfo(uint32(aid))
if areaServiceInfo == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " 未找到学生信息",
})
return
}
cardStatus := api_we_phone_card.PhoneCardStatus(cardUserInfo)
if cardStatus == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
temp := cache.GetAreaServicePhonePayListMap(uint32(aid))
//res := resCardUserGetPayAmountList{
// Charges: []struct{
// cache.GetAreaServicePhonePayListMap(uint32(aid)),
// "",
// }
//}
var res resCardUserGetPayAmountList
switch cardStatus.Status {
case 0,1: // 0未绑卡但在有效期 1 正常使用 2 已挂失 3 服务已到期 4 未充值(即从未充过值) 5 已销号,请补卡
res = resCardUserGetPayAmountList{
CardFee: struct {
Type uint8 `json:"type"`
Amount int32 `json:"amount"`
Required uint8 `json:"required"`
Describe string `json:"describe" example:"完成充值后生活老师会将电话卡配发给学生"`
}{
Type: 2, // 补卡
Amount: areaServiceInfo.ReplacementCardFee, // 补卡费
Required: 2, // 1 必选项 2 可选项默认不勾选 3 可选项默认勾选
Describe: "补卡(卡遗失)",
},
Charges: []struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
}{},
ChargeRequired: 3,
}
for i,v := range temp {
if v.Status {
res.Charges = append(res.Charges,struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
}{
v.CacheAreaServicePhonePayBase,
util.RenewExpiry(cardStatus.ExpiryAt,temp[i].Expiry).Format("2006-01-02"),// 有效期加月数
})
}
}
case 2: // 已挂失
res = resCardUserGetPayAmountList{
CardFee: struct {
Type uint8 `json:"type"`
Amount int32 `json:"amount"`
Required uint8 `json:"required"`
Describe string `json:"describe" example:"完成充值后生活老师会将电话卡配发给学生"`
}{
Type: 2, // 补卡
Amount: areaServiceInfo.ReplacementCardFee, // 补卡费
Required: 3, // 1 必选项 2 可选项默认不勾选 3 可选项默认勾选
Describe: "补卡(卡遗失)",
},
Charges: []struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
}{},
ChargeRequired: 2, // 2 可选项默认不勾选
}
for i,v := range temp {
if v.Status {
res.Charges = append(res.Charges,struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
}{
v.CacheAreaServicePhonePayBase,
util.RenewExpiry(cardStatus.ExpiryAt,temp[i].Expiry).Format("2006-01-02"),// 有效期加月数
})
}
}
case 3: // 服务已到期
res = resCardUserGetPayAmountList{
CardFee: struct {
Type uint8 `json:"type"`
Amount int32 `json:"amount"`
Required uint8 `json:"required"`
Describe string `json:"describe" example:"完成充值后生活老师会将电话卡配发给学生"`
}{
Type: 2, // 补卡
Amount: areaServiceInfo.ReplacementCardFee, // 补卡费
Required: 2, // 1 必选项 2 可选项默认不勾选 3 可选项默认勾选
Describe: "补卡(卡遗失)",
},
Charges: []struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
}{},
ChargeRequired: 1, // 1 必选
}
for i,v := range temp {
if v.Status {
res.Charges = append(res.Charges,struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
}{
v.CacheAreaServicePhonePayBase,
util.RenewExpiry(cardStatus.ExpiryAt,temp[i].Expiry).Format("2006-01-02"),// 有效期加月数
})
}
}
case 4,5: // 未充值(即从未充过值开过卡)
res = resCardUserGetPayAmountList{
CardFee: struct {
Type uint8 `json:"type"`
Amount int32 `json:"amount"`
Required uint8 `json:"required"`
Describe string `json:"describe" example:"完成充值后生活老师会将电话卡配发给学生"`
}{
Type: 1, // 开卡
Amount: areaServiceInfo.ActivateCardFee, // 开卡费
Required: 1, // 1 必选项 2 可选项默认不勾选 3 可选项默认勾选
Describe: "卡费",
},
Charges: []struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
}{},
ChargeRequired: 1, // 1 必选
}
for i,v := range temp {
if v.Status {
res.Charges = append(res.Charges,struct{
model.CacheAreaServicePhonePayBase // 话费:多选一,默认选第一项(0)
ExpiryAt string `json:"expiryAt"`
}{
v.CacheAreaServicePhonePayBase,
util.NewCardAddExpiry(temp[i].Expiry).Format("2006-01-02"),// 有效期加月数
})
}
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": res,
})
}
\ No newline at end of file
package api_we_phone_pay
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
"strconv"
)
// GetPayRecord 查询话费缴费记录
// @Tags 家长微信-缴费
// @Summary 查询缴费记录[complete]
// @Description 查询缴费记录
// @Produce json
// @Param aid path integer true "areaServiceID,获取学生公话卡状态接口返回了这个ID的"
// @Param id query integer true "学生ID"
// @Success 0 {object} []dbcurd.SelectUPhonePayRecordStruct " "
// @Router /we/payrecord/{aid} [GET]
// @Security ApiKeyAuth
func GetPayRecord(c *gin.Context) {
cardUserIDInt64, _ := strconv.ParseInt(c.Query("id"), 10, 32)
areaServiceIDInt64, _ := strconv.ParseInt(c.Param("aid"), 10, 32)
if cardUserIDInt64 == 0 || areaServiceIDInt64 == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara],
})
return
}
cardUserID := uint32(cardUserIDInt64)
// 取微信用户
weID, ok := c.Get("userID")
masterWeUserID := weID.(uint32)
if ok != true || masterWeUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("GetPayRecord",
zap.Reflect("c.Get(\"userID\")", weID))
return
}
// 校验weUserID是否有cardUserID权限
if cache.CheckCardUserMaserAndSlaveWeID(cardUserID, masterWeUserID) < 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
res := dbcurd.SelectUPhonePayRecordByCardUserIDAndAreaServiceID(cardUserID,uint32(areaServiceIDInt64))
for i,v := range res {
weUserInfo := cache.GetWeUserInfoFromMapAndDB(v.WeUserID)
if weUserInfo != nil {
v.Nickname = weUserInfo.Nickname
v.AvatarURL = weUserInfo.AvatarURL
v.Phone = weUserInfo.WePhone
res[i] = v
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": res,
})
}
\ No newline at end of file
package api_we_phone_pay
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
// GetReplaceCardFeePhone 查询补卡费(目前仅公话卡)
// @Tags 家长微信-缴费
// @Summary 查询补卡费(目前仅公话卡)[complete]
// @Description 查询补卡费(目前仅公话卡)
// @Produce json
// @Param aid path integer true "areaServiceID,获取学生公话卡状态接口返回了这个ID的"
// @Success 0 {object} integer "补卡费,单位分"
// @Router /we/replacecardfee/phone/{aid} [GET]
// @Security ApiKeyAuth
func GetReplaceCardFeePhone(c *gin.Context) {
aid, _ := strconv.ParseUint(c.Param("aid"), 10, 32)
if aid == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " aid不正确",
})
return
}
areaServiceInfo := cache.GetAreaServiceInfo(uint32(aid))
if areaServiceInfo == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": areaServiceInfo.ReplacementCardFee,
})
}
\ No newline at end of file
package api_we_phone_pay
// PostPayReplaceCard 发起公话卡补卡支付
// @//Tags 家长微信-缴费
// @//Summary 发起公话卡补卡支付[complete]
// @//Description 发起公话卡补卡支付
// @//Produce json
// @//Param aid path integer true "areaServiceID,获取学生信息返回了这个ID的"
// @//Param cid path integer true "cardUserID,要缴费的学生ID"
// @//Success 0 {object} tencent.WxMiniRequestPayment "微信支付信息"
// @//Router /we/payreplacecard/phone/{aid}/{cid} [POST]
// @//Security ApiKeyAuth
//func PostPayReplaceCard(c *gin.Context) {
// // 取微信用户
// v, ok := c.Get("userID")
// weUserID := v.(uint32)
// if ok != true || weUserID == 0 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemErr,
// "message": api.CodeMsg[api.ErrorSystemErr],
// })
// logger.Log.Error("PostPay",
// zap.Reflect("c.Get(\"userID\")", v))
// return
// }
// weUserInfo := cache.GetWeUserInfoFromMapAndDB(weUserID) // 取openID用于支付,wePhone保存在账单里面
// if weUserInfo == nil {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemErr,
// "message": api.CodeMsg[api.ErrorSystemErr],
// })
// logger.Log.Error("PostPay cache.GetWeUserInfoFromMapAndDB(weUserID)==nil",
// zap.Uint32("weUserID", weUserID))
// return
// }
// if len(weUserInfo.OpenID) == 0 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemErr,
// "message": api.CodeMsg[api.ErrorSystemErr] + " openID为空",
// })
// logger.Log.Error("PostPay openID==nil",
// zap.Uint32("weUserID", weUserID),
// zap.Reflect("weUserInfo", weUserInfo))
// return
// }
//
// aidInt64, _ := strconv.ParseInt(c.Param("aid"), 10, 32)
// if aidInt64 == 0 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqPara,
// "message": api.CodeMsg[api.ErrorReqPara],
// })
// return
// }
//}
\ No newline at end of file
package api_we
package api_we_slave
import (
"dc_golang_server_1/api"
......@@ -12,7 +12,7 @@ import (
)
// DeleteSlaveBindCardUser 副家长解绑学生
// @Tags 家长微信
// @Tags 家长微信-副家长相关
// @Summary 副家长解绑学生 [complete]
// @Description 传学生ID至后台,后台返回成功失败
// @Produce json
......@@ -36,8 +36,8 @@ func DeleteSlaveBindCardUser(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("DeleteSlaveBindCardUser",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -46,13 +46,13 @@ func DeleteSlaveBindCardUser(c *gin.Context) {
if dbcurd.UpdateUWeCardUserDeleteAt(weUserID, cardUserID) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
}
cache.DeleteAStudentIDInWechatCustomerMap(weUserID, cardUserID, false)
cache.DeleteASlaveWeUserIDInCardUserMap(weUserID, cardUserID)
cache.AddOrDelSlaveWeUserIDInCardUserMap(weUserID, cardUserID, true) // 并发安全
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
......
package api_we
package api_we_slave
import (
"dc_golang_server_1/api"
......@@ -16,7 +16,7 @@ type apiDeleteSlaveWeUserStruct struct {
}
// DeleteSlaveWeUser 删除副家长(仅主家长有权限)
// @Tags 家长微信
// @Tags 家长微信-副家长相关
// @Summary 删除副家长(仅主家长有权限) [complete]
// @Description 传学生ID和微信UnionID,后台返回成功失败
// @Produce json
......@@ -41,8 +41,8 @@ func DeleteSlaveWeUser(c *gin.Context) {
masterWeUserID := v.(uint32)
if ok != true || masterWeUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("DeleteSlaveBindCardUser",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -52,8 +52,8 @@ func DeleteSlaveWeUser(c *gin.Context) {
// 校验weUserID是否有cardUserID权限
if cache.CheckCardUserMaserAndSlaveWeID(cardUserID, masterWeUserID) != 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
......@@ -77,13 +77,13 @@ func DeleteSlaveWeUser(c *gin.Context) {
if dbcurd.UpdateUWeCardUserDeleteAt(reqData.WeUserID, cardUserID) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
}
cache.DeleteAStudentIDInWechatCustomerMap(reqData.WeUserID, cardUserID, false)
cache.DeleteASlaveWeUserIDInCardUserMap(reqData.WeUserID, cardUserID)
cache.AddOrDelSlaveWeUserIDInCardUserMap(reqData.WeUserID, cardUserID, true)
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
......
package api_we
package api_we_slave
import (
"dc_golang_server_1/api"
......@@ -14,7 +14,7 @@ import (
)
// GetCardUserShareCode 获取邀请码(仅主家长有权限)
// @Tags 家长微信
// @Tags 家长微信-副家长相关
// @Summary 获取邀请码(仅主家长有权限) [complete]
// @Description 主家长生成邀请码,有效时长可选1分钟~60分钟
// @Produce json
......
package api_we
package api_we_slave
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/logger"
"dc_golang_server_1/util"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
"time"
)
......@@ -12,10 +14,11 @@ import (
type getPreviewCardUserStruct struct {
Name string `json:"name"` // 学生名字,脱敏显示
Area string `json:"area" example:"温江实验中学"` // 区域名字
ID uint32 `json:"id"` // 学生ID
}
// GetPreviewCardUser 通过邀请码获取学生预览信息
// @Tags 家长微信
// @Tags 家长微信-副家长相关
// @Summary 通过邀请码获取学生预览信息 [complete]
// @Description 传学生的邀请码,后台返回学生信息预览
// @Produce json
......@@ -87,6 +90,20 @@ func GetPreviewCardUser(c *gin.Context) {
})
return
}
// 取微信用户
v, ok := c.Get("userID")
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("GetPreviewCardUser",
zap.Reflect("c.Get(\"userID\")", v))
return
}
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo == nil {
c.JSON(http.StatusOK, gin.H{
......@@ -96,11 +113,40 @@ func GetPreviewCardUser(c *gin.Context) {
return
}
type alreadyBinding struct {
ID uint32 `json:"id"`
Master bool `json:"master"`
}
if cardUserInfo.MasterWechatUserID == weUserID { // 已经是主家长了
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": alreadyBinding{
cardUserID,
true,
},
})
return
}
for _, slave := range cardUserInfo.SlaveWechatUserID {
if weUserID == slave { // 已经是附家长了
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": alreadyBinding{
cardUserID,
false,
},
})
return
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": getPreviewCardUserStruct{
cardUserInfo.Name,
cache.GetAreaMapName(cardUserInfo.AreaID, true),
cardUserID, //api_we_student.GetCardUserDownSmallAvatarQiNiuURL(cardUserID),
},
})
}
package api_we
package api_we_slave
import (
"dc_golang_server_1/api"
......@@ -11,14 +11,10 @@ import (
)
type slaveWeUserRes struct {
// 微信UnionID
WeUserID uint32 `json:"weUserID"`
// 微信昵称
Nickname string `json:"nickname"`
// 头像URL
AvatarURL string `json:"avatarURL"`
// 手机号
Phone string `json:"phone"`
WeUserID uint32 `json:"weUserID"` // 微信UnionID
Nickname string `json:"nickname"` // 微信昵称
AvatarURL string `json:"avatarURL"` // 头像URL
Phone string `json:"phone"` // 手机号
// 绑定时间
// CreateAt time.Time `json:"createAt"`
}
......@@ -31,7 +27,7 @@ type slaveWeUserRes struct {
//}
// GetSlaveBindCardUser 获取学生副家长列表(仅主家长有权限)
// @Tags 家长微信
// @Tags 家长微信-副家长相关
// @Summary 获取学生副家长列表(仅主家长有权限) [complete]
// @Description 传学生ID至后台,后台返回成功失败
// @Produce json
......@@ -55,8 +51,8 @@ func GetSlaveBindCardUser(c *gin.Context) {
masterWeUserID := v.(uint32)
if ok != true || masterWeUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("DeleteSlaveBindCardUser",
zap.Reflect("c.Get(\"userID\")", v))
......
package api_we
package api_we_slave
import (
"dc_golang_server_1/api"
"dc_golang_server_1/api/api_we/api_we_student"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/logger"
......@@ -13,12 +14,12 @@ import (
)
// SlaveBindCardUser 通过邀请码绑定学生
// @Tags 家长微信
// @Tags 家长微信-副家长相关
// @Summary 通过邀请码绑定学生 [complete]
// @Description 传学生的邀请码,后台返回学生信息
// @Produce json
// @Param share_code path string true "学生的邀请码"
// @Success 0 {object} getCardUserAndTrendRes "学生信息"
// @Success 0 {object} api_we_student.GetCardUserAndTrendRes "学生信息"
// @Failure 30 "邀请码无效"
// @Failure 31 "邀请码已过期"
// @Router /we/bindcarduser/{share_code} [POST]
......@@ -91,41 +92,46 @@ func SlaveBindCardUser(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("SlaveBindCardUser",
zap.Reflect("c.Get(\"userID\")", v))
return
}
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r < 1 { // 居然没得这个微信用户
// 用户是否为测试用户
testRole, ok := cache.GetWechatCustomerTestRole(weUserID)
if ok == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTokenWrong,
"data": api.CodeMsg[api.ErrorTokenWrong],
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
var master bool
if r == 2 {
master = true
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r < 1 { // 居然没得这个微信用户
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTokenWrong,
"message": api.CodeMsg[api.ErrorTokenWrong],
})
return
}
if r == 1 { // 还没有绑定
// 存数据库
if dbcurd.InsertOrUpdateUWeCardUserSlave(weUserID, cardUserID) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
// 存缓存
cache.InsertNewStudentIDToWechatCustomerMap(weUserID, cardUserID, false)
cache.InsertWechatAndCardUserRelationToCardUserMap(weUserID, cardUserID, false) // todo 这里可优化
cache.AddOrDelSlaveWeUserIDInCardUserMap(weUserID, cardUserID, false) // 并发安全
cardUserInfo = cache.GetCardUserInfo(cardUserID) // todo 这里可优化
if cardUserInfo == nil { // 刚才都有,在就没有了呢
......@@ -140,20 +146,71 @@ func SlaveBindCardUser(c *gin.Context) {
}
}
// 根据学生所在的学校ID查询其区域服务[]ID
areaInfo := cache.GetAreaMapInfo(cardUserInfo.AreaID)
if areaInfo == nil || areaInfo.Status < 2 { // 查不到该区域或区域状态不对
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("api_we_student.GetCardUserAndTrend() 区域状态不对",
zap.Reflect("cardUserInfo", cardUserInfo),
zap.Reflect("areaInfo", areaInfo),
zap.Uint32("cardUserID", cardUserID))
return
}
var service []api_we_student.ServiceStruct
for _, areaServiceID := range areaInfo.AreaServiceID {
areaServiceInfo := cache.GetAreaServiceInfo(areaServiceID)
if areaServiceInfo != nil {
if areaServiceInfo.Status == 1 { // 正式 // 状态 0无内容1正式2测试3暂停4暂未开放
// if areaServiceInfo.ServiceType == 1 { // 1公话2定位3饮水4卡消费5洗浴6洗衣机 目前只支持公话
service = append(service, api_we_student.ServiceStruct{
Name: areaServiceInfo.Name,
AID: areaServiceID,
Type: areaServiceInfo.ServiceType,
})
//}
} else if areaServiceInfo.Status == 2 && testRole { // 测试
service = append(service, api_we_student.ServiceStruct{
Name: areaServiceInfo.Name,
AID: areaServiceID,
Type: areaServiceInfo.ServiceType,
})
} else if areaServiceInfo.Status == 4 {
service = append(service, api_we_student.ServiceStruct{
Name: areaServiceInfo.Name, // 暂未开放传0
Type: areaServiceInfo.ServiceType,
})
}
} else {
logger.Log.Error("api_we_student.GetCardUserAndTrend() 区域服务为空不对",
zap.Reflect("cardUserInfo", cardUserInfo),
zap.Reflect("areaInfo", areaInfo),
zap.Reflect("areaServiceID", areaServiceID),
zap.Uint32("cardUserID", cardUserID))
}
}
if service == nil {
service = append(service, api_we_student.ServiceStruct{Name: "公话", Type: 1})
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": getCardUserAndTrendRes{
weResUserInfoStruct: weResUserInfoStruct{
master,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, true),
cardUserInfo.Grade,
cardUserInfo.Class,
cardUserInfo.StuNum,
"data": api_we_student.GetCardUserAndTrendRes{
WeResUserInfoStruct: api_we_student.WeResUserInfoStruct{
Master: r == 2,
ID: cardUserID,
Name: cardUserInfo.Name,
Sex: cardUserInfo.Sex,
Area: cache.GetAreaMapName(cardUserInfo.AreaID, true),
//Grade: cardUserInfo.Grade,
//Class: cardUserInfo.Class,
//StuNum: cardUserInfo.StuNum,
Birthday: cardUserInfo.Birthday,
},
Service: [6]uint8{1, 2, 2, 2, 2, 2},
Service: service,
Trend: cache.GetCardUserTrendMapByCardUserID(cardUserID),
},
})
......
package api_we
package api_we_student
import (
"dc_golang_server_1/api"
......@@ -9,6 +9,7 @@ import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
"time"
)
//type creatCardUserRes struct {
......@@ -17,13 +18,13 @@ import (
//}
// CreateCardUser 创建一个学生
// @Tags 家长微信
// @Summary 创建一个学生 [同一微信号并发创建学生,WechatCustomerMap缓存弱安全complete]
// @Tags 家长微信-学生
// @Summary 创建一个学生[complete]
// @Description 传新建学生信息至后台,后台返回学生id,以及对应校区的service
// @Accept json
// @Produce json
// --@Param data body dbcurd.InsertTableUCardUserStruct true "学生信息"
// @Success 0
// @Param data body dbcurd.InsertTableUCardUserStruct true "学生信息"
// @Success 0 {object} integer true "新创建的学生ID"
// @Router /we/carduser [POST]
// @Security ApiKeyAuth
func CreateCardUser(c *gin.Context) {
......@@ -40,46 +41,53 @@ func CreateCardUser(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("CreateCardUser",
zap.Reflect("c.Get(\"userID\")", v))
return
}
// 校验Birthday
if len(reqData.Birthday) > 0 {
_, err = time.Parse("2006-01", reqData.Birthday)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqParaFormat,
"message": api.CodeMsg[api.ErrorReqParaFormat] + " 出生年月格式错误",
})
return
}
}
newID := dbcurd.InsertUCardUserAndUserWeCardUser(&reqData, weUserID) //插入数据库
if newID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
//更新微信用户缓存,添加该学生
if cache.InsertNewStudentIDToWechatCustomerMap(weUserID, newID, true) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
//添加学生缓存
cache.CardUserMap.Store(newID, model.CacheCardUserStruct{
cache.CreatCardUserMap(newID, &model.CacheCardUserStruct{
AreaID: reqData.AreaID,
Name: reqData.Name,
Sex: reqData.Sex,
Grade: reqData.Grade,
Class: reqData.Class,
StuNum: reqData.StuNum,
Birthday: reqData.Birthday,
MasterWechatUserID: weUserID,
})
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
//"data": creatCardUserRes{
// newID,
// // [6]uint8{1, 2, 2, 2, 2, 2},
//},
"data": newID,
})
}
package api_we
package api_we_student
import (
"dc_golang_server_1/api"
......@@ -12,7 +12,7 @@ import (
)
// DeleteCardUser 主家长删除一个学生
// @Tags 家长微信
// @Tags 家长微信-学生
// @Summary 主家长删除一个学生,(当家长点删除时弹框二次确认)[并发弱安全complete]
// @Description 传学生ID至后台,后台返回成功失败
// @Produce json
......@@ -76,14 +76,13 @@ func DeleteCardUser(c *gin.Context) {
return
}
// 再删缓存 1.simInfoMap 2.WechatCustomerMap 3.cardUserTrendMap 4.CardUserMap
cache.CardUserMap.Delete(cardUserID)
cache.CardUserTrendMap.Delete(cardUserID)
// 再删缓存 1.simInfoMap 2.wechatCustomerMap 3.cardUserTrendMap 4.cardUserMap
cache.DeleteCardUserMap(cardUserID)
cache.DeleteCardUserTrendMap(cardUserID)
cache.DeleteAStudentIDInWechatCustomerMap(cardUserInfo.MasterWechatUserID, cardUserID, true)
for _, v := range cardUserInfo.SlaveWechatUserID {
cache.DeleteAStudentIDInWechatCustomerMap(v, cardUserID, false)
}
cache.SimInfoMap.Delete(cardUserInfo.SimCardID)
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
......
package api_we_student
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
// GetAreaName 根据区域ID查询区域名字
// @Tags 家长微信-学生
// @Summary 根据区域ID查询区域名字[complete]
// @Description 根据区域ID查询区域名字
// @Produce json
// @Param id path integer true "区域ID"
// @Success 0 {object} string true "名字"
// @Router /we/areaname/{id} [GET]
// @Security ApiKeyAuth
func GetAreaName(c *gin.Context) {
idInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": cache.GetAreaMapName(uint32(idInt), true),
})
}
// GetAreaServicePhone 根据区服务ID查询区域服务服务电话
// @Tags 家长微信-学生
// @Summary 根据区服务ID查询区域服务服务电话[complete]
// @Description 根据区服务ID查询区域服务服务电话
// @Produce json
// @Param id path integer true "区域服务ID"
// @Success 0 {object} string true "服务电话"
// @Router /we/areaservicephone/{id} [GET]
// @Security ApiKeyAuth
func GetAreaServicePhone(c *gin.Context) {
idInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
info := cache.GetAreaServiceInfo(uint32(idInt))
if info == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": "aid错误:系统找不到该区域服务",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": info.ServicePhone,
})
}
\ No newline at end of file
package api_we
package api_we_student
import (
"dc_golang_server_1/api"
......@@ -11,19 +11,19 @@ import (
"strconv"
)
type getCardUserAndTrendRes struct {
weResUserInfoStruct
Service [6]uint8 `json:"service" example:"1,2,2,0,0,0"` // 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
type GetCardUserAndTrendRes struct {
WeResUserInfoStruct
Service []ServiceStruct `json:"service"` // 服务列表,有几个显示几个
Trend []model.CacheCardUserTrendStruct `json:"trend"`
}
// GetCardUserAndTrend 获取单个学生信息和最新动态
// @Tags 家长微信
// @Tags 家长微信-学生
// @Summary 获取单个学生信息和最新动态[complete]
// @Description 传学生的ID,后台返回学生信息和最新动态
// @Produce json
// @Param id path integer true "学生ID"
// @Success 0 {object} getCardUserAndTrendRes "学生信息和最新动态"
// @Success 0 {object} GetCardUserAndTrendRes "学生信息和最新动态"
// @Router /we/cardusertrend/{id} [GET]
// @Security ApiKeyAuth
func GetCardUserAndTrend(c *gin.Context) {
......@@ -48,35 +48,94 @@ func GetCardUserAndTrend(c *gin.Context) {
})
return
}
// 用户是否为测试用户
testRole, ok := cache.GetWechatCustomerTestRole(weUserID.(uint32))
if ok == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
// 查出该学生信息
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID.(uint32))
if r < 2 { // 用户根本没得这个学生的权限,有问题
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
// 根据学生所在的学校ID查询其区域服务[]ID
areaInfo := cache.GetAreaMapInfo(cardUserInfo.AreaID)
if areaInfo == nil || areaInfo.Status < 2 { // 查不到该区域或区域状态不对
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("api_we_student.GetCardUserAndTrend() 区域状态不对",
zap.Reflect("cardUserInfo", cardUserInfo),
zap.Reflect("areaInfo", areaInfo),
zap.Uint32("cardUserID", cardUserID))
return
}
var master bool
if r == 2 {
master = true
var service []ServiceStruct
for _, areaServiceID := range areaInfo.AreaServiceID {
areaServiceInfo := cache.GetAreaServiceInfo(areaServiceID)
if areaServiceInfo != nil {
if areaServiceInfo.Status == 1 { // 正式 // 状态 0无内容1正式2测试3暂停4暂未开放
// if areaServiceInfo.ServiceType == 1 { // 1公话2定位3饮水4卡消费5洗浴6洗衣机 目前只支持公话
service = append(service, ServiceStruct{
areaServiceInfo.Name,
areaServiceID,
areaServiceInfo.ServiceType,
})
//}
} else if areaServiceInfo.Status == 2 && testRole { // 测试
service = append(service, ServiceStruct{
areaServiceInfo.Name,
areaServiceID,
areaServiceInfo.ServiceType,
})
} else if areaServiceInfo.Status == 4 {
service = append(service, ServiceStruct{
areaServiceInfo.Name,
0, // 暂未开放传0
areaServiceInfo.ServiceType,
})
}
} else {
logger.Log.Error("api_we_student.GetCardUserAndTrend() 区域服务为空不对",
zap.Reflect("cardUserInfo", cardUserInfo),
zap.Reflect("areaInfo", areaInfo),
zap.Reflect("areaServiceID", areaServiceID),
zap.Uint32("cardUserID", cardUserID))
}
}
if service == nil {
service = append(service, ServiceStruct{"公话", 0, 1})
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": getCardUserAndTrendRes{
weResUserInfoStruct: weResUserInfoStruct{
master,
"data": GetCardUserAndTrendRes{
WeResUserInfoStruct: WeResUserInfoStruct{
r == 2,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, true),
cardUserInfo.Grade,
cardUserInfo.Class,
cardUserInfo.StuNum,
//cardUserInfo.Grade,
//cardUserInfo.Class,
//cardUserInfo.StuNum,
cardUserInfo.Birthday,
// GetCardUserDownSmallAvatarQiNiuURL(cardUserID),
},
Service: [6]uint8{1, 2, 2, 2, 2, 2},
Service: service, //append(service, ServiceStruct{"定位", 0, 2}, ServiceStruct{"饮水", 0, 3}),
Trend: cache.GetCardUserTrendMapByCardUserID(cardUserID),
},
})
......
package api_we
package api_we_student
import (
"dc_golang_server_1/api"
......@@ -10,20 +10,21 @@ import (
"strconv"
)
type GetCardUserInfoRes struct {
weResUserInfoStruct
Service [6]uint8 `json:"service" example:"1,2,2,0,0,0"` // 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
type ServiceStruct struct {
Name string `json:"name" example:"公话"` // 图标上显示的名字
AID uint32 `json:"aid" example:"1"` // 校区服务ID,充值之类的要用的,如果为0,则点击提示校区暂未开通该服务
Type uint8 `json:"type" example:"1"` // 1公话2定位3饮水4卡消费5洗浴6洗衣机
}
// GetCardUser 获取单个学生信息
// @Tags 家长微信
// @Summary 获取单个学生信息 [complete]
// @Description 传学生的ID,后台返回学生信息
// @Produce json
// @Param id path integer true "学生ID"
// @Success 0 {object} GetCardUserInfoRes "学生信息"
// @Router /we/carduser/{id} [GET]
// @Security ApiKeyAuth
// @//Tags 家长微信-学生
// @//Summary 获取单个学生信息 [complete]
// @//Description 传学生的ID,后台返回学生信息
// @//Produce json
// @//Param id path integer true "学生ID"
// @//Success 0 {object} WeResUserInfoStruct "学生信息"
// @//Router /we/carduser/{id} [GET]
// @//Security ApiKeyAuth
func GetCardUser(c *gin.Context) {
cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
cardUserID := uint32(cardUserIDInt)
......@@ -51,31 +52,38 @@ func GetCardUser(c *gin.Context) {
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID.(uint32))
if r < 2 { // 用户根本没得这个学生的权限,有问题
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
var master bool
if r == 2 {
master = true
// 根据学生所在的学校ID查询其区域服务[]ID
areaInfo := cache.GetAreaMapInfo(cardUserInfo.AreaID)
if areaInfo == nil || areaInfo.Status < 2 { // 查不到该区域或区域状态不对
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("api_we_student.GetCardUser() 区域状态不对",
zap.Reflect("cardUserInfo", cardUserInfo),
zap.Reflect("areaInfo", areaInfo),
zap.Uint32("cardUserID", cardUserID))
return
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": GetCardUserInfoRes{
weResUserInfoStruct: weResUserInfoStruct{
master,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, true),
cardUserInfo.Grade,
cardUserInfo.Class,
cardUserInfo.StuNum,
},
Service: [6]uint8{1, 2, 2, 2, 2, 2},
"data": WeResUserInfoStruct{
r == 2,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, true),
cardUserInfo.Birthday,
//cardUserInfo.Class,
//cardUserInfo.StuNum,
// GetCardUserDownSmallAvatarQiNiuURL(cardUserID),
},
})
}
package api_we
package api_we_student
import (
"dc_golang_server_1/api"
......@@ -11,7 +11,7 @@ import (
)
// GetCardUserTrend 微信学生首页,获取近20条用户最新动态
// @Tags 家长微信
// @Tags 家长微信-学生
// @Summary 微信学生首页,获取近20条用户最新动态 [complete]
// @Description 微信学生首页,获取近20条用户最新动态
// @Param id path integer true "学生ID"
......@@ -34,8 +34,8 @@ func GetCardUserTrend(c *gin.Context) {
weUserID := v.(uint32)
if ok != true || weUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("GetCardUserTrend",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -45,8 +45,8 @@ func GetCardUserTrend(c *gin.Context) {
// 校验weUserID是否有cardUserID权限
if cache.CheckCardUserMaserAndSlaveWeID(uint32(cardUserID), weUserID) < 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
......
package api_we
package api_we_student
import (
"dc_golang_server_1/api"
......@@ -9,17 +9,19 @@ import (
"net/http"
)
type weResUserInfoStruct struct {
type WeResUserInfoStruct struct {
Master bool `json:"master"` // 是否为主家长
ID uint32 `json:"id"` // 学生ID
Name string `json:"name"`
Sex uint8 `json:"sex"` // 0无意义 1女 2男
Area string `json:"area" example:"温江实验中学"` // 区域名字
Grade int8 `json:"grade"` // 0无意义 "1~9对应一年级~九年级,10~12对应高一~高三"
Class int8 `json:"class"` // 0无意义
StuNum string `json:"stuNum"` // ""无意义
//Grade int8 `json:"grade"` // 0无意义 "1~9对应一年级~九年级,10~12对应高一~高三"
//Class int8 `json:"class"` // 0无意义
//StuNum string `json:"stuNum"` // ""无意义
Birthday string `json:"birthday"`
// Service [6]uint8 `json:"service" example:"1,2,2,0,0,0"` // 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
// TopUp bool `json:"topUp"` // 是否已充值(已充值则不能删除,未充值可以删除)
// Avatar string `json:"avatar"` // 头像请求的地址
}
//type weUserListStruct struct {
......@@ -28,11 +30,11 @@ type weResUserInfoStruct struct {
//}
// GetStudentList 获取学生列表
// @Tags 家长微信
// @Tags 家长微信-学生
// @Summary 获取学生列表 [complete]
// @Description 获取学生列表
// @Product json
// @Success 0 {object} []weResUserInfoStruct
// @Success 0 {object} []WeResUserInfoStruct
// @Router /we/stulist [GET]
// @Security ApiKeyAuth
func GetStudentList(c *gin.Context) {
......@@ -40,8 +42,8 @@ func GetStudentList(c *gin.Context) {
userID := v.(uint32)
if ok != true || userID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("GetStudentList",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -57,19 +59,21 @@ func GetStudentList(c *gin.Context) {
return
}
var res []weResUserInfoStruct
var res []WeResUserInfoStruct
for _, cardUserID := range userInfo.MasterCardUserID {
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo != nil {
res = append(res, weResUserInfoStruct{
res = append(res, WeResUserInfoStruct{
true,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, userInfo.TestRole),
cardUserInfo.Grade,
cardUserInfo.Class,
cardUserInfo.StuNum,
//cardUserInfo.Grade,
//cardUserInfo.Class,
//cardUserInfo.StuNum,
cardUserInfo.Birthday,
// GetCardUserDownSmallAvatarQiNiuURL(cardUserID),
})
}
}
......@@ -77,15 +81,17 @@ func GetStudentList(c *gin.Context) {
for _, cardUserID := range userInfo.SlaveCardUserID {
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo != nil {
res = append(res, weResUserInfoStruct{
res = append(res, WeResUserInfoStruct{
false,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, userInfo.TestRole),
cardUserInfo.Grade,
cardUserInfo.Class,
cardUserInfo.StuNum,
//cardUserInfo.Grade,
//cardUserInfo.Class,
//cardUserInfo.StuNum,
cardUserInfo.Birthday,
// GetCardUserDownSmallAvatarQiNiuURL(cardUserID),
})
}
}
......
package api_we
package api_we_student
import (
"dc_golang_server_1/api"
......@@ -10,10 +10,11 @@ import (
"go.uber.org/zap"
"net/http"
"strconv"
"time"
)
// PutCardUser 修改学生信息
// @Tags 家长微信
// @Tags 家长微信-学生
// @Summary 修改学生信息 [complete]
// @Description 传学生id及新信息至后台,后台返回成功失败
// @Accept json
......@@ -39,8 +40,8 @@ func PutCardUser(c *gin.Context) {
masterWeUserID := v.(uint32)
if ok != true || masterWeUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("DeleteSlaveBindCardUser",
zap.Reflect("c.Get(\"userID\")", v))
......@@ -50,8 +51,8 @@ func PutCardUser(c *gin.Context) {
// 校验weUserID是否有cardUserID权限
if cache.CheckCardUserMaserAndSlaveWeID(cardUserID, masterWeUserID) < 2 { // todo 其实后面会查,所以这里不用调这个函数,但是暂时并发不安全,先查一盘,后面查完马上改
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
......@@ -66,29 +67,42 @@ func PutCardUser(c *gin.Context) {
return
}
// 校验Birthday
if len(reqData.Birthday) > 0 {
_, err = time.Parse("2006-01", reqData.Birthday)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqParaFormat,
"message": api.CodeMsg[api.ErrorReqParaFormat] + " 出生年月格式错误",
})
return
}
}
if dbcurd.UpdateUCardUserInfo(cardUserID, &reqData) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
userInfo := cache.GetCardUserInfo(cardUserID)
if userInfo != nil { // 这里并发不安全
userInfo.Sex = reqData.Sex
userInfo.Grade = reqData.Grade
userInfo.Class = reqData.Class
userInfo.Name = reqData.Name
userInfo.StuNum = reqData.StudentNo
cache.CardUserMap.Store(cardUserID, *userInfo)
// 更新缓存
if cache.UpdateCardUserMap(cardUserID, &model.CacheUpdateCardUserStruct{
Sex: &reqData.Sex,
//Grade: &reqData.Grade,
//Class: &reqData.Class,
Name: &reqData.Name,
//StuNum: &reqData.StudentNo,
Birthday: &reqData.Birthday,
}) {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
}
}
package api_we_student
//const (
// bucket = "k12-avatar"
// url = "https://k12avatar.dcrym.com"
// accessKey = "KetEqWbfKrA7V8lNcQbLZJQszlFDVbk9H3nCPFmz"
// secretKey = "3LFimEUOs7G7l_vsTViIkIyRjAOXs_jlvTunwhG5"
//)
//// GetCardUserUploadAvatarQiNiuToken 根据学生ID获取学生头像上传的token
//// @Tags 家长微信-学生
//// @Summary 根据学生ID获取学生头像上传的token [complete]
//// @Description 根据学生ID获取学生头像上传的token
//// @Produce json
//// @Param id path integer true "学生ID"
//// @Success 0 {object} string "upLoadToken"
//// @Router /we/qiniu/uptoken/{id} [GET]
//// @Security ApiKeyAuth
//func GetCardUserUploadAvatarQiNiuToken(c *gin.Context) {
// cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
// cardUserID := uint32(cardUserIDInt)
// if cardUserID == 0 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqPara,
// "message": api.CodeMsg[api.ErrorReqPara] + " id不正确",
// })
// return
// }
// // todoTodo 加鉴权
// // 需要覆盖的文件名为 cardUserID
// putPolicy := storage.PutPolicy{
// Scope: bucket + ":" + strconv.FormatUint(uint64(cardUserID),10) + ".png",
// }
// mac := qbox.NewMac(accessKey, secretKey)
//
// c.JSON(http.StatusOK, gin.H{
// "code": api.Success,
// "data": putPolicy.UploadToken(mac),
// })
//}
//
////GetCardUserDownBigAvatarQiNiuURL 根据学生ID获取学生大头像下载的url
////@Tags 家长微信-学生
////@Summary 根据学生ID获取学生大头像下载的token [complete]
////@Description 根据学生ID获取学生大头像下载的token
////@Produce json
////@Param id path integer true "学生ID"
////@Success 0 {object} string "url"
////@Router /we/qiniu/downbigurl/{id} [GET]
////@Security ApiKeyAuth
//func GetCardUserDownBigAvatarQiNiuURL(c *gin.Context) {
// cardUserIDInt, _ := strconv.ParseUint(c.Param("id"), 10, 32)
// cardUserID := uint32(cardUserIDInt)
// if cardUserID == 0 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqPara,
// "message": api.CodeMsg[api.ErrorReqPara] + " id不正确",
// })
// return
// }
// // todoTodo 加鉴权
// mac := qbox.NewMac(accessKey, secretKey)
//
// c.JSON(http.StatusOK, gin.H{
// "code": api.Success,
// "data":storage.MakePrivateURL(mac, url, strconv.FormatUint(uint64(cardUserID),10) + ".png", time.Now().Unix()+60),
// })
//}
//
//func GetCardUserDownSmallAvatarQiNiuURL(cardUserID uint32)string{
// mac := qbox.NewMac(accessKey, secretKey)
// //fmt.Println(storage.MakePrivateURLv2WithQueryString(mac,url,strconv.FormatUint(uint64(cardUserID),10) + ".png","imageView2/1/w/80/h/80/format/png/q/75",time.Now().Unix()+60))
// //fmt.Println(storage.MakePrivateURL(mac, url, strconv.FormatUint(uint64(cardUserID),10) + ".png", time.Now().Unix()+60))
// //fmt.Println(storage.MakePrivateURLv2(mac, url, strconv.FormatUint(uint64(cardUserID),10) + ".png", time.Now().Unix()+60))
// return storage.MakePrivateURLv2WithQueryString(mac,url,strconv.FormatUint(uint64(cardUserID),10) + ".png","imageView2/1/w/60/h/60/q/75",time.Now().Unix()+60)
//}
\ No newline at end of file
package api
import (
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
func Cors() gin.HandlerFunc {
return func(context *gin.Context) {
if context.Request.Method == "OPTIONS" {
origin := context.Request.Header.Get("Origin")
var headerKeys []string
for k := range context.Request.Header {
headerKeys = append(headerKeys, k)
}
headerStr := strings.Join(headerKeys, ",")
if headerStr != "" {
headerStr = "access-control-allow-origin, access-control-allow-headers, " + headerStr //fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr) 测试了下,速度忆氧
} else {
headerStr = "access-control-allow-origin, access-control-allow-headers"
}
if origin != "" {
context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
context.Header("Access-Control-Max-Age", "172800")
context.Header("Access-Control-Allow-Credentials", "false")
context.Set("content-type", "application/json") //// 设置返回格式是json
}
context.JSON(http.StatusOK, "Options Request!")
}
context.Next()
}
}
//func Cors() gin.HandlerFunc {
// return func(c *gin.Context) {
// method := c.Request.Method
// origin := c.Request.Header.Get("Origin")
// var headerKeys []string
// for k, _ := range c.Request.Header {
// headerKeys = append(headerKeys, k)
// }
// headerStr := strings.Join(headerKeys, ", ")
// if headerStr != "" {
// headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
// } else {
// headerStr = "access-control-allow-origin, access-control-allow-headers"
// }
// if origin != "" {
// c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
// c.Header("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
// c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
// // header的类型
// c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
// // 允许跨域设置 可以返回其他子段
// c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
// c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
// c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
// c.Set("content-type", "application/json") // 设置返回格式是json
// }
//
// //放行所有OPTIONS方法
// //if method == "OPTIONS" {
// // c.JSON(http.StatusOK, "Options Request!")
// //}
// if method == "OPTIONS" {
// c.AbortWithStatus(204)
// return
// }
// // 处理请求
// c.Next() // 处理请求
// }
//}
//func Cors() gin.HandlerFunc {
// return func(context *gin.Context) {
// method := context.Request.Method
// origin := context.Request.Header.Get("Origin")
// var headerKeys []string
// for k, _ := range context.Request.Header {
// headerKeys = append(headerKeys, k)
// }
// headerStr := strings.Join(headerKeys, ",")
// if headerStr != "" {
// headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
// } else {
// headerStr = "access-control-allow-origin, access-control-allow-headers"
// }
//
// if origin != "" {
// context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
// context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
// context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
// context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
// context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
// context.Header("Access-Control-Max-Age", "172800")
// context.Header("Access-Control-Allow-Credentials", "false")
// context.Set("content-type", "application/json") //// 设置返回格式是json
// }
//
// if method == "OPTIONS" {
// context.JSON(http.StatusOK, "Options Request!")
// }
//
// context.Next()
// }
//}
......@@ -16,6 +16,9 @@ const (
ErrorReqPara = 11
ErrorReqInsertDuplicate = 12
ErrorDeleteCardUserHaveSimCard = 13
ErrorServiceStop = 14
ErrorSmsCaptchaErr = 40
ErrorMonthDeleteFamilyNumOverrun = 20
......@@ -38,6 +41,9 @@ var CodeMsg = map[uint16]string{
ErrorReqParaFormat: "请求参数格式错误",
ErrorReqInsertDuplicate: "内容重复,无法创建",
ErrorDeleteCardUserHaveSimCard: "已绑定电话卡,请解绑电话卡后再删除",
ErrorServiceStop: "对不起,该校区服务已暂停",
ErrorSmsCaptchaErr: "验证码错误",
ErrorMonthDeleteFamilyNumOverrun: "根据防电信诈骗相关规定,月删除亲情号次数不得超过2次,请于下月修改",
......
......@@ -20,7 +20,7 @@ type TokenResult struct {
CreatTime int64 //token创建时间
UserID uint32 //
ExpireTime uint32
UserType uint8 // 1微信家长 2后台用户 其余预留
UserType uint8 // 1微信家长 2后台用户 3硬件设备 4服务器请求 其余预留
CheckResult uint8
}
......@@ -140,7 +140,7 @@ func DecryptToken(token string) (clearStruct TokenResult) {
(uint32(clear[2]-166-random) << 16) +
(uint32(^(clear[0] + random)) << 24)
clearStruct.UserType = clear[16] + random
clearStruct.UserType = (clear[16] + random) & 0xf
if clearStruct.UserType != 1 && clearStruct.UserType != 2 {
// todo logger
......@@ -189,7 +189,7 @@ func JeffWTPublic() gin.HandlerFunc {
return
}
c.Set("userID", clearStruct.UserID)
c.Next()
// c.Next()
}
}
......@@ -216,7 +216,7 @@ func JeffWTWechat() gin.HandlerFunc {
return
}
c.Set("userID", clearStruct.UserID)
c.Next()
// c.Next()
}
}
......@@ -283,7 +283,7 @@ func JeffWTAdmin() gin.HandlerFunc {
return
}
c.Set("userID", clearStruct.UserID)
c.Next()
// c.Next()
}
}
......
package zzz_api_callback
//// AllinPay 通联支付结果回调函数
//func AllinPay(c *gin.Context) {
// buf, _ := ioutil.ReadAll(c.Request.Body)
// if allinpay.PayCallback(buf)
// //appId=1461169657065537537&bizContent=%7B%22amount%22%3A1%2C%22orderNo%22%3A%221492532599166345216%22%2C%22channelFee%22%3A%220%22%2C%22channelPaytime%22%3A%222022-02-13+00%3A14%3A58%22%2C%22extendInfo%22%3A%22%22%2C%22payInterfaceOutTradeNo%22%3A%22220213119414260683%22%2C%22buyerBizUserId%22%3A%22K12U14%22%2C%22cusid%22%3A%2255265104816Z9Z7%22%2C%22payInterfacetrxcode%22%3A%22VSP501%22%2C%22payDatetime%22%3A%222022-02-13+00%3A14%3A58%22%2C%22acct%22%3A%22orIcn5Wvy3spreKxhFtAfqUkcO9g%22%2C%22bizOrderNo%22%3A%22AAAADmIc8X8AAAABFtMV_6SIieBV%22%2C%22status%22%3A%22OK%22%7D&charset=utf-8&notifyId=1492532694216650754&notifyTime=2022-02-13+00%3A14%3A58&notifyType=allinpay.yunst.orderService.pay&sign=hgflZsSWWOfH1D%2B6%2B7sCig7%2FYgHw4QLqbrGlGsmMgCkchYka33gG5M3s4AuPFlQ8SWZ7RlyAmYaJryXW8LH3MUhL2DQWIEOAXgh5xgFl5VD7FC4afM8d2e8%2Bj8Y0Jpun3bB1QAssJ6KQakXdGYW3ifhGf6JGdZkiWhjtVOsGidrsN2BFlEAAHK9%2BjL8sTzMsodDwuBYtYBqSA%2B%2Fimp21VTFig5vVT5GGF5LOyDZvXPseb1aGY593lnez%2F5JSd0AW3fvMbMd5NOWE2Jq86JYGVuMbgVg%2BQKJRN4N2qsfa5C4gzfUfglwfVKKEEh2uFUhH5plm9%2FGjWUy3ZbXsqcbrcg%3D%3D&signType=SHA256WithRSA&version=1.0
// //orderNum, money := tencent.CallbackPayOrder(c.Request)
// //if len(orderNum) != 28 {
// // fmt.Println("微信支付回调,订单号长度错误",orderNum,money)
// // logger.Log.Error("api_callback.WechatPay orderNum.len!=28", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// // return // 订单号都不对,看看要不要回复它,免得它一直发
// //}
// //fmt.Println("微信支付回调", orderNum, money)
// //
// //bytes, err := base64.URLEncoding.DecodeString(orderNum)
// //if err != nil {
// // logger.Log.Error("api_callback.WechatPay base64.StdEncoding.DecodeString", zap.String("orderNum", orderNum), zap.Uint32("money", money), zap.Error(err))
// // return // 订单号都不对,看看要不要回复它,免得它一直发
// //}
// //if len(bytes)!=21 {
// // logger.Log.Error("api_callback.WechatPay len(bytes)!=21", zap.String("orderNum", orderNum), zap.Uint32("money", money), zap.Error(err))
// // return // 订单号都不对,看看要不要回复它,免得它一直发
// //}
// //// 订单号生成规则:4B cardUserID,4B到期时间,4B 金额amount,8B 时间纳秒
// //cardUserID := uint32(bytes[0])<<24 + uint32(bytes[1])<<16 +uint32(bytes[2])<<8 + uint32(bytes[3])
// //expiryUnix := int64(bytes[4])<<24 + int64(bytes[5])<<16 +int64(bytes[6])<<8 + int64(bytes[7])
// //// amount := uint32(bytes[8])<<24 + uint32(bytes[9])<<16 +uint32(bytes[10])<<8 + uint32(bytes[11])
// //if uint32(bytes[8])<<24 + uint32(bytes[9])<<16 +uint32(bytes[10])<<8 + uint32(bytes[11]) != money {
// // logger.Log.Error("api_callback.WechatPay uint32(amount) != money", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// // return // 订单金额不对,看看要不要回复它,免得它一直发
// //}
// //
// //expiry := time.Unix(expiryUnix,0)
// //// 1. 更新库 用事务处理
// //if dbcurd.UpdateUPhonePayRecordPayAtAndUCardUserPhoneExpiryTransaction(cardUserID, &expiry, time.Now(), orderNum) {
// // // 更新两个库都成功,那就写缓存回成功 2. 修改缓存的到期时间
// // if cache.UpdateCardUserMap(cardUserID, &model.CacheUpdateCardUserStruct{
// // PhoneExpiry: &expiry,
// // }) == false {
// // fmt.Println("WechatPay 写缓存失败", cardUserID)
// // }
// //
// // c.JSON(http.StatusOK, map[string]string{
// // "code": "SUCCESS",
// // "message": "成功",
// // })
// //}
// c.Status(404)
//}
\ No newline at end of file
package zzz_api_callback
//// WechatPay 微信支付结果回调函数
//func WechatPay(c *gin.Context) {
// orderNum, money := tencent.CallbackPayOrder(c.Request)
// if len(orderNum) != 28 {
// fmt.Println("微信支付回调,订单号长度错误",orderNum,money)
// logger.Log.Error("api_callback.WechatPay orderNum.len!=28", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
// fmt.Println("微信支付回调", orderNum, money)
//
// bytes, err := base64.URLEncoding.DecodeString(orderNum)
// if err != nil {
// logger.Log.Error("api_callback.WechatPay base64.StdEncoding.DecodeString", zap.String("orderNum", orderNum), zap.Uint32("money", money), zap.Error(err))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
// if len(bytes)!=21 {
// logger.Log.Error("api_callback.WechatPay len(bytes)!=21", zap.String("orderNum", orderNum), zap.Uint32("money", money), zap.Error(err))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
// // 订单号生成规则:4B cardUserID,4B到期时间,4B 金额amount,8B 时间纳秒
// cardUserID := uint32(bytes[0])<<24 + uint32(bytes[1])<<16 +uint32(bytes[2])<<8 + uint32(bytes[3])
// expiryUnix := int64(bytes[4])<<24 + int64(bytes[5])<<16 +int64(bytes[6])<<8 + int64(bytes[7])
// // amount := uint32(bytes[8])<<24 + uint32(bytes[9])<<16 +uint32(bytes[10])<<8 + uint32(bytes[11])
// if uint32(bytes[8])<<24 + uint32(bytes[9])<<16 +uint32(bytes[10])<<8 + uint32(bytes[11]) != money {
// logger.Log.Error("api_callback.WechatPay uint32(amount) != money", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单金额不对,看看要不要回复它,免得它一直发
// }
//
// expiry := time.Unix(expiryUnix,0)
// // 1. 更新库 用事务处理
// if dbcurd.UpdateUPhonePayRecordPayAtAndUCardUserPhoneExpiryTransaction(cardUserID, &expiry, time.Now(), orderNum) {
// // 更新两个库都成功,那就写缓存回成功 2. 修改缓存的到期时间
// if cache.UpdateCardUserMap(cardUserID, &model.CacheUpdateCardUserStruct{
// PhoneExpiry: &expiry,
// }) == false {
// fmt.Println("WechatPay 写缓存失败", cardUserID)
// }
//
// c.JSON(http.StatusOK, map[string]string{
// "code": "SUCCESS",
// "message": "成功",
// })
// }
//}
//
//
//type wechatPayCallbackTest struct {
// OrderNum string `json:"orderNum"`
// Money uint32 `json:"money"`
//}
//
//// WechatPayTest 假的微信支付结果回调函数
//// @Tags 假的微信支付结果回调函数
//// @Summary 假的微信支付结果回调函数[complete]
//// @Description 假的微信支付结果回调函数
//// @Accept json
//// @Produce json
//// @Param data body wechatPayCallbackTest true "支付信息"
//// @Success 0 {object} tencent.WxMiniRequestPayment "微信支付信息"
//// @Router /callback/wechat/paytest [POST]
//// @Security ApiKeyAuth
//func WechatPayTest(c *gin.Context) {
// var reqData wechatPayCallbackTest
// err := c.ShouldBindJSON(&reqData)
// if err != nil {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqParaFormat,
// "message": api.CodeMsg[api.ErrorReqParaFormat],
// })
// return
// }
//
// orderNum, money := reqData.OrderNum,reqData.Money
// if len(orderNum) != 28 {
// fmt.Println("微信支付回调,订单号长度错误",orderNum,money)
// logger.Log.Error("api_callback.WechatPay orderNum.len!=28", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
// fmt.Println("微信支付回调", orderNum, money)
//
// bytes, err := base64.URLEncoding.DecodeString(orderNum)
// if err != nil {
// logger.Log.Error("api_callback.WechatPay base64.StdEncoding.DecodeString", zap.String("orderNum", orderNum), zap.Uint32("money", money), zap.Error(err))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
// if len(bytes)!=21 {
// logger.Log.Error("api_callback.WechatPay len(bytes)!=21", zap.String("orderNum", orderNum), zap.Uint32("money", money), zap.Error(err))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
// // 订单号生成规则:4B cardUserID,4B到期时间,4B 金额amount,8B 时间纳秒
// cardUserID := uint32(bytes[0])<<24 + uint32(bytes[1])<<16 +uint32(bytes[2])<<8 + uint32(bytes[3])
// expiryUnix := int64(bytes[4])<<24 + int64(bytes[5])<<16 +int64(bytes[6])<<8 + int64(bytes[7])
// // amount := uint32(bytes[8])<<24 + uint32(bytes[9])<<16 +uint32(bytes[10])<<8 + uint32(bytes[11])
// if uint32(bytes[8])<<24 + uint32(bytes[9])<<16 +uint32(bytes[10])<<8 + uint32(bytes[11]) != money {
// logger.Log.Error("api_callback.WechatPay uint32(amount) != money", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单金额不对,看看要不要回复它,免得它一直发
// }
//
// expiry := time.Unix(expiryUnix,0)
// // 1. 更新库 用事务处理
// if dbcurd.UpdateUPhonePayRecordPayAtAndUCardUserPhoneExpiryTransaction(cardUserID, &expiry, time.Now(), orderNum) {
// // 更新两个库都成功,那就写缓存回成功 2. 修改缓存的到期时间
// if cache.UpdateCardUserMap(cardUserID, &model.CacheUpdateCardUserStruct{
// PhoneExpiry: &expiry,
// })==false {
// fmt.Println("WechatPay 写缓存失败", cardUserID)
// // 咋个处理下
// }
//
// c.JSON(http.StatusOK, map[string]string{
// "code": "SUCCESS",
// "message": "成功",
// })
// }
//}
//// WechatPay 微信支付结果回调函数
//func WechatPay(c *gin.Context) {
// fmt.Println("微信支付回调")
// orderNum, money := tencent.CallbackPayOrder(c.Request)
// if len(orderNum) == 0 {
// logger.Log.Error("api_callback.WechatPay orderNum==\"\"", zap.Uint32("money", money))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
// fmt.Println("微信支付回调",orderNum,money)
// // 订单号生成规则:cardUserID_金额_productTime_话费到期时间 8B 时间纳秒,4BcardUserID,4B 金额amount,+ 到期时间
// orderInfo := strings.Split(orderNum, "_")
// if len(orderInfo) != 4 {
// logger.Log.Error("api_callback.WechatPay len(orderInfo) != 4", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
//
// cardUserIDU64, err := strconv.ParseUint(orderInfo[0], 10, 32)
// if err != nil {
// logger.Log.Error("api_callback.WechatPay cardUserID err", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
//
// amount, err := strconv.ParseUint(orderInfo[1], 10, 32)
// if err != nil {
// logger.Log.Error("api_callback.WechatPay amount err", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
// if uint32(amount) != money {
// logger.Log.Error("api_callback.WechatPay uint32(amount) != money", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单金额不对,看看要不要回复它,免得它一直发
// }
//
// _, err = time.Parse("060102150405.000000000",orderInfo[2])
// if err != nil {
// logger.Log.Error("api_callback.WechatPay insertID err", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
//
// expiry,err := time.Parse("2006-01-02",orderInfo[3])
// if err != nil {
// logger.Log.Error("api_callback.WechatPay expiry err", zap.String("orderNum", orderNum), zap.Uint32("money", money))
// return // 订单号都不对,看看要不要回复它,免得它一直发
// }
//
// cardUserID := uint32(cardUserIDU64)
// // 1. 更新库 用事务处理
// if dbcurd.UpdateUPhonePayRecordPayAtAndUCardUserPhoneExpiryTransaction(cardUserID,orderInfo[4],time.Now(),orderNum) {
// // 更新两个库都成功,那就写缓存回成功 2. 修改缓存的到期时间
// if cache.UpdateCardUserMap(cardUserID,&model.CacheUpdateCardUserStruct{
// PhoneExpiry: &expiry,
// }) {
// fmt.Println("WechatPay 写缓存失败",cardUserID)
// // todoN 咋个处理下
// }
//
// c.JSON(http.StatusOK, map[string]string{
// "code": "SUCCESS",
// "message": "成功",
// })
// }
//}
set GOARCH=amd64
set GOOS=linux
swag init
go build -o dcGoServer1 -ldflags "-w -s" main.go
\ No newline at end of file
go build -o customerServer.new -ldflags "-w -s" main.go
\ No newline at end of file
set GOOS=linux
swag init
go build -o dcGoServer2 -ldflags "-w -s" main.go
\ No newline at end of file
[database]
#阿里云9.9 外网
#dbDSN = "user=higher password=hj^&bhjb789j$^* dbname=dctest1 host=pgm-2ze3yp0bss39cxvh1o.pg.rds.aliyuncs.com port=1921 sslmode=disable"
#阿里云9.9 内网 pgm-2ze3yp0bss39cxvh129210.pg.rds.aliyuncs.com
#dbDSN = "user=higher password=hj^&bhjb789j$^* dbname=jeff_study host=pgm-2ze3yp0bss39cxvh129210.pg.rds.aliyuncs.com port=1921 sslmode=disable"
#chengdu-office 内网 192.168.1.42:5432
#dbDSN = "user=postgres password=buzhidao123. dbname=dctest1 host=192.168.1.42 port=5432 sslmode=disable"
#chengdu-office 外网 to-chengdu-office.168cad.top:50032
#dbDSN = "user=postgres password=buzhidao123 dbname=dctest1 host=to-chengdu-office.168cad.top port=50032 sslmode=disable"
[sys_para]
#每个用户允许添加的亲情号数量
MaxFamilyNum = 2
[database]
#ECS外网
dbDSN = "user=postgres password=buzhidao123. dbname=jeff host=60.205.190.129 port=59999 sslmode=disable"
dbDSN = user=postgres password=buzhidao123. dbname=jeff host=60.205.190.129 port=59999 sslmode=disable
#ECS内网
#dbDSN = "user=postgres password=buzhidao123. dbname=jeff host=127.0.0.1 port=59999 sslmode=disable"
#dbDSN = user=postgres password=buzhidao123. dbname=jeff host=127.0.0.1 port=59999 sslmode=disable
[http_server]
#debug release
ServerMode = release
ServerPort = :50000
Swagger = true
# k12m.dcrym.com
MainHost = https://k12t.shero.plus
ServerPort = :6010
# true 表示使用https false 表示使用http
# HttpSSL = true
# Swagger = true
[tcp_long_server]
#TCP服务监听的端口号
TcpPort = 60000
TcpPort = 8010
#TCP 最大连接数限制,建议设置实际设备数量的2.5倍
MaxConnections = 20000
#新建立的TCP连接,连上后多久完全没收到数据就判断为非法设备断掉,单位秒
......@@ -32,6 +28,22 @@ NewConnRightfulTimeout = 120
#老连接(已验证通过确实是合法设备的tcp连接),多久没收到数据就断掉,这里设置为3倍心跳时间(若同一台设备建立了新连接,系统会立即释放老连接)
OldConnReadDeadline = 180
[wechat]
AppId = wx7b2ba9d192edd163
AppSecret = 8e007ad30204af2a64af27ecc88b54e7
#服务商ID
#OurSpMchID = 1607746840
[sms_captcha]
#短信验证码服务器请求地址
#url = http://127.0.0.1:6051
url = http://192.168.1.43:6051
[firmware_server]
#固件服务器地址
baseUrl = http://192.168.1.41:6031
deviceUrl = http://k12t.shero.plus:6031
[log]
#debug info warn error 只允许设置这4个等级,以保证至少记录error DPanic Panic Fatal
#debug info: 记录流水数据(都存在info.log里)
......@@ -49,11 +61,11 @@ InfoMaxFileNum = 30
InfoWithMaxAge = 30
#warn级别日志最多保存多少份
WarnMaxFileNum = 30
WarnMaxFileNum = 30mk
#warn日志最长保留天数
WarnWithMaxAge = 90
#Error级别日志最多保存多少份
ErrorMaxFileNum = 10
#Error日志最长保留天数s
ErrorWithMaxAge = 180
ErrorWithMaxAge = 180
\ No newline at end of file
......@@ -16,128 +16,55 @@ func Init() {
initAreaServiceMap()
initPhone20DeviceMap()
initCardUserTrendMap()
initAreaServicePhonePayListMap()
areaServicePhonePayListMapAddSplit() // 区域服务收款项列表添加分账列表
// initWechatMchInfoMap()
initDeviceUpdateFirmwareMapPhone20()
}
// ProvinceMap /*********************************************************全国行政区域**/------------------------OK
var ProvinceMap []model.CacheBDistrictStruct // 省份列表[]model.CacheBDistrictStruct
var CityMap sync.Map // 城市列表map[uint32][]model.CacheBDistrictStruct //省份ID作为KEY
var CountyMap sync.Map // 区县列表map[uint32][]model.CacheBDistrictStruct //城市ID作为KEY
//type CacheBDistrictStruct struct {
// Id uint32 `json:"id" example:"1"`
// Name string `json:"name" example:"四川省"`
// Initial string `json:"initial" example:"S"`
//}
// 全国行政区域
var provinceList []model.CacheBDistrictStruct // 省份列表[]model.CacheBDistrictStruct 只能查
var CityMap sync.Map // 城市列表map[uint32][]model.CacheBDistrictStruct //省份ID作为KEY 只能查 //todoN 改成小写
var CountyMap sync.Map // 区县列表map[uint32][]model.CacheBDistrictStruct //城市ID作为KEY 只能查 //todoN 改成小写
// CountyAreaMap /******************************************************************区县学校列表**/
var CountyAreaMap sync.Map //map[uint32][[]uint32] 区县ID作为KEY,[]area_id 作为Value
// var LockCountyAreaMap bool // todo 正规的做法是用 map[区县ID]bool
// AreaMap /******************************************************区域(校区)**/
var AreaMap sync.Map //area_id 作为KEY CacheBAreaStruct 作为VALUE
//type CacheBAreaStruct struct { // CacheBAreaStruct 区域信息缓存,通过区域ID查出
// Name string
// Longitude uint32
// Latitude uint32
//// CountyID uint32
//// AreaService []uint32
// Status uint8 //校区状态 0 不展示 1展示 2测试校区
//}
//countyAreaMap 各区县ID:学校ID列表 map[uint32_countID][]uint32_areaID -----OK
var countyAreaMap sync.Map // 列表,全局锁增删改 仅GRPC
// var LockAreaMapAreaService bool todo
// 区域(校区) map[uint32_areaID]model.CacheBAreaStruct -----OK
var areaMap sync.Map // 有列表,全局锁增删改 仅GRPC
/******************************************************区域(校区)服务信息**/
var areaServiceMap sync.Map //area_service_id 作为KEY CacheBAreaStruct 作为VALUE //status不为0的所有校区服务
//type AreaServiceStruct struct { // 后续再加支付信息
// AreaID uint32
// ServiceType uint8 //服务项目 1公话 2定位 3饮水 4POS .........
// OperatorID uint32 //运营商ID
// //Name string //服务名字(例宿舍135栋饮水)name
// Status uint8 //状态 0无内容1正式2测试3暂停4暂未开放
//}
// status不为0的所有区域服务 map[uint32_areaServiceID]model.CacheAreaServiceStruct -----OK
var areaServiceMap sync.Map // 无列表,直接增删改 仅GRPC
/*---------------------------------------------------------------*/
// 校区服务支付信息 map[uint32_areaServiceID][]model.CacheAreaServicePhonePayListStruct 仅缓存库里面status==true的项 -----OK
var areaServicePhonePayListMap sync.Map // 列表,全局锁增删改 仅GRPC
// roleAuthMap /****************************角色权限(包含区域和系统角色)*/
//var adminRoleAuthMap sync.Map //admin_role_id 作为KEY
//type RoleAuthStruct struct {
// Name string
// MenuRole map[uint32][]uint32 // 菜单、按钮权限
//}
// 电话设备信息 map[uint32_deviceID]model.CachePhone20DeviceStruct -----OK
var phone20DeviceMap sync.Map // 无列表,直接增删改 仅GRPC // 只存绑定了校区的
// todo 加锁
/***************************************************微信用户(家长)**/ //------------------------OK
var WechatCustomerUnionIDToIDMAP sync.Map // UnionID作为KEY(string),微信用户ID作为VALUE(uint32)
var WechatCustomerMap sync.Map // 微信的WechatUserID(uint32)作为KEY
//type CacheWeCustomerStruct struct {
// TokenCreatTime int64
// TestRole bool // 测试用户(可看到测试校区)
// WePhone string // 手机号
// Nickname string // 微信昵称
// AvatarURL string // 头像链接
// MasterCardUserID []uint32 // 自己创建的学生用户
// SlaveCardUserID []uint32 // 被邀请查看的学生用户
//}
// simInfoMap Sim卡信息(存绑定了校区服务的卡,不管绑没绑定学生) map[string_simID]model.CacheSimInfoStruct -----OK
var simInfoMap sync.Map //有列表,大并发量,channel增删改
// todo 加锁
/****************************************************************/
//CardUserMap /***************************************************卡用户(学生、教师、职工)**/
var CardUserMap sync.Map //卡用户 CardUserID卡用户ID(uint32) 作为KEY 纯卡用户可以不绑定微信
//type CacheCardUserStruct struct {
// MasterWechatUserID uint32
// SlaveWechatUserID []uint32
// // Role uint8 //角色0学生,1教师,2职工,default0
// AreaID uint32
// Name string
// Sex uint8 //0,无信息,1女,2男
// // Birthday
// Grade int8
// Class int8
// StuNum string
// //Recharge bool //是否充过值
// SimCardID string
// LocationCardID uint32
// IcCardID uint32
//}
// 微信收款商户 map[string_mchID]model.CacheWechatMchInfoStruct
// var wechatMchInfoMap sync.Map // 无列表,直接增删改 仅GRPC
//var CardUserWechatMap sync.Map
// CardUserTrendMap /***************************************************卡用户动态**/
var CardUserTrendMap sync.Map //卡用户 CardUserID卡用户ID(uint32) 作为KEY,[]CardUserTrendStruct作为VALUE
//type CacheCardUserTrendStruct struct {
// ServiceType uint8 //服务项目 UI图标及颜色等
// DeviceID uint32
// Content string
// Time time.Time
//
/*---------------------------------------------------------------*/
/********************************************************Sim卡信息(仅存学生绑定了的)**/
var SimInfoMap sync.Map //sim_id(string) 作为KEY
//type CacheSimInfoStruct struct {
// CardUserID uint32 //卡用户ID
// AreaServiceID uint32
// Status uint8 //0无数据 1 正常使用 2 已挂失
// MonthTalkMinutes uint16
// MonthPackageMinutes uint16
// ExpiryAt time.Time
// FamilyNum []CacheFamilyOnePerson // 如果一张sim卡,到多个学校绑定不一样的亲情号,则改成MAP,但是移动不允许。先这样。
//}
//type CacheFamilyOnePerson struct {
// Phone string
// Nickname string
//WechatCustomerUnionIDToIDMAP 微信用户,用unionID查weUserID map[string_unionID]uint32_weUserID -----OK
var WechatCustomerUnionIDToIDMAP sync.Map // 直接增删改
//wechatCustomerMap 微信用户信息, map[uint32_weUserID]model.CacheWeCustomerStruct -----OK 有点复杂,多测试
var wechatCustomerMap sync.Map // 有列表,大并发量,channel增删改
var WechatCustomerTokenCreateTime sync.Map // map[weUserID:uint32]tokenCreateTime:int64
//var WechatCustomerLoginRecordStruct struct{
// TokenCreateTime int64
// CountP *uint32 // 这里存地址,就可以并发修改啦
// LastTime time.Time
//}
// todo 加锁FamilyNum
/*---------------------------------------------------------------*/
// 卡用户(学生、教师、职工 纯卡用户可以不绑定微信) map[uint32_cardUserID]model.CacheCardUserStruct -----OK
var cardUserMap sync.Map //有列表,大并发量,channel增删改
/*******************************************************电话设备**/
var phone20DeviceMap sync.Map //device_id 作为KEY CachePhone20DeviceStruct 作为VALUE //存放绑定了校区的设备
//type CachePhone20DeviceStruct struct {
//AreaServiceID uint32
//AllowCallTime uint8 //允许通话时长,255表示不限制时长
//PlaceUser string //位置,家长微信看到的
//Status bool
//}
// 学生最新动态 map[uint32_cardUserID][]model.CacheCardUserTrendStruct -----OK
var cardUserTrendMap sync.Map //有列表,全局锁增删改
/*---------------------------------------------------------------*/
// 固件升级缓存 存设备号和期望的固件版本,如果设备已经是期望版本,则删除
var deviceUpdateFirmwareMapPhone20 sync.Map // map[deviceID uint32]firmwareName string
package cache
import (
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"fmt"
"go.uber.org/zap"
"log"
"time"
)
//id integer NOT NULL DEFAULT nextval('b_area_id_seq'::regclass),
//county_id integer,
//name character varying(32) COLLATE pg_catalog."default",
//longitude integer,
//latitude integer,
//status smallint,
//creator_id integer,
//updater_id integer,
//create_at timestamp without time zone,
//update_at timestamp without time zone,
//CONSTRAINT b_area_pkey PRIMARY KEY (id),
//CONSTRAINT b_area_uniq1 UNIQUE (name)
func initAreaMapAndCountyAreaMap() {
fmt.Println(time.Now(), "cache: initAreaMap begin")
var areaID uint32
var temp model.CacheBAreaStruct
rows, err := dbcurd.PgDb.Query("SELECT id,county_id,name,longitude,latitude,status FROM b_area") //
if err != nil {
log.Panicln("SelectAreaToMap rows", err)
}
defer rows.Close()
var countyID uint32
for rows.Next() {
//err = rows.Scan(&areaID, &temp.CountyID, &temp.Name, &temp.Longitude, &temp.Latitude, &temp.Status)
err = rows.Scan(&areaID, &countyID, &temp.Name, &temp.Longitude, &temp.Latitude, &temp.Status)
if err != nil {
log.Panicln("SelectAreaToMap rows.Scan", err)
}
AreaMap.Store(areaID, temp)
//if temp.CountyID != 0 {
// var areaIDList []uint32
// if v, ok := CountyAreaMap.Load(temp.CountyID); ok {
// areaIDList, _ = v.([]uint32)
// }
// areaIDList = append(areaIDList, areaID)
// CountyAreaMap.Store(temp.CountyID, areaIDList)
//}
if countyID != 0 {
var areaIDList []uint32
if v, ok := CountyAreaMap.Load(countyID); ok {
areaIDList, _ = v.([]uint32)
}
areaIDList = append(areaIDList, areaID)
CountyAreaMap.Store(countyID, areaIDList)
}
}
// 处理完毕后,需要判断一次遍历过程中是否有错误产生
if err = rows.Err(); err != nil {
log.Panicln(time.Now(), "initAreaMap rows.Err()", err)
}
fmt.Println(time.Now(), "cache: initAreaMap OK")
}
func GetAreaMapName(areaID uint32, test bool) string {
if v, ok := AreaMap.Load(areaID); ok {
if data, ok := v.(model.CacheBAreaStruct); ok {
if data.Status == 1 || (data.Status == 2 && test) {
return data.Name
}
} else {
AreaMap.Delete(areaID)
logger.Log.Error("AreaMap 类型断言错误",
zap.String("Src", "GetAreaMapName"),
zap.Uint32("areaID", areaID))
}
} else {
logger.Log.Error("AreaMap 没数据",
zap.String("Src", "GetAreaMapName"),
zap.Uint32("areaID", areaID))
}
// todo 查库
return ""
}
func GetAreaMapInfo(areaID uint32) *model.CacheBAreaStruct {
//var info model.CacheBAreaStruct
if v, ok := AreaMap.Load(areaID); ok {
if info, ok := v.(model.CacheBAreaStruct); ok {
return &info
} else {
AreaMap.Delete(areaID)
logger.Log.Error("AreaMap 类型断言错误",
zap.String("Src", "GetAreaMapInfo"),
zap.Uint32("areaID", areaID))
}
} else {
logger.Log.Error("AreaMap 没数据",
zap.String("Src", "GetAreaMapInfo"),
zap.Uint32("areaID", areaID))
}
//if areaID == 0 {
// // todo1 logger
// return nil
//}
// todo1 查库
return nil
}
package cache
import (
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"errors"
"fmt"
"go.uber.org/zap"
"log"
"strconv"
"sync"
"time"
)
func initAreaServicePhonePayListMap() { // 存入status为true且verify_result=1即审核通过的
fmt.Println(time.Now(), "cache: initAreaServicePhonePayListMap begin")
// rows, err := dbcurd.PgDb.Query("SELECT id,area_service_id,expiry,amount,month_min,describe FROM b_phone_pay_list WHERE status=true and verify_result=1 ORDER BY create_at") // 暂时不管审核的事情
rows, err := dbcurd.PgDb.Query("SELECT id,area_service_id,expiry,amount,month_min,describe,status FROM b_phone_pay_list ORDER BY create_at") // 暂时不管审核的事情
if err != nil {
log.Panicln("initAreaServicePhonePayListMap rows", err)
}
defer rows.Close()
//var t time.Time
var areaServiceID uint32
var temp model.CacheAreaServicePhonePayListStruct
for rows.Next() {
var list []model.CacheAreaServicePhonePayListStruct
err = rows.Scan(&temp.ID, &areaServiceID, &temp.Expiry, &temp.Amount, &temp.MonthMin, &temp.Describe, &temp.Status)
if err != nil {
log.Panicln("initAreaServicePhonePayListMap rows.Scan", err)
}
//if t.After(time.Now()) {
if areaServiceID > 0 {
if v, ok := areaServicePhonePayListMap.Load(areaServiceID); ok {
list, _ = v.([]model.CacheAreaServicePhonePayListStruct)
}
list = append(list, temp)
areaServicePhonePayListMap.Store(areaServiceID, list)
// fmt.Println(areaServiceID,list)
}
//} else {
// logger.Log.Error("充值项已到期",
// zap.String("Src", "initAreaServicePhonePayListMap"),
// zap.Uint32("id", temp.ID))
// fmt.Println("WARNING WARNING WARNING 充值项已到期",temp.ID)
//}
}
// 处理完毕后,需要判断一次遍历过程中是否有错误产生
if err = rows.Err(); err != nil {
logger.Log.Error("rows.Err()",
zap.Error(err),
zap.String("src", "initAreaServicePhonePayListMap"))
fmt.Println(time.Now(), "initAreaServicePhonePayListMap rows.Err()", err)
} else {
fmt.Println(time.Now(), "cache: initAreaServicePhonePayListMap end")
}
}
func GetAreaServicePhonePayListMap(areaServiceID uint32) []model.CacheAreaServicePhonePayListStruct {
if v, ok := areaServicePhonePayListMap.Load(areaServiceID); ok {
if list, ok := v.([]model.CacheAreaServicePhonePayListStruct); ok {
return list //正常情况
} else {
areaServicePhonePayListMap.Delete(areaServiceID)
logger.Log.Error("areaServicePhonePayListMap 类型断言错误",
zap.String("Src", "GetAreaServicePhonePayListMap"),
zap.Uint32("areaServiceID", areaServiceID))
}
} else {
logger.Log.Error("areaServicePhonePayListMap 没数据",
zap.String("Src", "GetAreaServicePhonePayListMap"),
zap.Uint32("areaServiceID", areaServiceID))
}
//data, unionID := dbcurd.SelectUWeCustomerByUserIDToCacheModel(weUserID)
//if len(unionID) == 0 || data == nil {
// return nil //没有这个用户
//}
//logger.Log.Error("wechatCustomerMap 没数据,数据库有",
// zap.String("Src", "GetWeUserInfoFromMapAndDB"),
// zap.Uint32("userID", weUserID))
return nil
}
var areaServicePhonePayListMapUpdateLock sync.Mutex // 直接全局锁
// AddPhonePayListMap 仅GRPC调用,给校区服务添加一项支付项
func AddPhonePayListMap(areaServiceID uint32,newData *model.CacheAreaServicePhonePayListStruct) error {
areaServicePhonePayListMapUpdateLock.Lock()
defer areaServicePhonePayListMapUpdateLock.Unlock()
if v, ok := areaServicePhonePayListMap.Load(areaServiceID); ok {
if list, ok := v.([]model.CacheAreaServicePhonePayListStruct); ok {
for i,oldData := range list {
if oldData.ID == newData.ID{ // 如果已经有这个ID的了,先删除
list = append(list[:i], list[i+1:]...)
// break 等它遍历完
}
}
list = append(list,*newData)
areaServicePhonePayListMap.Store(areaServiceID,list)
return nil
} else {
areaServicePhonePayListMap.Delete(areaServiceID)
logger.Log.Error("areaServicePhonePayListMap 类型断言错误",
zap.String("Src", "AddPhonePayListMapWhereStatusIsTrue"),
zap.Uint32("areaServiceID", areaServiceID))
}
}
areaServicePhonePayListMap.Store(areaServiceID,[]model.CacheAreaServicePhonePayListStruct{*newData})
return nil
}
// DelPhonePayListMap 仅GRPC调用,校区服务删除一项支付项
func DelPhonePayListMap(areaServiceID , payListID uint32) {
areaServicePhonePayListMapUpdateLock.Lock()
defer areaServicePhonePayListMapUpdateLock.Unlock()
if v, ok := areaServicePhonePayListMap.Load(areaServiceID); ok {
if list, ok := v.([]model.CacheAreaServicePhonePayListStruct); ok {
for i,oldData := range list {
if oldData.ID == payListID{
list = append(list[:i], list[i+1:]...)
if len(list) == 0 {
areaServicePhonePayListMap.Delete(areaServiceID)
} else {
areaServicePhonePayListMap.Store(areaServiceID,list)
}
return
}
}
} else {
areaServicePhonePayListMap.Delete(areaServiceID)
logger.Log.Error("areaServicePhonePayListMap 类型断言错误",
zap.String("Src", "DelPhonePayListMapWhereStatusIsTrue"),
zap.Uint32("areaServiceID", areaServiceID))
}
}
}
// UpdatePhonePayListMap 仅GRPC调用,修改校区服务支付项
func UpdatePhonePayListMap(areaServiceID uint32,newData *model.CacheAreaServicePhonePayListStruct) error {
areaServicePhonePayListMapUpdateLock.Lock()
defer areaServicePhonePayListMapUpdateLock.Unlock()
if v, ok := areaServicePhonePayListMap.Load(areaServiceID); ok {
if list, ok := v.([]model.CacheAreaServicePhonePayListStruct); ok {
for i,oldData := range list {
if oldData.ID == newData.ID{
list[i] = *newData
areaServicePhonePayListMap.Store(areaServiceID,list)
return nil
}
}
} else {
areaServicePhonePayListMap.Delete(areaServiceID)
logger.Log.Error("areaServicePhonePayListMap 类型断言错误",
zap.String("Src", "UpdateOrDelPhonePayListMapAddList"),
zap.Uint32("areaServiceID", areaServiceID))
}
}
return errors.New("未找到ID为:"+ strconv.FormatUint(uint64(newData.ID),10) +"的支付项")
}
\ No newline at end of file
package cache
import (
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"fmt"
"go.uber.org/zap"
"log"
"time"
)
func areaServicePhonePayListMapAddSplit(){ // 区域服务收款项列表添加分账列表
// 遍历 areaServicePhonePayListMap 中的 每一个areaServiceID的每一个[]model.CacheAreaServicePhonePayListStruct,去查询分账信息
fmt.Println(time.Now(),"cache: init areaServicePhonePayListMap SplitAmount begin")
areaServicePhonePayListMap.Range(func(key, value interface{}) bool {
if list, ok := value.([]model.CacheAreaServicePhonePayListStruct);ok{
for _,v := range list{
v.SplitAmount = areaServicePhonePayListMapAddSplitByPayListID(v.ID) // todoN 可考虑校验分账之和是否等于amount,因设置时做了校验,现暂时不判断
}
} else {
areaServicePhonePayListMap.Delete(key)
fmt.Println("---------------error-error-error: value.([]model.CacheAreaServicePhonePayListStruct) != ok",key,value)
}
return true
})
fmt.Println(time.Now(),"init areaServicePhonePayListMap SplitAmount end")
}
func areaServicePhonePayListMapAddSplitByPayListID(payListID uint32) (res []model.PhonePaySplitMoneyStruct) {
rows,err := dbcurd.PgDb.Query("SELECT admin_id,amount FROM b_phone_pay_split_money WHERE pay_list_id=$1",payListID) //
if err != nil {
log.Panicln("areaServicePhonePayListMapAddSplit rows", err)
}
defer rows.Close()
var temp model.PhonePaySplitMoneyStruct
for rows.Next() {
err = rows.Scan(&temp.AdminID, &temp.Amount)
if err != nil {
log.Panicln("initAreaServicePhonePayListMap rows.Scan", err)
}
res = append(res,temp)
}
// 处理完毕后,需要判断一次遍历过程中是否有错误产生
if err = rows.Err(); err != nil {
logger.Log.Error("rows.Err()",
zap.Error(err),
zap.String("src", "initAreaServicePhonePayListMap"))
fmt.Println(time.Now(), "areaServicePhonePayListMapAddSplitByPayListID rows.Err()", err,payListID)
}
return
}
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment