Browse Source

消息推送

bsj 3 years ago
parent
commit
926313f91d

+ 7 - 0
.vscode/launch.json

@@ -0,0 +1,7 @@
+{
+    // 使用 IntelliSense 了解相关属性。 
+    // 悬停以查看现有属性的描述。
+    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
+    "version": "0.2.0",
+    "configurations": []
+}

BIN
KPTAdmin64.exe


BIN
KPTAdmin64.zip


BIN
TMRWatchComm


+ 2 - 2
conf/app.ini

@@ -46,8 +46,8 @@ GRFDURL = http://120.48.30.31:88
 Type = mysql
 User = root
 #Password = root
-Host = 127.0.0.1:3316
-Name = tmrwatch2
+Host = 192.168.1.93:3326
+Name = tmrwatch3
 Password = root
 #Password = root
 #Password = kptzhu@163.com

BIN
dist(2).zip


BIN
dist.zip


File diff suppressed because it is too large
+ 0 - 0
dist/index.html


File diff suppressed because it is too large
+ 0 - 0
dist/static/css/app.db26fdc4.css


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/app.4e24d177.js


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/app.e0a2c68c.js


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/chunk-libs.011550ed.js


+ 40 - 137
docs/docs.go

@@ -1,11 +1,12 @@
 // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
 // This file was generated by swaggo/swag at
-// 2019-09-27 10:56:45.7469034 +0800 CST m=+0.047123001
+// 2022-06-22 15:11:48.7853794 +0800 CST m=+0.305982301
 
 package docs
 
 import (
 	"bytes"
+
 	"github.com/alecthomas/template"
 	"github.com/swaggo/swag"
 )
@@ -475,8 +476,8 @@ var doc = `{
                 }
             }
         },
-        "/authdata/users": {
-            "get": {
+        "/data/GetDataByName": {
+            "post": {
                 "consumes": [
                     "application/json"
                 ],
@@ -484,88 +485,49 @@ var doc = `{
                     "application/json"
                 ],
                 "tags": [
-                    "users"
+                    "GetDataByName"
                 ],
-                "summary": "获取所有用户",
+                "summary": "根据APISQL表中SQL执行得到数据集",
                 "parameters": [
                     {
-                        "type": "string",
-                        "description": "username",
-                        "name": "username",
-                        "in": "path"
-                    }
-                ],
-                "responses": {
-                    "200": {
-                        "description": "{ \"code\": 200, \"data\": {}, \"msg\": \"ok\" }",
+                        "description": "sqlname",
+                        "name": "sqlname",
+                        "in": "body",
+                        "required": true,
                         "schema": {
-                            "type": "string"
+                            "type": "object",
+                            "$ref": "#/definitions/string"
                         }
-                    }
-                }
-            },
-            "post": {
-                "consumes": [
-                    "application/json"
-                ],
-                "produces": [
-                    "application/json"
-                ],
-                "tags": [
-                    "users"
-                ],
-                "summary": "增加用户1",
-                "parameters": [
-                    {
-                        "type": "string",
-                        "description": "username",
-                        "name": "username",
-                        "in": "query",
-                        "required": true
                     },
                     {
-                        "type": "string",
-                        "description": "password",
-                        "name": "password",
-                        "in": "query",
-                        "required": true
+                        "description": "offset",
+                        "name": "offset",
+                        "in": "body",
+                        "required": true,
+                        "schema": {
+                            "type": "object",
+                            "$ref": "#/definitions/int"
+                        }
                     },
                     {
-                        "type": "integer",
-                        "description": "role_id",
-                        "name": "role_id",
-                        "in": "path"
-                    }
-                ],
-                "responses": {
-                    "200": {
-                        "description": "{ \"code\": 200, \"data\": {}, \"msg\": \"ok\" }",
+                        "description": "pagecount",
+                        "name": "pagecount",
+                        "in": "body",
+                        "required": true,
                         "schema": {
-                            "type": "string"
+                            "type": "object",
+                            "$ref": "#/definitions/int"
                         }
-                    }
-                }
-            }
-        },
-        "/authdata/users/": {
-            "get": {
-                "consumes": [
-                    "application/json"
-                ],
-                "produces": [
-                    "application/json"
-                ],
-                "tags": [
-                    "users"
-                ],
-                "summary": "获取单个用户信息",
-                "parameters": [
+                    },
                     {
-                        "type": "integer",
-                        "description": "id",
-                        "name": "id",
-                        "in": "path",
-                        "required": true
+                        "description": "returntype",
+                        "name": "returntype",
+                        "in": "body",
+                        "required": true,
+                        "schema": {
+                            "type": "object",
+                            "$ref": "#/definitions/string"
+                        }
                     }
                 ],
                 "responses": {
@@ -574,74 +536,15 @@ var doc = `{
                         "schema": {
                             "type": "string"
                         }
-                    }
-                }
-            },
-            "put": {
-                "consumes": [
-                    "application/json"
-                ],
-                "produces": [
-                    "application/json"
-                ],
-                "tags": [
-                    "users"
-                ],
-                "summary": "更新用户",
-                "parameters": [
-                    {
-                        "type": "string",
-                        "description": "username",
-                        "name": "username",
-                        "in": "query",
-                        "required": true
-                    },
-                    {
-                        "type": "string",
-                        "description": "password",
-                        "name": "password",
-                        "in": "query",
-                        "required": true
                     },
-                    {
-                        "type": "integer",
-                        "description": "role_id",
-                        "name": "role_id",
-                        "in": "query"
-                    }
-                ],
-                "responses": {
-                    "200": {
-                        "description": "{ \"code\": 200, \"data\": {}, \"msg\": \"ok\" }",
+                    "400": {
+                        "description": "{\"code\":400,  \"data\":null,\"msg\":\"请求参数错误\"}",
                         "schema": {
                             "type": "string"
                         }
-                    }
-                }
-            },
-            "delete": {
-                "consumes": [
-                    "application/json"
-                ],
-                "produces": [
-                    "application/json"
-                ],
-                "tags": [
-                    "users"
-                ],
-                "summary": "删除用户",
-                "parameters": [
-                    {
-                        "type": "integer",
-                        "description": "id",
-                        "name": "id",
-                        "in": "path",
-                        "required": true
-                    }
-                ],
-                "responses": {
-                    "200": {
-                        "description": "{ \"code\": 200, \"data\": {}, \"msg\": \"ok\" }",
+                    },
+                    "404": {
+                        "description": "{ \"code\": 404, \"data\":null,\"msg\":\"请求参数错误\"}",
                         "schema": {
                             "type": "string"
                         }

+ 38 - 136
docs/swagger.json

@@ -463,8 +463,8 @@
                 }
             }
         },
-        "/authdata/users": {
-            "get": {
+        "/data/GetDataByName": {
+            "post": {
                 "consumes": [
                     "application/json"
                 ],
@@ -472,88 +472,49 @@
                     "application/json"
                 ],
                 "tags": [
-                    "users"
+                    "GetDataByName"
                 ],
-                "summary": "获取所有用户",
+                "summary": "根据APISQL表中SQL执行得到数据集",
                 "parameters": [
                     {
-                        "type": "string",
-                        "description": "username",
-                        "name": "username",
-                        "in": "path"
-                    }
-                ],
-                "responses": {
-                    "200": {
-                        "description": "{ \"code\": 200, \"data\": {}, \"msg\": \"ok\" }",
+                        "description": "sqlname",
+                        "name": "sqlname",
+                        "in": "body",
+                        "required": true,
                         "schema": {
-                            "type": "string"
+                            "type": "object",
+                            "$ref": "#/definitions/string"
                         }
-                    }
-                }
-            },
-            "post": {
-                "consumes": [
-                    "application/json"
-                ],
-                "produces": [
-                    "application/json"
-                ],
-                "tags": [
-                    "users"
-                ],
-                "summary": "增加用户1",
-                "parameters": [
-                    {
-                        "type": "string",
-                        "description": "username",
-                        "name": "username",
-                        "in": "query",
-                        "required": true
                     },
                     {
-                        "type": "string",
-                        "description": "password",
-                        "name": "password",
-                        "in": "query",
-                        "required": true
+                        "description": "offset",
+                        "name": "offset",
+                        "in": "body",
+                        "required": true,
+                        "schema": {
+                            "type": "object",
+                            "$ref": "#/definitions/int"
+                        }
                     },
                     {
-                        "type": "integer",
-                        "description": "role_id",
-                        "name": "role_id",
-                        "in": "path"
-                    }
-                ],
-                "responses": {
-                    "200": {
-                        "description": "{ \"code\": 200, \"data\": {}, \"msg\": \"ok\" }",
+                        "description": "pagecount",
+                        "name": "pagecount",
+                        "in": "body",
+                        "required": true,
                         "schema": {
-                            "type": "string"
+                            "type": "object",
+                            "$ref": "#/definitions/int"
                         }
-                    }
-                }
-            }
-        },
-        "/authdata/users/": {
-            "get": {
-                "consumes": [
-                    "application/json"
-                ],
-                "produces": [
-                    "application/json"
-                ],
-                "tags": [
-                    "users"
-                ],
-                "summary": "获取单个用户信息",
-                "parameters": [
+                    },
                     {
-                        "type": "integer",
-                        "description": "id",
-                        "name": "id",
-                        "in": "path",
-                        "required": true
+                        "description": "returntype",
+                        "name": "returntype",
+                        "in": "body",
+                        "required": true,
+                        "schema": {
+                            "type": "object",
+                            "$ref": "#/definitions/string"
+                        }
                     }
                 ],
                 "responses": {
@@ -562,74 +523,15 @@
                         "schema": {
                             "type": "string"
                         }
-                    }
-                }
-            },
-            "put": {
-                "consumes": [
-                    "application/json"
-                ],
-                "produces": [
-                    "application/json"
-                ],
-                "tags": [
-                    "users"
-                ],
-                "summary": "更新用户",
-                "parameters": [
-                    {
-                        "type": "string",
-                        "description": "username",
-                        "name": "username",
-                        "in": "query",
-                        "required": true
-                    },
-                    {
-                        "type": "string",
-                        "description": "password",
-                        "name": "password",
-                        "in": "query",
-                        "required": true
                     },
-                    {
-                        "type": "integer",
-                        "description": "role_id",
-                        "name": "role_id",
-                        "in": "query"
-                    }
-                ],
-                "responses": {
-                    "200": {
-                        "description": "{ \"code\": 200, \"data\": {}, \"msg\": \"ok\" }",
+                    "400": {
+                        "description": "{\"code\":400,  \"data\":null,\"msg\":\"请求参数错误\"}",
                         "schema": {
                             "type": "string"
                         }
-                    }
-                }
-            },
-            "delete": {
-                "consumes": [
-                    "application/json"
-                ],
-                "produces": [
-                    "application/json"
-                ],
-                "tags": [
-                    "users"
-                ],
-                "summary": "删除用户",
-                "parameters": [
-                    {
-                        "type": "integer",
-                        "description": "id",
-                        "name": "id",
-                        "in": "path",
-                        "required": true
-                    }
-                ],
-                "responses": {
-                    "200": {
-                        "description": "{ \"code\": 200, \"data\": {}, \"msg\": \"ok\" }",
+                    },
+                    "404": {
+                        "description": "{ \"code\": 404, \"data\":null,\"msg\":\"请求参数错误\"}",
                         "schema": {
                             "type": "string"
                         }

+ 32 - 95
docs/swagger.yaml

@@ -305,63 +305,39 @@ paths:
       summary: 获取单个用户信息
       tags:
       - users
-  /authdata/users:
-    get:
-      consumes:
-      - application/json
-      parameters:
-      - description: username
-        in: path
-        name: username
-        type: string
-      produces:
-      - application/json
-      responses:
-        "200":
-          description: '{ "code": 200, "data": {}, "msg": "ok" }'
-          schema:
-            type: string
-      summary: 获取所有用户
-      tags:
-      - users
+  /data/GetDataByName:
     post:
       consumes:
       - application/json
       parameters:
-      - description: username
-        in: query
-        name: username
+      - description: sqlname
+        in: body
+        name: sqlname
         required: true
-        type: string
-      - description: password
-        in: query
-        name: password
+        schema:
+          $ref: '#/definitions/string'
+          type: object
+      - description: offset
+        in: body
+        name: offset
         required: true
-        type: string
-      - description: role_id
-        in: path
-        name: role_id
-        type: integer
-      produces:
-      - application/json
-      responses:
-        "200":
-          description: '{ "code": 200, "data": {}, "msg": "ok" }'
-          schema:
-            type: string
-      summary: 增加用户1
-      tags:
-      - users
-  /authdata/users/:
-    delete:
-      consumes:
-      - application/json
-      parameters:
-      - description: id
-        in: path
-        name: id
+        schema:
+          $ref: '#/definitions/int'
+          type: object
+      - description: pagecount
+        in: body
+        name: pagecount
         required: true
-        type: integer
+        schema:
+          $ref: '#/definitions/int'
+          type: object
+      - description: returntype
+        in: body
+        name: returntype
+        required: true
+        schema:
+          $ref: '#/definitions/string'
+          type: object
       produces:
       - application/json
       responses:
@@ -369,56 +345,17 @@ paths:
           description: '{ "code": 200, "data": {}, "msg": "ok" }'
           schema:
             type: string
-      summary: 删除用户
-      tags:
-      - users
-    get:
-      consumes:
-      - application/json
-      parameters:
-      - description: id
-        in: path
-        name: id
-        required: true
-        type: integer
-      produces:
-      - application/json
-      responses:
-        "200":
-          description: '{ "code": 200, "data": {}, "msg": "ok" }'
+        "400":
+          description: '{"code":400,  "data":null,"msg":"请求参数错误"}'
           schema:
             type: string
-      summary: 获取单个用户信息
-      tags:
-      - users
-    put:
-      consumes:
-      - application/json
-      parameters:
-      - description: username
-        in: query
-        name: username
-        required: true
-        type: string
-      - description: password
-        in: query
-        name: password
-        required: true
-        type: string
-      - description: role_id
-        in: query
-        name: role_id
-        type: integer
-      produces:
-      - application/json
-      responses:
-        "200":
-          description: '{ "code": 200, "data": {}, "msg": "ok" }'
+        "404":
+          description: '{ "code": 404, "data":null,"msg":"请求参数错误"}'
           schema:
             type: string
-      summary: 更新用户
+      summary: 根据APISQL表中SQL执行得到数据集
       tags:
-      - users
+      - GetDataByName
   /data/GetDataByNameForm:
     post:
       consumes:

+ 253 - 3
routers/api/db.go

@@ -664,8 +664,8 @@ func GetReportform(c *gin.Context) {
 	checked := fsion.Get("checked").ValueStr()
 	offset := fsion.Get("offset").ValueDefaultInt(0)
 	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
-
 	parammaps := fsion.Get("parammaps")
+	typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部  1 理论, 2实际
 	logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
 	tx := restful.Engine.NewSession()
 	err := tx.Begin()
@@ -685,7 +685,7 @@ func GetReportform(c *gin.Context) {
 		}
 	}()
 
-	queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount)
+	queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea)
 	if err != nil {
 		appG.Response(http.StatusOK, e.ERROR, err.Error())
 	} else {
@@ -4774,6 +4774,80 @@ func DeleteSpillageAll(c *gin.Context) {
 	appG.Response(http.StatusOK, e.SUCCESS, true)
 }
 
+func GetTMRListEnableTypeAll(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	parammaps := fsion.Get("parammaps")
+	pastureid := parammaps.Get("pastureid").ValueStr()
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL(`SELECT
+	eqcode,
+	tname,
+	datacaptureno,
+	trim(tclassid) tclassid,
+	concat(tname,' / ',eqcode) tmrmix,
+	d.label tclassname,
+	maxstirfeed,
+	remark,
+	tmr.enable,
+	TRIM(tmr.id) id,
+	TRIM(tmr.pastureid)pastureid
+	FROM
+	  tmr
+	left	join dictlist d on d.pid = 16 and d.value = tmr.tclassid 
+	WHERE tmr.pastureid = ?  and tmr.enable=1  and tclassid in (1,3)
+	ORDER BY id DESC`, pastureid).Query().List()
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+
+	sysoptData, err := tx.SQL(`select inforvalue from  sysopt where inforname = 'anyCar' and  pastureid = ? `, pastureid).Query().List()
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+
+	var carNum int64
+	for _, sysopt := range sysoptData {
+		if sysopt["inforvalue"] == nil {
+			carNum = 1
+		} else {
+			carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
+		}
+	}
+
+	id := 200
+	n := 0
+	for i := carNum; i > 0; i-- {
+		id++
+		n++
+		data := make(map[string]interface{}, 0)
+		data["eqcode"] = fmt.Sprintf("任意车%d", n)
+		data["tname"] = fmt.Sprintf("任意车%d", n)
+		data["datacaptureno"] = -2
+		data["tclassid"] = -2
+		data["tmrmix"] = fmt.Sprintf("任意车%d", n)
+		data["tclassname"] = fmt.Sprintf("任意车%d", n)
+		data["maxstirfeed"] = 100000
+		data["remark"] = fmt.Sprintf("任意车%d", n)
+		data["enable"] = 1
+		data["id"] = fmt.Sprintf("%d", id)
+		data["pastureid"] = pastureid
+		dataList = append(dataList, data)
+	}
+	// UNION ALL
+	// SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
+
+	appG.Response(http.StatusOK, e.SUCCESS, dataList)
+}
+
 func GetFeedpHistory(c *gin.Context) {
 	appG := app.Gin{C: c}
 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
@@ -4840,7 +4914,7 @@ func GetFeedpHistory(c *gin.Context) {
 // 	tx := restful.Engine.NewSession()
 // 	defer tx.Close()
 
-// // 	feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s')  as createdate 
+// // 	feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s')  as createdate
 // // 	from  lpplandtl1history  lh   join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
 // //    and  lh.createdate between ? and ?  order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
 // // 	if err != nil {
@@ -4874,3 +4948,179 @@ func GetFeedpHistory(c *gin.Context) {
 
 // 	appG.Response(http.StatusOK, e.SUCCESS, nil)
 // }
+
+func GetRemind(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	parammaps := fsion.Get("parammaps")
+	pastureid := parammaps.Get("pastureid").ValueStr()
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL("select * from  remind  where  pastureid  = ? ", pastureid).Query().List()
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+
+	// pastureid = "3"
+	resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+	defer resp.Body.Close()
+	buf := bytes.NewBuffer(make([]byte, 0, 512))
+	buf.ReadFrom(resp.Body)
+	fmt.Println(string(buf.Bytes()))
+
+	respMap := make(map[string]interface{}, 0)
+	err = json.Unmarshal(buf.Bytes(), &respMap)
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+
+	for _, data := range dataList {
+		r := make(map[string]interface{}, 0)
+		r["sys_name"] = ""
+		r["service_id"] = ""
+		r["pasture_id"] = ""
+		r["type_name"] = ""
+		r["remind_type_id"] = ""
+		r["remind_type"] = ""
+		r["push_date"] = ""
+		r["push_time"] = ""
+		r["interval_time"] = ""
+		r["push_limit"] = ""
+		r["template_id"] = ""
+		r["roles_id"] = ""
+		r["users_id"] = ""
+		r["date_type"] = ""
+		r["cycle_type"] = ""
+
+		data["data"] = r
+		for _, resp := range respMap["data"].([]interface{}) {
+			resp1 := resp.(map[string]interface{})
+			if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
+				if resp1["push_time"] == nil {
+					resp1["push_time"] = ""
+				}
+				data["data"] = resp1
+				break
+			}
+		}
+	}
+
+	appG.Response(http.StatusOK, e.SUCCESS, dataList)
+}
+
+type NoticeMsgtype struct {
+	SysName      string `json:"sys_name"`
+	PastureId    int64  `json:"pasture_id"`
+	ServiceId    int64  `json:"service_id"`
+	TypeName     string `json:"type_name"`
+	RemindType   int64  `json:"remind_type"`
+	PushDate     int64  `json:"push_date"`
+	PushTime     string `json:"push_time"`
+	IntervalTime int64  `json:"interval_time"`
+	PushLimit    int64  `json:"push_limit"`
+	TemplateId   string `json:"template_id"`
+	UsersId      string `json:"users_id"`
+	DateType     int64  `json:"date_type"`
+	CycleType    int64  `json:"cycle_type"`
+	DelayTime    int64  `json:"delay_time"`
+	Status       int64  `json:"status"`
+}
+
+func UpdateRemind(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	parammaps := gofasion.NewFasion(string(dataByte))
+	// parammaps := fsion.Get("parammaps")
+	// user := parammaps.Get("user").ValueStr()
+	id := parammaps.Get("id").ValueInt64()
+	noticeMsgtype := new(NoticeMsgtype)
+	noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
+	noticeMsgtype.ServiceId = id
+	noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
+	noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
+	// noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
+	noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
+	noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
+	noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
+	noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
+	noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
+	noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
+	// noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
+	noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
+	noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
+	noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
+	noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
+	userList := parammaps.Get("user").Array()
+
+	var userstr []string
+	for _, user := range userList {
+		userstr = append(userstr, user.ValueStr())
+	}
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	_, err := tx.SQL(` update remind set user = ? where id =  ? and  pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+
+	// var jsonStr = []byte(noticeMsgtype
+	noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
+	req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
+
+	req.Header.Set("Content-Type", "application/json")
+	client := &http.Client{}
+	resp, err := client.Do(req)
+	if err != nil {
+		logs.Error(err)
+	}
+
+	defer resp.Body.Close()
+	body, _ := ioutil.ReadAll(resp.Body)
+	fmt.Println("response Body:", string(body))
+
+	getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+	defer getresp.Body.Close()
+	buf := bytes.NewBuffer(make([]byte, 0, 512))
+	buf.ReadFrom(getresp.Body)
+	fmt.Println(string(buf.Bytes()))
+
+	respMap := make(map[string]interface{}, 0)
+	err = json.Unmarshal(buf.Bytes(), &respMap)
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+
+	for _, resp := range respMap["data"].([]interface{}) {
+		resp1 := resp.(map[string]interface{})
+		_, err := tx.SQL(` update remind set service_id = ? where id =  ? and  pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
+		if err != nil {
+			logs.Error(err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			return
+		}
+	}
+
+	appG.Response(http.StatusOK, e.SUCCESS, true)
+}

+ 85 - 38
routers/api/report.go

@@ -14,7 +14,7 @@ import (
 )
 
 //包含报表模块前端需要的各种数据格式转换
-func praseReportform(sqlnamestr string, parammaps *gofasion.Fasion, tx *xorm.Session, checked string, offset, count int) (queryData map[string]interface{}, err error) {
+func praseReportform(sqlnamestr string, parammaps *gofasion.Fasion, tx *xorm.Session, checked string, offset, count, typea int) (queryData map[string]interface{}, err error) {
 
 	sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
 	s_params := make([]interface{}, 0)
@@ -124,7 +124,7 @@ func praseReportform(sqlnamestr string, parammaps *gofasion.Fasion, tx *xorm.Ses
 			}
 		}
 		queryListSum, _ := tx.SQL(sql1, s_params1...).Query().List()
-		queryData, err = getAccuracyV4(queryList, queryListSum, checked, feednamesort3)
+		queryData, err = getAccuracyV4(queryList, queryListSum, checked, feednamesort3, typea)
 	case "getPriceAn":
 		queryData, err = getAccuracyV5(queryList)
 	case "getJT1Accu":
@@ -284,18 +284,32 @@ func getAccuracyV9(queryList []map[string]interface{}, sqlnamestr string, flleig
 			for key := range mtem {
 				mapc2[xorm.String(key)] = 0
 			}
-			var lweight float64
+			// var lweight float64
 			if queryList[i]["lweight"] != nil {
-				lweight, _ = strconv.ParseFloat(queryList[i]["lweight"].(string), 64)
+				// var error errors.Error
+				lweight, err := strconv.ParseFloat(queryList[i]["lweight"].(string), 64)
+				if err == nil {
+					mapc2[xorm.String(queryList[i]["fname"])] = lweight
+				} else {
+					mapc2[xorm.String(queryList[i]["fname"])] = queryList[i]["lweight"]
+				}
+			} else {
+				mapc2[xorm.String(queryList[i]["fname"])] = queryList[i]["lweight"]
 			}
-			mapc2[xorm.String(queryList[i]["fname"])] = lweight
+
 		}
 		if tem == queryList[i]["projname"] {
-			var lweight float64
+			// var lweight float64
 			if queryList[i]["lweight"] != nil {
-				lweight, _ = strconv.ParseFloat(queryList[i]["lweight"].(string), 64)
+				lweight, err := strconv.ParseFloat(queryList[i]["lweight"].(string), 64)
+				if err == nil {
+					mapc2[xorm.String(queryList[i]["fname"])] = lweight
+				} else {
+					mapc2[xorm.String(queryList[i]["fname"])] = queryList[i]["lweight"]
+				}
+			} else {
+				mapc2[xorm.String(queryList[i]["fname"])] = queryList[i]["lweight"]
 			}
-			mapc2[xorm.String(queryList[i]["fname"])] = lweight
 		} else {
 			data2 = append(data2, mapc2)
 			tem = queryList[i]["projname"]
@@ -308,12 +322,16 @@ func getAccuracyV9(queryList []map[string]interface{}, sqlnamestr string, flleig
 			for key := range mtem {
 				mapc2[xorm.String(key)] = 0
 			}
-			var lweight float64
 			if queryList[i]["lweight"] != nil {
-				lweight, _ = strconv.ParseFloat(queryList[i]["lweight"].(string), 64)
+				lweight, err := strconv.ParseFloat(queryList[i]["lweight"].(string), 64)
+				if err == nil {
+					mapc2[xorm.String(queryList[i]["fname"])] = lweight
+				} else {
+					mapc2[xorm.String(queryList[i]["fname"])] = queryList[i]["lweight"]
+				}
+			} else {
+				mapc2[xorm.String(queryList[i]["fname"])] = queryList[i]["lweight"]
 			}
-			mapc2[xorm.String(queryList[i]["fname"])] = lweight
-
 		}
 	}
 
@@ -751,7 +769,7 @@ func getAccuracyV5(queryList []map[string]interface{}) (map[string]interface{},
 	queryData["data"] = queryList
 	return queryData, nil
 }
-func getAccuracyV4(queryList []map[string]interface{}, queryListSum []map[string]interface{}, checked string, feednamesort3 []string) (map[string]interface{}, error) {
+func getAccuracyV4(queryList []map[string]interface{}, queryListSum []map[string]interface{}, checked string, feednamesort3 []string, typea int) (map[string]interface{}, error) {
 	queryData := make(map[string]interface{})
 	chartData := make(map[string]interface{})
 	datamap1 := make(map[string]interface{})
@@ -858,17 +876,18 @@ func getAccuracyV4(queryList []map[string]interface{}, queryListSum []map[string
 
 		if queryList[i]["fname"] == temstr {
 			datamap2["label"] = queryList[i]["feedname"]
-
-			datamap2child["label"] = "理论"
-			datamap2child["prop"] = "a" + strconv.Itoa(a)
-			data3 = append(data3, datamap2child)
-			datamap2child = make(map[string]interface{})
-
-			datamap2child["label"] = "实际"
-			datamap2child["prop"] = "a" + strconv.Itoa(a+1)
-			data3 = append(data3, datamap2child)
-			datamap2child = make(map[string]interface{})
-
+			if typea == 0 || typea == 1 {
+				datamap2child["label"] = "理论"
+				datamap2child["prop"] = "a" + strconv.Itoa(a)
+				data3 = append(data3, datamap2child)
+				datamap2child = make(map[string]interface{})
+			}
+			if typea == 0 || typea == 2 {
+				datamap2child["label"] = "实际"
+				datamap2child["prop"] = "a" + strconv.Itoa(a+1)
+				data3 = append(data3, datamap2child)
+				datamap2child = make(map[string]interface{})
+			}
 			if checked == "1" {
 				datamap2child["label"] = "误差值"
 				datamap2child["prop"] = "a" + strconv.Itoa(a+2)
@@ -891,8 +910,21 @@ func getAccuracyV4(queryList []map[string]interface{}, queryListSum []map[string
 
 		datamap1["A"] = queryList[i]["fname"]
 
-		datamap1["a"+strconv.Itoa(a)] = queryList[i]["lweight"]
-		datamap1["a"+strconv.Itoa(a+1)] = queryList[i]["actualweightminus"]
+		if queryList[i]["lweight"] != nil {
+			var lweight float64
+			lweight, _ = strconv.ParseFloat(queryList[i]["lweight"].(string), 64)
+			datamap1["a"+strconv.Itoa(a)] = lweight
+		} else {
+			datamap1["a"+strconv.Itoa(a)] = queryList[i]["lweight"]
+		}
+		if queryList[i]["actualweightminus"] != nil {
+			var actualweightminus float64
+			actualweightminus, _ = strconv.ParseFloat(queryList[i]["actualweightminus"].(string), 64)
+			datamap1["a"+strconv.Itoa(a+1)] = actualweightminus
+		} else {
+			datamap1["a"+strconv.Itoa(a+1)] = queryList[i]["actualweightminus"]
+		}
+
 		if checked == "1" {
 			datamap1["a"+strconv.Itoa(a+2)] = queryList[i]["diff"]
 			datamap1["a"+strconv.Itoa(a+3)] = queryList[i]["diffrate"]
@@ -901,8 +933,21 @@ func getAccuracyV4(queryList []map[string]interface{}, queryListSum []map[string
 
 		for z := 0; z < len(queryListSum); z++ {
 			if queryListSum[z]["fname"] == queryList[i]["fname"] {
-				datamap1["B"] = queryListSum[z]["lweight"]
-				datamap1["C"] = queryListSum[z]["actualweightminus"]
+				if queryListSum[z]["lweight"] != nil {
+					var lweight float64
+					lweight, _ = strconv.ParseFloat(queryListSum[z]["lweight"].(string), 64)
+					datamap1["B"] = lweight
+				} else {
+					datamap1["B"] = queryListSum[z]["lweight"]
+				}
+
+				if queryListSum[z]["actualweightminus"] != nil {
+					var actualweightminus float64
+					actualweightminus, _ = strconv.ParseFloat(queryListSum[z]["actualweightminus"].(string), 64)
+					datamap1["C"] = actualweightminus
+				} else {
+					datamap1["B"] = queryListSum[z]["actualweightminus"]
+				}
 
 			}
 		}
@@ -910,16 +955,18 @@ func getAccuracyV4(queryList []map[string]interface{}, queryListSum []map[string
 		if i == len(queryList)-1 {
 
 			datamap2["label"] = "合计"
-			datamap2child = make(map[string]interface{})
-			datamap2child["label"] = "理论"
-			datamap2child["prop"] = "B"
-			data3 = append(data3, datamap2child)
-
-			datamap2child = make(map[string]interface{})
-			datamap2child["label"] = "实际"
-			datamap2child["prop"] = "C"
-			data3 = append(data3, datamap2child)
-
+			if typea == 0 || typea == 1 {
+				datamap2child = make(map[string]interface{})
+				datamap2child["label"] = "理论"
+				datamap2child["prop"] = "B"
+				data3 = append(data3, datamap2child)
+			}
+			if typea == 0 || typea == 2 {
+				datamap2child = make(map[string]interface{})
+				datamap2child["label"] = "实际"
+				datamap2child["prop"] = "C"
+				data3 = append(data3, datamap2child)
+			}
 			//	###########################
 			datamap2["children"] = data3
 			data2 = append(data2, datamap2)

+ 229 - 189
routers/api/scheduled.go

@@ -38,199 +38,78 @@ func CronScheduled(ctx context.Context) {
 		return
 	}
 
-	duetimecst, _ := time.ParseInLocation("15:04:05", "00:00:30", time.Local)
-	duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
-	spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
-
-	c := cron.New()
-	c.AddFunc(spec, func() {
-		tx1 := restful.Engine.NewSession()
-		defer tx1.Close()
-		exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
-		if err != nil {
-			logs.Error("CronScheduled-error-1:", err)
-			return
-		}
-
-		fmt.Println(exist)
-		if exist {
-			_, err := tx.SQL(`update notice set status = 0  where content =  ? `, "downloadedplan_log").Execute()
-			if err != nil {
-				logs.Error("CronScheduled-error-2:", err)
-				return
-			}
-			Scheduled(ctx, tx1, pastureinfo)
-		}
-
-	})
-	c.Start()
-
-	// duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:01", time.Local)
-	// duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
-	// spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
-
-	// downloadplandtl1 := cron.New()
-	// downloadplandtl1.AddFunc(spec1, func() {
-	// 	tx2 := restful.Engine.NewSession()
-	// 	defer tx2.Close()
-
-	// 	exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
+	// duetimecst, _ := time.ParseInLocation("15:04:05", "00:05:00", time.Local)
+	// duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
+	// spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
+
+	// c := cron.New()
+	// c.AddFunc(spec, func() {
+	// 	tx1 := restful.Engine.NewSession()
+	// 	defer tx1.Close()
+	// 	exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
 	// 	if err != nil {
-	// 		logs.Error("CronScheduled-error-4:", err)
+	// 		logs.Error("CronScheduled-error-1:", err)
 	// 		return
 	// 	}
+
 	// 	fmt.Println(exist)
 	// 	if exist {
-	// 		_, err := tx2.SQL(`update notice set status = 0  where content =  ? `, "downloadplandtl1").Execute()
+	// 		_, err := tx.SQL(`update notice set status = 0  where content =  ? `, "downloadedplan_log").Execute()
 	// 		if err != nil {
-	// 			logs.Error("CronScheduled-error-5:", err)
+	// 			logs.Error("CronScheduled-error-2:", err)
 	// 			return
 	// 		}
+	// 		Scheduled(ctx, tx1, pastureinfo)
+	// 	}
 
-	// 		dataList, err := tx2.SQL("select * from downloadplandtl1_log  where date = date_format(now(),'%Y-%m-%d') ").Query().List()
-	// 		if err != nil {
-	// 			logs.Error("CronScheduled-error-6:", err)
-	// 			return
-	// 		}
-	// 		plandtl1SlIdMap := make(map[string][]int64, 0)
-	// 		// plandtl1HlIdMap := make(map[string][]string, 0)
-	// 		for _, data := range dataList {
-	// 			if data["type"].(int64) == 0 && data["plandtl1"] != nil {
-	// 				plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
-	// 			}
+	// })
+	// c.Start()
 
-	// 		}
+	duetimecst2, _ := time.ParseInLocation("15:04:05", "00:00:30", time.Local)
+	duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
+	spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
 
-	// 		for _, data := range dataList {
-	// 			if data["type"].(int64) == 0 {
-	// 				plandtl1List, err := tx2.SQL(`select d1.fname,d.tmrtname,d1.intime,d1.id,d1.feedallowratio,abs(d1.actualweightminus -d1.lweight ) errorvalue ,d1.actualweightminus,d1.lweight,
-	// 				if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy  from
-	// 				downloadplandtl1 d1
-	// 				join downloadedplan d on d.id = d1.pid
-	// 				where d1.pid = ?  and d1.sort = ?  and  d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
-	// 					data["planid"], data["sort"], data["pastureid"]).Query().List()
-
-	// 				if err != nil {
-	// 					logs.Error("CronScheduled-error-7:", err)
-	// 					return
-	// 				}
-	// 				idexist := false
-	// 				for _, plandtl1 := range plandtl1List {
-	// 					//防止同顺序饲料多次推送
-	// 					for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
-	// 						if plandtl1Id == plandtl1["id"].(int64) {
-	// 							idexist = true
-	// 							break
-	// 						}
-
-	// 					}
-	// 					if idexist {
-	// 						continue
-	// 					}
-
-	// 					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
-	// 					if plandtl1["feedallowratio"].(float64) < errorvalue {
-	// 						// if plandtl1["feedallowratio"].(float64) < plandtl1["errorvalue"].(float64) {
-	// 						fmt.Println(plandtl1, "推送")
-	// 						target := []string{"13916925233"}
-	// 						var sendList []interface{}
-	// 						sendStr := fmt.Sprintf("tmr名称:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率:%v",
-	// 							plandtl1["tmrtname"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
-	// 						// content = append(content, "混料", plandtl1["begintime"], "kpt", sendStr, "搅拌预警")
-
-	// 						sendMap1 := make(map[string]interface{}, 0)
-	// 						sendMap1["value"] = "搅拌"
-	// 						sendMap1["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap1)
-	// 						sendMap2 := make(map[string]interface{}, 0)
-	// 						sendMap2["value"] = plandtl1["intime"]
-	// 						sendMap2["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap2)
-	// 						sendMap3 := make(map[string]interface{}, 0)
-	// 						sendMap3["value"] = "kpt"
-	// 						sendMap3["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap3)
-	// 						sendMap4 := make(map[string]interface{}, 0)
-	// 						sendMap4["value"] = sendStr
-	// 						sendMap4["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap4)
-
-	// 						sendMap5 := make(map[string]interface{}, 0)
-	// 						sendMap5["value"] = "搅拌预警"
-	// 						sendMap5["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap5)
-	// 						wxPush(target, sendList)
-	// 					}
-
-	// 					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
-	// 					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ?  and type =  0 ", plandtl1["id"], data["id"]).Execute()
-	// 					if err != nil {
-	// 						logs.Error("CronScheduled-error-8:", err)
-	// 						return
-	// 					}
-
-	// 				}
-	// 			} else {
-	// 				plandtl1List, err := tx2.SQL(`select  d2.fname,d.tmrtname,d2.id,ifnull(d2.allowratio,0) allowratio ,abs(d2.actualweightminus -d2.lweight ) errorvalue ,d2.intime,d2.actualweightminus,d2.lweight,
-	// 				if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
-	// 			 from 	downloadplandtl2 d2
-	// 				join downloadedplan d on d.id = d2.pid
-	// 				where d2.pid = ?  and d2.sort = ?  and  d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
-	// 					data["planid"], data["sort"], data["pastureid"]).Query().List()
-	// 				// Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
-	// 				if err != nil {
-	// 					logs.Error("CronScheduled-error-7:", err)
-	// 					return
-	// 				}
-	// 				for _, plandtl1 := range plandtl1List {
-	// 					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
-	// 					if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
-	// 						fmt.Println(plandtl1, "推送")
-	// 						target := []string{"13916925233"}
-	// 						// var content []interface{}
-
-	// 						var sendList []interface{}
-	// 						sendStr := fmt.Sprintf("tmr名称:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率:%v",
-	// 							plandtl1["tmrtname"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
-	// 						sendMap1 := make(map[string]interface{}, 0)
-	// 						sendMap1["value"] = "撒料"
-	// 						sendMap1["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap1)
-	// 						sendMap2 := make(map[string]interface{}, 0)
-	// 						sendMap2["value"] = plandtl1["intime"]
-	// 						sendMap2["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap2)
-	// 						sendMap3 := make(map[string]interface{}, 0)
-	// 						sendMap3["value"] = "kpt"
-	// 						sendMap3["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap3)
-	// 						sendMap4 := make(map[string]interface{}, 0)
-	// 						sendMap4["value"] = sendStr
-	// 						sendMap4["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap4)
-
-	// 						sendMap5 := make(map[string]interface{}, 0)
-	// 						sendMap5["value"] = "撒料预警"
-	// 						sendMap5["color"] = "#173177"
-	// 						sendList = append(sendList, sendMap5)
-
-	// 						wxPush(target, sendList)
-	// 					}
-
-	// 					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
-	// 					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
-	// 					if err != nil {
-	// 						logs.Error("CronScheduled-error-8:", err)
-	// 						return
-	// 					}
-
-	// 				}
-	// 			}
-	// 		}
-	// 	}
-	// })
+	downloadplandtl1 := cron.New()
+	downloadplandtl1.AddFunc(spec1, func() {
+		dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? `, pastureinfo.Pastureid).Query().List()
+		if err != nil {
+			logs.Error("CronScheduled-error-3:", err)
+			return
+		}
+		for _, data := range dataList {
+			if data["function"].(string) == "processAnalysisEarlyWarning" {
+				// user := strings.Split(data["user"].(string), ",")
+				if len(data["user"].(string)) > 0 {
+					var userids string
+					for _, str := range strings.Split(data["user"].(string), ",") {
+						if len(userids) <= 0 {
+							userids = fmt.Sprintf("'%s'", str)
+						} else {
+							userids += fmt.Sprintf(",'%s'", str)
+						}
+					}
+					sql := fmt.Sprintf(` select openid from user_wx where pastureid = ? and userid in(%s)`, userids)
+					fmt.Println(sql)
+					openidList, err := tx.SQL(sql, pastureinfo.Pastureid).Query().List()
+					// openidList, err := tx.Table("user_wx").Where(" pastureid = ? ", pastureinfo.Pastureid).And("userid in (?)", data["user"].(string)).Query().List()
+					if err != nil {
+						logs.Error("CronScheduled-error-4:", err)
+						return
+					}
 
-	// downloadplandtl1.Start()
+					var openIdList []string
+					for _, open := range openidList {
+						if open["openid"] != nil {
+							openIdList = append(openIdList, open["openid"].(string))
+						}
+					}
+					processAnalysisEarlyWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
+				}
+			}
+		}
+	})
+
+	downloadplandtl1.Start()
 }
 
 type ScheduledInfo struct {
@@ -852,17 +731,18 @@ func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) err
 	return nil
 }
 
-func wxPush(target []string, content []interface{}) {
+func wxPush(target []string, content []interface{}, pastureId string, serviceId int64) {
 	url := "http://tmrwatch.cn/notice/message"
 
 	dataStr := `{
-		"sys_name": "tmrwatch",
-		"remind_type": "1",
+		"pasture_id":%s,
+		"service_id":%d,
+		"sys_name": "tmrWatch",
 		"template_id": "BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo",
 		"target": %s,
 		"miniprogram": {
-			"appid": "xiaochengxuappid12345",
-			"pagepath": "index?foo=bar"
+			"appid": "wx9ab2b5b25701da0a",
+			"pagepath": "pages/index/index?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTY1NDIzMDMxMywiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.jKLR74kTy9tXqFH5OwlwK7zTGKvMVbrOecsaJpxbxq8"
 		},
 		"keys": [
 			"first",
@@ -876,7 +756,8 @@ func wxPush(target []string, content []interface{}) {
 
 	targetStr, _ := json.Marshal(target)
 	contentStr, _ := json.Marshal(content)
-	dataStr = fmt.Sprintf(dataStr, string(targetStr), string(contentStr))
+	dataStr = fmt.Sprintf(dataStr, pastureId, serviceId, string(targetStr), string(contentStr))
+
 	var jsonStr = []byte(dataStr)
 	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
 
@@ -889,7 +770,8 @@ func wxPush(target []string, content []interface{}) {
 
 	defer resp.Body.Close()
 	body, _ := ioutil.ReadAll(resp.Body)
-	fmt.Println("response Body:", string(body))
+	fmt.Println(dataStr)
+	fmt.Println("response Body:", string(body), "fasong")
 }
 
 func UDPostPush1(data, method string) {
@@ -909,7 +791,6 @@ func UDPostPush1(data, method string) {
 
 	defer resp.Body.Close()
 	body, _ := ioutil.ReadAll(resp.Body)
-	fmt.Println("response Body:", string(body))
 	fsion := gofasion.NewFasion(string(body))
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
@@ -925,5 +806,164 @@ func UDPostPush1(data, method string) {
 			return
 		}
 	}
+	fmt.Println("response Body:", string(body))
+}
+
+func processAnalysisEarlyWarning(target []string, pastureId string, serviceId int64) {
+	tx2 := restful.Engine.NewSession()
+	defer tx2.Close()
+
+	exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
+	if err != nil {
+		logs.Error("CronScheduled-error-4:", err)
+		return
+	}
+	if exist {
+		_, err := tx2.SQL(`update notice set status = 0  where content =  ? `, "downloadplandtl1").Execute()
+		if err != nil {
+			logs.Error("CronScheduled-error-5:", err)
+			return
+		}
+
+		dataList, err := tx2.SQL("select * from downloadplandtl1_log  where date = date_format(now(),'%Y-%m-%d') ").Query().List()
+		if err != nil {
+			logs.Error("CronScheduled-error-6:", err)
+			return
+		}
+		plandtl1SlIdMap := make(map[string][]int64, 0)
+		// plandtl1HlIdMap := make(map[string][]string, 0)
+		for _, data := range dataList {
+			if data["type"].(int64) == 0 && data["plandtl1"] != nil {
+				plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
+			}
+
+		}
 
+		for _, data := range dataList {
+			if data["type"].(int64) == 0 {
+				plandtl1List, err := tx2.SQL(`select d1.fname,d.tmrtname,d1.intime,d1.id,d1.feedallowratio,abs(d1.actualweightminus -d1.lweight ) errorvalue ,d1.actualweightminus,d1.lweight,
+					if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy  from
+					downloadplandtl1 d1
+					join downloadedplan d on d.id = d1.pid
+					where d1.pid = ?  and d1.sort = ?  and  d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
+					data["planid"], data["sort"], data["pastureid"]).Query().List()
+
+				if err != nil {
+					logs.Error("CronScheduled-error-7:", err)
+					return
+				}
+				idexist := false
+				for _, plandtl1 := range plandtl1List {
+					//防止同顺序饲料多次推送
+					for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
+						if plandtl1Id == plandtl1["id"].(int64) {
+							idexist = true
+							break
+						}
+
+					}
+					if idexist {
+						continue
+					}
+
+					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
+					if plandtl1["feedallowratio"].(float64) < errorvalue {
+						// if plandtl1["feedallowratio"].(float64) < plandtl1["errorvalue"].(float64) {
+						fmt.Println(plandtl1, "推送")
+						// target := []string{"13916925233"}
+						var sendList []interface{}
+						sendStr := fmt.Sprintf("tmr名称:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率:%v",
+							plandtl1["tmrtname"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
+						// content = append(content, "混料", plandtl1["begintime"], "kpt", sendStr, "搅拌预警")
+
+						sendMap1 := make(map[string]interface{}, 0)
+						sendMap1["value"] = "搅拌"
+						sendMap1["color"] = "#173177"
+						sendList = append(sendList, sendMap1)
+						sendMap2 := make(map[string]interface{}, 0)
+						sendMap2["value"] = plandtl1["intime"]
+						sendMap2["color"] = "#173177"
+						sendList = append(sendList, sendMap2)
+						sendMap3 := make(map[string]interface{}, 0)
+						sendMap3["value"] = "kpt"
+						sendMap3["color"] = "#173177"
+						sendList = append(sendList, sendMap3)
+						sendMap4 := make(map[string]interface{}, 0)
+						sendMap4["value"] = sendStr
+						sendMap4["color"] = "#173177"
+						sendList = append(sendList, sendMap4)
+
+						sendMap5 := make(map[string]interface{}, 0)
+						sendMap5["value"] = "搅拌预警"
+						sendMap5["color"] = "#173177"
+						sendList = append(sendList, sendMap5)
+						wxPush(target, sendList, pastureId, serviceId)
+					}
+
+					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
+					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ?  and type =  0 ", plandtl1["id"], data["id"]).Execute()
+					if err != nil {
+						logs.Error("CronScheduled-error-8:", err)
+						return
+					}
+
+				}
+			} else {
+				plandtl1List, err := tx2.SQL(`select  d2.fname,d.tmrtname,d2.id,ifnull(d2.allowratio,0) allowratio ,abs(d2.actualweightminus -d2.lweight ) errorvalue ,d2.intime,d2.actualweightminus,d2.lweight,
+					if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
+				 from 	downloadplandtl2 d2
+					join downloadedplan d on d.id = d2.pid
+					where d2.pid = ?  and d2.sort = ?  and  d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
+					data["planid"], data["sort"], data["pastureid"]).Query().List()
+				// Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
+				if err != nil {
+					logs.Error("CronScheduled-error-7:", err)
+					return
+				}
+				for _, plandtl1 := range plandtl1List {
+					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
+					if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
+						fmt.Println(plandtl1, "推送")
+						// target := []string{"13916925233"}
+						// var content []interface{}
+
+						var sendList []interface{}
+						sendStr := fmt.Sprintf("tmr名称:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率:%v",
+							plandtl1["tmrtname"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
+						sendMap1 := make(map[string]interface{}, 0)
+						sendMap1["value"] = "撒料"
+						sendMap1["color"] = "#173177"
+						sendList = append(sendList, sendMap1)
+						sendMap2 := make(map[string]interface{}, 0)
+						sendMap2["value"] = plandtl1["intime"]
+						sendMap2["color"] = "#173177"
+						sendList = append(sendList, sendMap2)
+						sendMap3 := make(map[string]interface{}, 0)
+						sendMap3["value"] = "kpt"
+						sendMap3["color"] = "#173177"
+						sendList = append(sendList, sendMap3)
+						sendMap4 := make(map[string]interface{}, 0)
+						sendMap4["value"] = sendStr
+						sendMap4["color"] = "#173177"
+						sendList = append(sendList, sendMap4)
+
+						sendMap5 := make(map[string]interface{}, 0)
+						sendMap5["value"] = "撒料预警"
+						sendMap5["color"] = "#173177"
+						sendList = append(sendList, sendMap5)
+
+						wxPush(target, sendList, pastureId, serviceId)
+					}
+
+					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
+					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
+					if err != nil {
+						logs.Error("CronScheduled-error-8:", err)
+						return
+					}
+
+				}
+			}
+		}
+	}
 }

+ 87 - 10
routers/api/spillage.go

@@ -1197,15 +1197,6 @@ func UpdateLpplan(c *gin.Context) {
 		return
 	}
 
-	// if tmrid != lpplan.Tmrid {
-	// 	_, err = tx.SQL(`delete from lpplandtl1 where lppid = ? and pastureid = ? `, lpplanid, pastureid).Execute()
-	// 	if err != nil {
-	// 		log.Println("UpdateLpplan-error-2: ", err)
-	// 		appG.Response(http.StatusInternalServerError, e.ERROR, err)
-	// 		tx.Rollback()
-	// 		return
-	// 	}
-	// }
 	err = tx.Commit()
 	if err != nil {
 		log.Println("UpdateLpplan-error-3: ", err)
@@ -1214,6 +1205,92 @@ func UpdateLpplan(c *gin.Context) {
 		return
 	}
 
+	/*
+		dataList, err := tx.SQL(`select * from lpplandtl1 where lppid = ? and  pastureid = ? `, lpplanid, pastureid).Query().List()
+		if err != nil {
+			log.Println("UpdateLpplan-error-4: ", err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			return
+		}
+		// var oldbar, bar []int64
+		oldList := fsion.Get("old").Array()
+
+		if len(dataList) >= len(oldList) {
+			for _, data := range dataList {
+				updateStatus := true
+				for _, old := range oldList {
+					if (old.Get("tmrid").ValueInt64() == data["tmrid"].(int64) || old.Get("lweight").ValueStr() == data["lweight"].(string)) && old.Get("barid").ValueInt64() == data["barid"].(int64) {
+						updateStatus = false
+						break
+					}
+				}
+				if updateStatus {
+					now := time.Now()
+					for _, data := range dataList {
+						_, err = tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
+											background,cowcount,ccountradio,lweighthis,createdate)
+										values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+							data["pastureid"], data["lppid"], data["barid"],
+							data["barname"], data["fpdid"], data["fttype"],
+							data["lweight"], data["sort"], data["tmrid"],
+							data["tmrname"], data["background"], data["cowcount"],
+							data["ccountradio"], data["lweighthis"], now).Execute()
+						if err != nil {
+							log.Println("UpdateLpplan-error-5: ", err)
+							appG.Response(http.StatusInternalServerError, e.ERROR, err)
+							return
+						}
+					}
+					break
+				}
+			}
+		} else {
+			for _, old := range oldList {
+				updateStatus := true
+				for _, data := range dataList {
+					if (old.Get("tmrid").ValueInt64() == data["tmrid"].(int64) || old.Get("lweight").ValueStr() == data["lweight"].(string)) && old.Get("barid").ValueInt64() == data["barid"].(int64) {
+						updateStatus = false
+						break
+					}
+				}
+				if updateStatus {
+					now := time.Now()
+					for _, old := range oldList {
+						exist := false
+						var lweight, tmrid, tmrname interface{}
+						for _, data := range dataList {
+							if old.Get("barid").ValueInt64() == data["barid"].(int64) {
+								lweight = data["lweight"]
+								tmrid = data["tmrid"]
+								tmrname = data["tmrname"]
+								exist = true
+								break
+							}
+						}
+						if !exist {
+							tmrid = old.Get("tmrid").ValueInt64()
+							tmrname = old.Get("tmrname").ValueStr()
+							lweight = 0
+						}
+						_, err = tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
+											background,cowcount,ccountradio,lweighthis,createdate) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+							old.Get("pastureid").ValueStr(), old.Get("lppid").ValueStr(), old.Get("barid").ValueStr(),
+							old.Get("barname").ValueStr(), old.Get("fpdid").ValueStr(), old.Get("fttype").ValueStr(),
+							lweight, old.Get("sort").ValueStr(), tmrid,
+							tmrname, old.Get("background").ValueStr(), old.Get("cowcount").ValueStr(),
+							old.Get("ccountradio").ValueStr(), old.Get("lweighthis").ValueInt64(), now).Execute()
+						if err != nil {
+							log.Println("UpdateLpplan-error-6: ", err)
+							appG.Response(http.StatusInternalServerError, e.ERROR, err)
+							return
+						}
+					}
+					break
+				}
+			}
+		}
+	*/
+
 	appG.Response(http.StatusOK, e.SUCCESS, true)
 }
 
@@ -2102,7 +2179,7 @@ func AddLpplandtlDate(c *gin.Context) {
 	var err error
 
 	lpplandList := make([]*lpplandtl1, 0)
-	err = tx.Table("lpplandtl1date").Select("id,pastureid,sort,barid,tmrid").Where("lppid = ? ", parammaps.Get("lppid").ValueStr()).And("pastureid = ?", parammaps.Get("pastureid").ValueStr()).
+	err = tx.Table("lpplandtl1date").Select("id,pastureid,sort,barid,tmrid,tmrname").Where("lppid = ? ", parammaps.Get("lppid").ValueStr()).And("pastureid = ?", parammaps.Get("pastureid").ValueStr()).
 		And("date = ? ", parammaps.Get("date").ValueStr()).OrderBy("sort").Find(&lpplandList)
 	if err != nil {
 		log.Println("AddLpplandtl-error-1: ", err)

+ 1 - 1
routers/api/user.go

@@ -184,7 +184,7 @@ func UserWXOpenIDBinding(c *gin.Context) {
 		return
 	}
 
-	_, err := tx.SQL(` replace into user_wx(userid,pastureid,openid,name) VALUES (?,(select  pastureid  from user where username = ?),?,?)`, userlist[1], userlist[1], openid, userlist[2]).Execute()
+	_, err := tx.SQL(` replace into user_wx(userid,pastureid,openid,name) VALUES (?,?,?,?)`, userlist[2], userlist[1], openid, userlist[3]).Execute()
 	if err != nil {
 		logs.Error("UserWXOpenIDBinding-error2:", err)
 		appG.Response(http.StatusInternalServerError, e.ERROR, false)

+ 7 - 1
routers/router.go

@@ -1,6 +1,7 @@
 package routers
 
 import (
+	"context"
 	"fmt"
 
 	"../comm"
@@ -21,7 +22,7 @@ import (
 func InitRouter() *gin.Engine {
 	r := gin.New()
 	// go api.UDSync()
-	// go api.CronScheduled(context.TODO())
+	go api.CronScheduled(context.TODO())
 
 	r.Use(func(c *gin.Context) {
 		fmt.Println(c.Request.URL)
@@ -182,6 +183,11 @@ func InitRouter() *gin.Engine {
 		apiV1.POST("/spillageall/del", api.DeleteSpillageAll)
 
 		apiV1.POST("/feedp/history", api.GetFeedpHistory)
+		//查看撒料设备
+		apiV1.POST("/tmrListEnableTypeAll", api.GetTMRListEnableTypeAll)
+		//查看提醒设置
+		apiV1.POST("/remind/list", api.GetRemind)
+		apiV1.POST("/remind/edit", api.UpdateRemind)
 
 	}
 

BIN
tmrgo


BIN
__debug_bin.exe → tmrgo.exe


BIN
tmrgo.zip


File diff suppressed because it is too large
+ 18 - 1
update.sql


Some files were not shown because too many files changed in this diff