Commit 5a0b52e6 by zhangjiec

添加文件

parent 0ad26449
package api_we
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
)
type creatCardUserRes struct {
ID uint32 `json:"id"` // 新创建的学生ID
Service [6]uint8 `json:"service" example:"1,2,2,2,2,2"` // 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
}
// CreateCardUser 创建一个学生
// @Tags 家长微信
// @Summary 创建一个学生 (同一微信号并发创建学生,WechatCustomerMap缓存弱安全) [complete]
// @Description 传新建学生信息至后台,后台返回学生id,以及对应校区的service
// @Accept json
// @Produce json
// @Param data body dbdao.InsertTableUserCardUser true "学生信息"
// @Success 0 {object} creatCardUserRes
// @Router /we/carduser [POST]
// @Security ApiKeyAuth
func CreateCardUser(c *gin.Context) {
var reqData dbdao.InsertTableUserCardUser
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,
"data": api.CodeMsg[api.ErrorSystemErr],
})
logger.Log.Error("strconv.Atoi(c.Param(\"userID\")",
zap.String("c.Param(\"userID\")", c.Param("userID")),
zap.Error(err))
return
}
newID := dbdao.InsertUserCardUserAndUserWeCardUser(reqData, weUserID) //插入数据库
if newID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": 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],
})
return
}
//添加学生缓存
cache.CardUserMap.Store(newID, cache.CardUserType{
AreaID: reqData.AreaID,
Name: reqData.Name,
Sex: reqData.Sex,
Grade: reqData.Grade,
Class: reqData.Class,
StuNum: reqData.StuNum,
MasterWechatUserID: weUserID,
})
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": creatCardUserRes{
newID,
[6]uint8{1, 2, 2, 2, 2, 2},
},
})
}
package api_we
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
"strconv"
)
// DeleteCardUser 主家长删除一个学生
// @Tags 家长微信
// @Summary 主家长删除一个学生
// @Description 传学生ID至后台,后台返回成功失败
// @Produce json
// @Param id path integer true "学生ID"
// @Success 0
// @Router /we/carduser/{id} [DELETE]
// @Security ApiKeyAuth
func DeleteCardUser(c *gin.Context) {
cardUserID, _ := strconv.Atoi(c.Param("id"))
if cardUserID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " id不正确",
})
return
}
// 取出微信ID
weUserID, ok := c.Get("userID")
if ok == false {
logger.Log.Error("userID在Context里面居然没填对,遇到鬼了",
zap.String("Src", "DeleteCardUser"),
zap.Int("cardUserID", cardUserID))
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
// 查出该学生信息
cardUserInfo, ok := cache.GetCardUserInfo(uint32(cardUserID))
if ok == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
if cardUserInfo.MasterWechatUserID != weUserID { // 用户根本没得这个学生的权限,有问题
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
}
if cardUserInfo.Recharge { //充过值不允许删除
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " 用户已充值",
})
return
}
// 删库
// 删缓存
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
})
}
package api_we
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/data_db_cache/model"
tencent2 "dc_golang_server_1/tencent"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
type WeSlaveLoginResUserInfoStruct struct {
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"` // ""无意义
Service [6]uint8 `json:"service" example:"1,2,2,0,0,0"` // 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
// TopUp bool `json:"topUp"` // 是否已充值(已充值则不能删除,未充值可以删除)
}
type WeMasterLoginResUserInfoStruct struct {
WeSlaveLoginResUserInfoStruct
TopUp bool `json:"topUp"` // 是否已充值(已充值则不能删除,未充值可以删除)
}
type weLoginRes struct {
Master []WeMasterLoginResUserInfoStruct `json:"master"` // 自己创建的学生列表(主家长)
Slave []WeSlaveLoginResUserInfoStruct `json:"slave"` // 添加的学生列表(副家长)
WePhone bool `json:"wePhone"` // 是否已获取到微信电话
WeInfo bool `json:"weInfo"` // 是否已获取到微信用户信息
Token string `json:"token"`
}
type weLoginReq struct {
Code string `json:"code" example:"codeTest1"` //必填,登录要用的微信code
Token string `json:"token,omitempty"` //选填,如果有旧的token,也带过来
}
// WeLogin 微信登录
// @Tags 家长微信
// @Summary 登录 [complete]
// @Description 微信code传至后台,后台返回token,token有效时长:48小时
// @Param data body weLoginReq true "登录信息"
// @Product json
// @Success 0 {object} weLoginRes
// @Router /we/login/{code} [POST]
func WeLogin(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 userID 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 {
userID = tokenInfo.UserID
}
}
}
var userInfo model.CacheUWeCustomerStruct
var haveInfo bool
if userID != 0 {
userInfo, haveInfo = cache.GetWechatCustomerInfoAndCanUpdateTokenTime(userID, nowTime)
if haveInfo {
dbdao.UpdateUWeCustomerLoginTime(userID)
}
}
if haveInfo == false { // 微信服务器登录
unionID, err := tencent2.TencentCode2Session(reqData.Code) //也不去校验reqData.Code长度了,对半是对的
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr] + err.Error(),
})
return
}
userID = cache.GetWechatCustomerUserIDByUnionID(unionID)
if userID == 0 { // 原来没有,只有注册
userInfo.TokenCreatTime = nowTime
userID = cache.InsertWechatCustomerMap(unionID, &userInfo)
if userID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
} else { // 已有用户
userInfo, haveInfo = cache.GetWechatCustomerInfoAndCanUpdateTokenTime(userID, nowTime)
if haveInfo {
dbdao.UpdateUWeCustomerLoginTime(userID)
} else {
cache.WechatCustomerMap.Delete(userID)
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],
})
return
}
}
}
var res weLoginRes
res.Token = api.CreateToken(nowTime, userID, 1, 48*24*3600)
if len(userInfo.WePhone) > 0 {
res.WePhone = true
}
if len(userInfo.Nickname) > 0 { // todo 这里考虑长时间之后重新获取一盘昵称头像
res.WeInfo = true
}
for _, cardUserID := range userInfo.MasterCardUserID {
if cardUserInfo, ok := cache.GetCardUserInfo(cardUserID); ok {
var areaInfo model.CacheBAreaStruct
var upInfo WeMasterLoginResUserInfoStruct
upInfo.ID = cardUserID
upInfo.Name = cardUserInfo.Name
upInfo.Sex = cardUserInfo.Sex
upInfo.Grade = cardUserInfo.Grade
upInfo.Class = cardUserInfo.Class
upInfo.StuNum = cardUserInfo.StuNum
upInfo.TopUp = true
upInfo.Service = [6]uint8{1, 2, 2, 2, 2, 2}
fmt.Println("upInfo.Service", upInfo.Service)
if cache.GetAreaMapInfo(cardUserInfo.AreaID, &areaInfo) {
if areaInfo.Status == 1 || (areaInfo.Status == 2 && userInfo.TestRole) {
upInfo.Area = areaInfo.Name
}
}
res.Master = append(res.Master, upInfo)
}
}
for _, cardUserID := range userInfo.SlaveCardUserID {
if cardUserInfo, ok := cache.GetCardUserInfo(cardUserID); ok {
var areaInfo model.CacheBAreaStruct
var upInfo WeSlaveLoginResUserInfoStruct
upInfo.ID = cardUserID
upInfo.Name = cardUserInfo.Name
upInfo.Sex = cardUserInfo.Sex
upInfo.Grade = cardUserInfo.Grade
upInfo.Class = cardUserInfo.Class
upInfo.StuNum = cardUserInfo.StuNum
//upInfo.TopUp = true
upInfo.Service = [6]uint8{1, 2, 2, 2, 2, 2}
fmt.Println("upInfo.Service", upInfo.Service)
if cache.GetAreaMapInfo(cardUserInfo.AreaID, &areaInfo) {
if areaInfo.Status == 1 || (areaInfo.Status == 2 && userInfo.TestRole) {
upInfo.Area = areaInfo.Name
}
}
res.Slave = append(res.Slave, upInfo)
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": res,
})
}
package cache
func initAdminMap() {
// todo
}
func GetAdminTokenCreatTime(adminID uint32) int64 {
return 0xffffffff //没有这个用户返回0xffffffff
}
func UpdateAdminTokenCreatTime(adminID uint32, createAt int64) {
}
package dbdao
import (
"dc_golang_server_1/logger"
"go.uber.org/zap"
"strings"
)
//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)
type TableBaseArea struct {
ID uint32 `swaggerignore:"true"`
CountyID uint32 `json:"county_id" example:"2725"` // 必填,所属区县ID
Name string `json:"name" example:"多彩温江校区"` // 必填,名字
Longitude uint32 `json:"longitude" example:"103000000"` // 必填,经度
Latitude uint32 `json:"latitude" example:"30000000"` // 必填,纬度
Status uint8 `json:"status" example:"1"` // 必填,是否测试校区,0预留 1正示 2测试校区
CreatorID uint32 `json:"creator_id" example:"1"` // 测试用,以后不传这个字段
// UpdaterID uint32
// CreateAt time.Time
// UpdateAt time.Time
}
func InsertBaseArea(insertData *TableBaseArea) uint8 { //0 成功 1 唯一约束重复 9 系统繁忙
err := PgDb.QueryRow("INSERT INTO b_area(county_id,name,longitude,latitude,status,creator_id)VALUES($1,$2,$3,$4,$5,$6)RETURNING id",
insertData.CountyID,
insertData.Name,
insertData.Longitude,
insertData.Latitude,
insertData.Status,
insertData.CreatorID,
).Scan(&insertData.ID)
if err == nil {
return 0
}
if strings.Contains(err.Error(), "duplicate key value") {
logger.Log.Error("InsertBaseArea duplicate key value",
zap.Reflect("insertData", insertData),
zap.Error(err))
return 1
}
logger.Log.Error("InsertBaseArea Err",
zap.Reflect("insertData", insertData),
zap.Error(err))
return 9
}
package dbdao
import (
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"fmt"
"go.uber.org/zap"
"strings"
"time"
)
func UpdateUWeCustomerLoginTime(weUserID uint32) { //todoN 以后添加微信登录流水表
var err error
for i := 0; i < 10; i++ {
_, err = stmtUpdateWechatUserLogin.Exec(time.Now().Format("2006-01-02 15:04:05.000"), weUserID) //这里格式化可加可不加
if err == nil {
// fmt.Println("res",res)
return
}
fmt.Println("UpdateUWeCustomerLoginTime:", i, err)
time.Sleep(3 * time.Second)
}
logger.Log.Error("UpdateUWeCustomerLoginTime Err",
zap.Error(err))
}
func InsertUWeCustomerUnionID(unionID string) (id uint32, res uint8) {
var err error
for i := 0; i < 10; i++ {
err = PgDb.QueryRow("INSERT INTO u_we_customer(unionid)VALUES($1)RETURNING id", unionID).Scan(&id)
if err == nil {
return // 这里是完全正常的情况
}
if strings.Contains(err.Error(), "duplicate key value") {
logger.Log.Error("InsertUWeCustomerUnionID unionID Err",
zap.Error(err))
return 0, InsertDuplicate
}
fmt.Println("InsertUWeCustomerUnionID Err:", i, unionID, err)
time.Sleep(10 * time.Millisecond)
}
logger.Log.Error("InsertUWeCustomerUnionID Err",
zap.Error(err))
return 0, InsertSysErr
}
func SelectUWeCustomerByUnionIDToCacheModel(unionID string, userInfo *model.CacheUWeCustomerStruct) (userID uint32) {
// 1. 查u_we_customer表获得基础数据
err := PgDb.QueryRow("SELECT id,phone,nickname,avatarurl,test_role FROM u_we_customer WHERE unionid=$1", unionID).Scan(
&userID,
&userInfo.WePhone,
&userInfo.Nickname,
&userInfo.AvatarURL,
&userInfo.TestRole)
if err != nil {
logger.Log.Error("SelectUWeCustomerByUnionIDToCacheModel 1",
zap.String("unionID", unionID),
zap.Error(err))
return 0
}
// 2. 查u_we_card_user表,获得绑定的学生数据
rows, err := PgDb.Query("SELECT card_user_id,master FROM u_we_card_user WHERE we_user_id=$1 order by create_at", userID)
defer rows.Close()
if err != nil {
logger.Log.Error("SelectUWeCustomerByUnionIDToCacheModel 2",
zap.Uint32("userID", userID),
zap.Error(err))
fmt.Println(err)
return 0
}
var cUserID uint32
var master bool
userInfo.MasterCardUserID = userInfo.MasterCardUserID[0:0]
userInfo.SlaveCardUserID = userInfo.SlaveCardUserID[0:0]
for rows.Next() {
err = rows.Scan(&cUserID, &master)
if err != nil {
logger.Log.Error("SelectUWeCustomerByUnionIDToCacheModel 3",
zap.Uint32("userID", userID),
zap.Error(err))
continue
}
if master {
userInfo.MasterCardUserID = append(userInfo.MasterCardUserID, cUserID)
} else {
userInfo.SlaveCardUserID = append(userInfo.SlaveCardUserID, cUserID)
}
}
// 处理完毕后,需要判断一次遍历过程中是否有错误产生
if err = rows.Err(); err != nil {
logger.Log.Error("SelectUWeCustomerByUnionIDToCacheModel 4",
zap.Uint32("userID", userID),
zap.Error(err))
}
return
}
func SelectUWeCustomerByUserIDToCacheModel(userID uint32, userInfo *model.CacheUWeCustomerStruct) (unionID string) {
// 1. 查u_we_customer表获得基础数据
err := PgDb.QueryRow("SELECT unionid,phone,nickname,avatarurl,test_role FROM u_we_customer WHERE id=$1", userID).Scan(
&unionID,
&userInfo.WePhone,
&userInfo.Nickname,
&userInfo.AvatarURL,
&userInfo.TestRole)
if err != nil {
logger.Log.Error("SelectUWeCustomerByUserIDToCacheModel 1",
zap.Uint32("userID", userID),
zap.Error(err))
return ""
}
// 2. 查u_we_card_user表,获得绑定的学生数据
rows, err := PgDb.Query("SELECT card_user_id,master FROM u_we_card_user WHERE we_user_id=$1 order by create_at", userID)
defer rows.Close()
if err != nil {
logger.Log.Error("SelectUWeCustomerByUserIDToCacheModel 2",
zap.Uint32("userID", userID),
zap.Error(err))
return ""
}
var cUserID uint32
var master bool
userInfo.MasterCardUserID = userInfo.MasterCardUserID[0:0]
userInfo.SlaveCardUserID = userInfo.SlaveCardUserID[0:0]
for rows.Next() {
err = rows.Scan(&cUserID, &master)
if err != nil {
logger.Log.Error("SelectUWeCustomerByUserIDToCacheModel 3",
zap.Uint32("userID", userID),
zap.Error(err))
continue
}
if master {
userInfo.MasterCardUserID = append(userInfo.MasterCardUserID, cUserID)
} else {
userInfo.SlaveCardUserID = append(userInfo.SlaveCardUserID, cUserID)
}
}
// 处理完毕后,需要判断一次遍历过程中是否有错误产生
if err = rows.Err(); err != nil {
logger.Log.Error("SelectUWeCustomerByUserIDToCacheModel 4",
zap.Uint32("userID", userID),
zap.Error(err))
}
return
}
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