Pārlūkot izejas kodu

Merge branch 'dev1.4.1' of http://192.168.3.207:10080/qmx/datatag into dev1.4.1

xuzhiheng 4 gadi atpakaļ
vecāks
revīzija
6eeaa4a10f

+ 3 - 0
src/filter/sessfilter.go

@@ -33,6 +33,9 @@ func (s *sessfilter) Do(w http.ResponseWriter, req *http.Request) bool {
 					b = false
 				}
 			}
+			if user["role"] == ""{
+				b = false
+			}
 		} else {
 			b = false
 		}

+ 116 - 50
src/front/front.go

@@ -28,6 +28,7 @@ type Front struct {
 	login          xweb.Mapper `xweb:"/"`               //登录页面
 	code           xweb.Mapper `xweb:"/code"`           //获取图片验证码
 	sendVerifyCode xweb.Mapper `xweb:"/sendVerifyCode"` //获取手机验证码
+	chooseEnt      xweb.Mapper `xweb:"/chooseEnt"`      //选择企业
 
 	index     xweb.Mapper `xweb:"/front/index"`     //index页面
 	logout    xweb.Mapper `xweb:"/front/logout"`    //注销
@@ -94,8 +95,6 @@ func (f *Front) Login() {
 			return
 		}
 		realPhoneCode := qu.ObjToString(session.Values["code"])
-		log.Println("realPhoneCode", realPhoneCode)
-		log.Println("param.phoneCode", phoneCode)
 		sessionPhone := qu.ObjToString(session.Values["phone"])
 		if sessionPhone == "" {
 			log.Printf("短信验证码过期-%s \n", phone)
@@ -124,8 +123,8 @@ func (f *Front) Login() {
 		log.Println("验证码验证通过")
 		// 3. 验证用户导出权限  确认认用户是否有数据导出权限
 		loginUser := JyMysql.SelectBySql("select id, name,ent_id,phone,export_power,name from entniche_user where phone=? and export_power=1", phone)
-		if len(*loginUser) == 0 || ((*loginUser)[0])["phone"] != phone {
-			log.Println("无权限")
+		if len(*loginUser) == 0 {
+			log.Println("该用户数据导出权限")
 			f.ServeJson(map[string]interface{}{
 				"code":    0,
 				"status":  false,
@@ -133,59 +132,62 @@ func (f *Front) Login() {
 			})
 			return
 		}
-		// 4. 根据用户的企业id查询对应的管理员手机号  根据管理员手机号查询jyqyfw的企业表对应的appid 放到session里  以及确认用户角色
-		log.Println((*loginUser)[0]["ent_id"], "=====================")
-		entInfo := JyMysql.SelectBySql("select phone,name from entniche_info WHERE id = ?", (*loginUser)[0]["ent_id"])
-		if len(*entInfo) == 0 {
+		// 4. 如果用户在多个企业并且都有剑鱼库里都有数据导出权限,则返回去让用户选择企业
+		if len(*loginUser) > 1 {
+			f.SetSession("user", map[string]interface{}{
+				"phone": phone,
+			})
 			f.ServeJson(map[string]interface{}{
-				"code":    0,
-				"status":  false,
-				"message": "企业信息查询失败",
+				"code":    1,
+				"status":  true,
+				"message": "",
 			})
 			return
-		}
-		var role int // 角色  1 管理员  3 普通用户
-		// 判断当前用户手机号是否是管理员手机号
-		if phone != qu.ObjToString((*entInfo)[0]["phone"]) {
-			role = 3
-		} else {
-			role = 1
-		}
-		// 查询mongo企业信息库 获取appid
-		query := bson.M{
-			"phone":    qu.ObjToString((*entInfo)[0]["phone"]),
-			"username": qu.ObjToString((*entInfo)[0]["name"]),
-		}
-		entMgoInfo, ok := MgoCus.FindOne("user", query)
-		if !ok {
-			//	企业信息查询失败
-			return
-		}
-		//相关信息存入session
-		if entMgoInfo != nil && len(*entMgoInfo) > 0 {
-			f.SetSession("user", map[string]interface{}{
-				"name":   (*loginUser)[0]["name"],
-				"phone":  phone,
-				"role":   role,
-				"appid":  (*entMgoInfo)["appid"],
-				"ent_id": (*loginUser)[0]["entid"],
-				"id":     (*loginUser)[0]["id"],
-			})
-			//UserMenu[email] = GetUserMenu(qu.ObjToString((*user)["s_role"]))
 
 		}
-		fmt.Println("role", role)
-		f.ServeJson(map[string]interface{}{
-			"code":    0,
-			"status":  true,
-			"role":    role,
-			"message": "",
-		})
+		fmt.Println()
+		LoginCheck(f, strconv.Itoa(int((*loginUser)[0]["ent_id"].(int64))), (*loginUser)[0], phone)
+		return
 	} else {
 		f.Render("login.html")
 	}
 }
+func (f *Front) ChooseEnt() {
+	defer qu.Catch()
+	// 选择企业页面
+	tempSession := f.GetSession("user")
+	if tempSession == nil || tempSession == "" {
+		f.Redirect("/", 302)
+		return
+	}
+	info := tempSession.(map[string]interface{})
+	if info["phone"] == "" || info["phone"] == nil {
+		f.Redirect("/", 302)
+		return
+	}
+	if f.Method() == "POST" {
+		entId := f.GetString("ent_id")
 
+		// 2. 确认该手机号有数据导出权限
+		loginUser := JyMysql.SelectBySql("select id, name,ent_id,phone,export_power,name from entniche_user where phone=? and export_power=1 and ent_id=?", info["phone"], entId)
+		if len(*loginUser) == 0 {
+			f.ServeJson(map[string]interface{}{
+				"code":    0,
+				"status":  false,
+				"message": "无权限",
+			})
+			return
+		}
+		LoginCheck(f, entId, (*loginUser)[0], info["phone"].(string))
+		return
+	} else { // get 请求时铺企业页面
+		// 查询 企业信息  name  ent_id
+		rs := JyMysql.SelectBySql("select a.ent_id, b.name ent_name from entniche_user a, entniche_info b WHERE a.phone =? and export_power=1 and a.ent_id=b.id", info["phone"])
+		f.T["ent_info"] = rs
+		f.Render("choose_ent.html", &f.T)
+	}
+
+}
 func (f *Front) Index() {
 	defer qu.Catch()
 	f.Render("index.html")
@@ -388,8 +390,6 @@ func (f *Front) SendVerifyCode() {
 			})
 			return
 		}
-		fmt.Println("code", code)
-		fmt.Println("img", imgCode)
 		if !captcha.VerifyString(code, imgCode) {
 			log.Printf("图片验证码错误-%s \n", phone)
 			f.ServeJson(map[string]interface{}{
@@ -401,7 +401,6 @@ func (f *Front) SendVerifyCode() {
 		}
 		//3. 验证手机号是否存在
 		user := JyMysql.SelectBySql("select * from entniche_user where phone=? and export_power=1", phone)
-		fmt.Println(user, "-----------------================")
 		// 确认用户是否存在
 		if len(*user) == 0 || ((*user)[0])["phone"] != phone {
 			log.Println("没有数据导出权限")
@@ -468,3 +467,70 @@ func SendSMS(tplcode /*模板代码*/, mobile /*手机号码*/ string, param map
 	text := strings.Join(tmp, "&")
 	sms.SendSms(mobile, tplcode, text)
 }
+
+func LoginCheck(f *Front, entId string, loginUser map[string]interface{}, userPhone string) {
+	// 1. 确认该企业有使用该系统的权限 查询配置文件appid 确认是否有使用该系统的权限
+	query2 := bson.M{
+		"ent_id": entId,
+	}
+	log.Println(entId)
+	isExist, _ := Mgo.FindOne("datatag_export_config", query2)
+	log.Println(isExist)
+	if len(*isExist) == 0 {
+		f.ServeJson(map[string]interface{}{
+			"code":    0,
+			"status":  false,
+			"message": "该企业无权限",
+		})
+		return
+	}
+	// 3. 查询企业管理员信息及手机号
+	entInfo := JyMysql.SelectBySql("select phone,name from entniche_info WHERE id = ?", loginUser["ent_id"])
+	if len(*entInfo) == 0 {
+		f.ServeJson(map[string]interface{}{
+			"code":    0,
+			"status":  false,
+			"message": "企业信息查询失败",
+		})
+		return
+	}
+	// 4. mongo库查询与之关联的企业appid
+	query := bson.M{
+		"phone":    (*entInfo)[0]["phone"],
+		"username": (*entInfo)[0]["name"],
+	}
+	entMgoInfo, ok := MgoCus.FindOne("user", query)
+	if !ok {
+		//	企业信息查询失败
+		f.ServeJson(map[string]interface{}{
+			"code":    0,
+			"status":  false,
+			"message": "appid查询失败",
+		})
+		return
+	}
+	// 5. 确认用户角色
+	var role int // 角色  1 管理员  3 普通用户
+	if userPhone != qu.ObjToString((*entInfo)[0]["phone"]) {
+		role = 3
+	} else {
+		role = 1
+	}
+
+	// 确认用户角色  存session
+	f.SetSession("user", map[string]interface{}{
+		"name":   loginUser["name"],
+		"phone":  userPhone,
+		"role":   role,
+		"appid":  (*entMgoInfo)["appid"],
+		"ent_id": entId,
+		"id":     loginUser["id"],
+	})
+	//	返回
+	f.ServeJson(map[string]interface{}{
+		"code":    0,
+		"status":  true,
+		"role":    role,
+		"message": "",
+	})
+}

+ 97 - 0
src/util/cost_util.go

@@ -0,0 +1,97 @@
+package util
+
+import (
+	"database/sql"
+	"log"
+	"qfw/util"
+	"time"
+)
+
+// 扣费相关
+// 获取账户当前剩余量
+func GetCurrentCount2(entId, userId int) int {
+	count := 0
+	userData := JyMysql.FindOne("user_account", map[string]interface{}{"user_id": userId, "ent_id": entId}, "left_num", "")
+	// 如果不存在就初始化一条记录
+	if userData == nil {
+		nowStr := time.Now().Local().Format("2006-01-02 15:04:05")
+		JyMysql.Insert("user_account", map[string]interface{}{"user_id": userId, "ent_id": entId, "left_num": 0, "create_at": nowStr})
+		return count
+	}
+	count = util.IntAll((*userData)["left_num"])
+	return count
+}
+
+// 扣费
+func DeductNum2(entId int, newCount int, userId int, exportId int64) bool {
+	var flag bool
+	// 1. 查询账户余额
+	log.Println("扣费开始")
+	query := map[string]interface{}{
+		"user_id": userId,
+		"ent_id":  entId,
+	}
+	userAccountData := JyMysql.FindOne("user_account", query, "left_num", "")
+	//2.扣费
+	// 扣费前剩余
+	if userAccountData == nil {
+		log.Printf("用户扣费失败:user_id-%dent_id:%d\n", userId, entId)
+		flag = false
+		return flag
+	}
+	before := int((*userAccountData)["left_num"].(int64))
+	after := before - newCount
+	// 扣费
+	rechargeRs := JyMysql.ExecTx("用户扣费", func(tx *sql.Tx) bool {
+		// 更新剩余额度
+		updateNowStr := time.Now().Local().Format("2006-01-02 15:04:05")
+		ok1 := JyMysql.UpdateOrDeleteBySqlByTx(tx, "update user_account set left_num=?,update_at=? where user_id=? and ent_id=?", after, updateNowStr, userId, entId) > 0
+		// 生扣费记录
+		sqlStr := "insert into user_expend_record (user_id,ent_id,`before`,`after`,trade,create_at,export_id) values(?,?,?,?,?,?,?)"
+		ok2 := JyMysql.InsertBySqlByTx(tx, sqlStr, userId, entId, before, after, newCount, updateNowStr, exportId) != -1
+		return ok1 && ok2
+	})
+	if rechargeRs != true {
+		flag = false
+		log.Printf("用户扣费失败:user_id-%dent_id:%d\n", userId, entId)
+	} else {
+		flag = true
+	}
+	log.Println("扣费结束")
+	return flag
+}
+
+// 存导出日志
+func SaveExportLog2(entId, entUserId, count, newCount, remain_nums, export_nums int, xlsxUrl, types, filterStr string) (exportId int64) {
+	query := map[string]interface{}{
+		"id":     entUserId,
+		"ent_id": entId,
+	}
+	set := map[string]interface{}{
+		"remain_nums": remain_nums - newCount,
+		"export_nums": export_nums + newCount,
+	}
+	ok := JyMysql.Update("entniche_export_limit", map[string]interface{}{"ent_id": entId, "user_id": entUserId}, set)
+	if !ok {
+		log.Println("修改导出条数失败", query, remain_nums, newCount)
+	}
+	userData := JyMysql.FindOne("entniche_user", query, "name,phone", "")
+	if userData != nil {
+		name := util.ObjToString((*userData)["name"])
+		phone := util.ObjToString((*userData)["phone"])
+		now := time.Now()
+		exportId = JyMysql.Insert("entniche_export_log", map[string]interface{}{
+			"user_name":    name,
+			"export_time":  util.FormatDate(&now, util.Date_Full_Layout),
+			"data_source":  "1",
+			"export_num":   count,
+			"deduct_num":   newCount,
+			"download_url": xlsxUrl,
+			"ent_id":       entId,
+			"phone":        phone,
+			"user_id":      entUserId,
+			"filter":       filterStr,
+		})
+	}
+	return
+}

+ 68 - 0
src/web/templates/choose_ent.html

@@ -0,0 +1,68 @@
+{{include "com/inc.html"}}
+<!-- Main Header -->
+{{include "com/header.html"}}
+
+
+<!-- Content Wrapper. Contains page content -->
+<div class="content-wrapper">
+    <!-- Main content -->
+    <section class="content">
+    </section>
+
+    <div class="modal " tabindex="-1" role="dialog" id="myModal" aria-hidden="true" data-backdrop="static">
+        <div class="modal-dialog" role="document">
+            <div class="modal-content">
+                <div class="modal-header">
+                    <h4 class="modal-title">您加入了多个企业,请先选择企业</h4>
+                </div>
+                <div class="modal-body" id="radioBody">
+                    <p></p>
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-primary" id="submitChoose">确认</button>
+                </div>
+            </div><!-- /.modal-content -->
+        </div><!-- /.modal-dialog -->
+    </div><!-- /.modal -->
+</div>
+
+
+<script>
+    var entInfo = {{.T.ent_info}}
+    <!--   页面加载时-->
+    $(document).ready(function () {
+        for (let i = 0; i < entInfo.length; i++) {
+            $("#radioBody").append('<div class="radio" style="margin-top: 10px">\
+            <label><input type="radio" name="optionsRadios" id=' + entInfo[i]["ent_id"] + " value=" + entInfo[i]["ent_id"] + '>' + entInfo[i]["ent_name"] + ' </label></div>')
+        }
+        $('#myModal').modal();
+    });
+    // 提交选择信息
+    $("#submitChoose").click(function () {
+        // 获取选择信息
+        let entId = $("input[name='optionsRadios']:checked").val();
+        // 提交
+        $.ajax({
+                url: "/chooseEnt",
+                data: {"ent_id": entId},
+                method: "post",
+                success: function (r) {
+                    // 结果 判断
+                    if (r.status) {
+                        if (r.role === 1) {
+                            window.location.href = "/admin/index";
+                        } else if (r.role === 3) {
+                            window.location.href = "/personnel/index";
+                        } else {
+                            alert("身份信息无效")
+                        }
+                    } else {
+                        alert(r.message)
+                    }
+                }
+            }
+        )
+    })
+</script>
+<!-- footer -->
+{{include "com/footer.html"}}

+ 9 - 3
src/web/templates/login.html

@@ -151,10 +151,16 @@
                 if (r.status === false) {
                     alert(r.message)
                 } else {
+                    if (r.code==1){
+                        window.location.href = "/chooseEnt";
+                        return
+                    }
                     if (r.role === 1) {
-                        window.location.href = "/front/index";
-                    } else {
-                        window.location.href = "/client/index";
+                        window.location.href = "/admin/index";
+                    } else if(r.role===3){
+                        window.location.href = "/personnel/index";
+                    }else {
+                        alert("身份信息无效")
                     }
                 }
             }