Ver Fonte

消息提醒提交

shawei_zz há 3 anos atrás
pai
commit
f40d0a26c3
68 ficheiros alterados com 1535 adições e 607 exclusões
  1. 5 1
      apiserver/config/config.go
  2. 0 7
      apiserver/config/config_test.go
  3. 0 19
      apiserver/model/http/mcs.go
  4. 32 16
      apiserver/model/http/message.go
  5. 77 28
      apiserver/model/message.go
  6. 18 0
      apiserver/model/model.go
  7. 8 0
      apiserver/model/user.go
  8. 19 5
      apiserver/server/message.go
  9. 1 1
      apiserver/server/server.go
  10. 0 7
      apiserver/server/server_test.go
  11. 10 9
      apiserver/server/wxoffice.go
  12. 51 107
      apiserver/service/job.go
  13. 170 97
      apiserver/service/message.go
  14. 16 87
      apiserver/service/send_test.go
  15. 21 2
      apiserver/service/service.go
  16. 22 1
      apiserver/service/user.go
  17. 60 47
      apiserver/service/wxoffce.go
  18. 21 0
      client/main.go
  19. 2 1
      cmd/apiserver/conf.toml
  20. 3 0
      cmd/apiserver/linux.bat
  21. 3 8
      cmd/apiserver/main.go
  22. BIN
      cmd/apiserver/notice
  23. 9 0
      conf.toml
  24. BIN
      doc/.DS_Store
  25. 69 0
      doc/bk.json
  26. 5 0
      doc/cow.md
  27. 19 0
      doc/cow.sql
  28. 5 0
      doc/dreq.sh
  29. 7 5
      doc/json/insert_type.json
  30. 61 24
      doc/json/message.json
  31. 17 0
      doc/json/type2.json
  32. 7 0
      doc/local.sh
  33. 7 0
      doc/md/maintenance_load.md
  34. 10 0
      doc/md/msg.md
  35. 64 0
      doc/md/msg_type.md
  36. BIN
      doc/md/msg_type.pdf
  37. 0 0
      doc/md/wx.md
  38. 39 0
      doc/msg.json
  39. 44 0
      doc/msgDoc.md
  40. BIN
      doc/msgDoc.pdf
  41. 64 0
      doc/msg_type.md
  42. BIN
      doc/notice
  43. 5 0
      doc/qt.json
  44. 3 0
      doc/run_local.sh
  45. 3 0
      doc/sh/deploy.sh
  46. 0 3
      doc/sh/devS.sh
  47. 0 3
      doc/sh/local.sh
  48. BIN
      doc/sh/main
  49. BIN
      doc/sh/notice
  50. 36 0
      doc/sql/apisql.sql
  51. 23 0
      doc/sql/dict.sql
  52. 6 0
      doc/sql/insert.sql
  53. 28 0
      doc/sql/log.sql
  54. 31 25
      doc/sql/message.sql
  55. 34 0
      doc/sql/mq.sql
  56. 46 0
      doc/sql/msg_query.sql
  57. 61 25
      doc/sql/msg_type.sql
  58. 41 0
      doc/sql/pas_url.sql
  59. 1 10
      doc/sql/query.sql
  60. 140 0
      doc/sql/repire/repire.sql
  61. 7 0
      doc/sql/test.sql
  62. 1 0
      doc/sql/up.sql
  63. 0 18
      go.mod
  64. 73 0
      local/local.go
  65. 0 33
      middleware/notice/notice_test.go
  66. 23 10
      middleware/notice/wxoffice.go
  67. BIN
      notice
  68. 7 8
      pkg/http/client.go

+ 5 - 1
apiserver/config/config.go

@@ -16,7 +16,10 @@ var (
 func init() {
 	flag.StringVar(&confPath, "conf", "conf.toml", "default config path")
 }
-func Init() (err error) {
+func Init(p string) (err error) {
+	if p != "" {
+		confPath = p
+	}
 	if _, err = toml.DecodeFile(confPath, &Conf); err != nil {
 		panic(err)
 	}
@@ -28,6 +31,7 @@ type Config struct {
 	DB     *MySQLConfig `toml:"db"`
 	Listen string       `toml:"listen"`
 	Log    *log.Config  `toml:"log"`
+	Env    string       `toml:"env"`
 }
 
 type MySQLConfig struct {

+ 0 - 7
apiserver/config/config_test.go

@@ -1,7 +0,0 @@
-package config
-
-import "testing"
-
-func Testinit(t *testing.T) {
-	Init()
-}

+ 0 - 19
apiserver/model/http/mcs.go

@@ -1,19 +0,0 @@
-package http
-
-type McsRequest struct {
-	Request bool    `json:"request"`
-	ID      int     `json:"id"`
-	Method  string  `json:"method"`
-	Data    McsData `json:"data"`
-}
-
-type McsData struct {
-	DevID    string `json:"devId"`
-	PeopleNo string `json:"peopleNo"`
-	WorkNo   string `json:"workNo"`
-	StorType int    `json:"storType"`
-}
-
-func (p *McsRequest) Validate() error {
-	return nil
-}

+ 32 - 16
apiserver/model/http/message.go

@@ -1,18 +1,27 @@
 package http
 
-import "errors"
+import (
+	"time"
+)
 
 type MessageResp struct {
-	Rows int `json:"rows"`
+	ID int `json:"id"`
 }
 
 type MessageReq struct {
 	MsgTypeID   int         `json:"msg_type_id"`
+	ServiceID   int         `form:"service_id" json:"service_id" gorm:"service_id"`
+	SysName     string      `form:"sys_name" json:"sys_name"  gorm:"sys_name"`
+	PastureID   int         `form:"pasture_id" json:"pasture_id" gorm:"pasture_id"`
 	Miniprogram Miniprogram `json:"miniprogram"`
 	Target      []string    `json:"target"`
 	Keys        []string    `json:"keys"`
 	Content     []Tag       `json:"content"`
 }
+type MessageTypeResp struct {
+	RowsAffected int    `json:"rows_affected"`
+	Method       string `json:"method"`
+}
 type Miniprogram struct {
 	AppID    string `json:"appid"`
 	PagePath string `json:"pagepath"`
@@ -23,28 +32,35 @@ type Tag struct {
 }
 
 type MessageTypeReq struct {
+	ID int `form:"id" json:"id" gorm:"column:id; primary_key;AUTO_INCREMENT" `
+
+	ServiceID int    `form:"service_id" json:"service_id" gorm:"service_id"`
 	SysName   string `form:"sys_name" json:"sys_name"  gorm:"sys_name"`
-	ID        int    `form:"id" json:"id" gorm:"id"`
 	PastureID int    `form:"pasture_id" json:"pasture_id" gorm:"pasture_id"`
+	TypeName  string `form:"type_name" json:"type_name" gorm:"type_name"`
+
+	RemindType int `form:"remind_type" json:"remind_type" gorm:"remind_type"`
+	DateType   int `form:"date_type" json:"date_type" gorm:"date_type"`
+	CycleType  int `form:"cycle_type" json:"cycle_type" gorm:"cycle_type"`
 
-	TypeName     string `form:"type_name" json:"type_name" gorm:"type_name"`
-	RemindTypeID int    `form:"remind_type_id" json:"remind_type_id" gorm:"remind_type_id"`
-	RemindType   string `form:"remind_type" json:"remind_type" gorm:"remind_type"`
-	PushDate     string `form:"push_date" json:"push_date" gorm:"push_date"`
+	DelayTime    int    `form:"delay_time" json:"delay_time" gorm:"delay_time"`
+	PushDate     int    `form:"push_date" json:"push_date" gorm:"push_date"`
 	PushTime     string `form:"push_time" json:"push_time" gorm:"push_time"`
 	IntervalTime int    `form:"interval_time" json:"interval_time" gorm:"interval_time"`
-	PushLimit    int    `form:"push_limit" json:"push_limit" gorm:"push_limit"`
-	TemplateID   string `form:"template_id" json:"template_id" gorm:"template_id"`
 
-	RolesID string `form:"roles_id" json:"roles_id" gorm:"roles_id"`
-	UsersID string `form:"users_id" json:"users_id" gorm:"users_id"`
+	PushLimit  int    `form:"push_limit" json:"push_limit" gorm:"push_limit"`
+	TemplateID string `form:"template_id" json:"template_id" gorm:"template_id"`
+	Status     int    `form:"status" json:"status" gorm:"status"`
+
+	CreatedAt time.Time `form:"created_at" json:"created_at" gorm:"created_at"`
+	UpdatedAt time.Time `form:"updated_at" json:"updated_at" gorm:"updated_at"`
 }
 
-func (m MessageTypeReq) Validate() error {
-	if m.SysName == "" || m.PastureID == 0 {
-		return errors.New("sys_name or  pasture_id is required")
-	}
-	return nil
+func (m MessageTypeReq) Validate() (err error) {
+	// if m.SysName == "" || m.PastureID == 0 || m.ServiceID == 0 {
+	// 	err = errors.New("sys_name or pasture_id or service_id is empty")
+	// }
+	return
 }
 
 func (p MessageReq) Validate() error {

+ 77 - 28
apiserver/model/message.go

@@ -3,32 +3,81 @@ package model
 import "time"
 
 type Message struct {
-	ID           int       `gorm:"primary_key;AUTO_INCREMENT"`
-	MsgTypeID    int       `gorm:"column:msg_type_id"`
-	RemindTypeID int       `gorm:"column:remind_type_id"`
-	MsgContent   string    `gorm:"column:msg_content"`
-	Target       string    `gorm:"column:target"`
-	CreatedAt    time.Time `gorm:"column:create_at"`
-	UpdateAt     time.Time `gorm:"column:update_at"`
-	status       int       `gorm:"column:status"`
-	PushCount    int       `gorm:"column:push_count"`
-	PushLimit    int       `gorm:"column:push_limit"`
-}
-
-type MessageType struct {
-	SysName   string `json:"sys_name" gorm:"sys_name"`
-	ID        int    `json:"id" gorm:"id"`
-	PastureID int    `json:"pasture_id" gorm:"pasture_id"`
-
-	TypeName     string `json:"type_name" gorm:"type_name"`
-	RemindTypeID int    `json:"remind_type_id" gorm:"remind_type_id"`
-	RemindType   string `json:"remind_type" gorm:"remind_type"`
-	PushDate     string `json:"push_date" gorm:"push_date"`
-	PushTime     string `json:"push_time" gorm:"push_time"`
-	IntervalTime int    `json:"interval_time" gorm:"interval_time"`
-	PushLimit    int    `json:"push_limit" gorm:"push_limit"`
-	TemplateID   string `json:"template_id" gorm:"template_id"`
-
-	Roles string `json:"roles_id" gorm:"roles_id"`
-	Users string `json:"users_id" gorm:"users_id"`
+	ID         int       `gorm:"primary_key;AUTO_INCREMENT"`
+	ServiceID  int       `form:"service_id" json:"service_id" gorm:"service_id"`
+	SysName    string    `form:"sys_name" json:"sys_name"  gorm:"sys_name"`
+	PastureID  int       `form:"pasture_id" json:"pasture_id" gorm:"pasture_id"`
+	MsgTypeID  int       `gorm:"column:msg_type_id"`
+	RemindType int       `gorm:"column:remind_type"`
+	MsgContent string    `gorm:"column:msg_content"`
+	Target     string    `gorm:"column:target"`
+	BodyData   string    `gorm:"column:body_data" json:"body_data"  `
+	CreatedAt  time.Time `gorm:"column:created_at"`
+	UpdatedAt  time.Time `gorm:"column:updated_at"`
+	status     int       `gorm:"column:status"`
+	PushCount  int       `gorm:"column:push_count"`
+	PushLimit  int       `gorm:"column:push_limit"`
+}
+
+type MessageResp struct {
+	ID int `json:"id"`
+}
+
+type MessageReq struct {
+	MsgTypeID   int         `json:"msg_type_id"`
+	ServiceID   int         `form:"service_id" json:"service_id" gorm:"service_id"`
+	SysName     string      `form:"sys_name" json:"sys_name"  gorm:"sys_name"`
+	PastureID   int         `form:"pasture_id" json:"pasture_id" gorm:"pasture_id"`
+	Miniprogram Miniprogram `json:"miniprogram"`
+	Target      []string    `json:"target"`
+	Keys        []string    `json:"keys"`
+	Content     []Tag       `json:"content"`
+}
+type MessageTypeResp struct {
+	RowsAffected int    `json:"rows_affected"`
+	Method       string `json:"method"`
+}
+type Miniprogram struct {
+	AppID    string `json:"appid"`
+	PagePath string `json:"pagepath"`
+}
+type Tag struct {
+	Value string `json:"value"`
+	Color string `json:"color"`
+}
+
+type MessageTypeReq struct {
+	ID int `form:"id" json:"id" gorm:"column:id; primary_key;AUTO_INCREMENT" `
+
+	ServiceID int    `form:"service_id" json:"service_id" gorm:"service_id"`
+	SysName   string `form:"sys_name" json:"sys_name"  gorm:"sys_name"`
+	PastureID int    `form:"pasture_id" json:"pasture_id" gorm:"pasture_id"`
+	TypeName  string `form:"type_name" json:"type_name" gorm:"type_name"`
+
+	RemindType int `form:"remind_type" json:"remind_type" gorm:"remind_type"`
+	DateType   int `form:"date_type" json:"date_type" gorm:"date_type"`
+	CycleType  int `form:"cycle_type" json:"cycle_type" gorm:"cycle_type"`
+
+	DelayTime    int    `form:"delay_time" json:"delay_time" gorm:"delay_time"`
+	PushDate     int    `form:"push_date" json:"push_date" gorm:"push_date"`
+	PushTime     string `form:"push_time" json:"push_time" gorm:"push_time"`
+	IntervalTime int    `form:"interval_time" json:"interval_time" gorm:"interval_time"`
+
+	PushLimit  int    `form:"push_limit" json:"push_limit" gorm:"push_limit"`
+	TemplateID string `form:"template_id" json:"template_id" gorm:"template_id"`
+	Status     int    `form:"status" json:"status" gorm:"status"`
+
+	CreatedAt time.Time `form:"created_at" json:"created_at" gorm:"created_at"`
+	UpdatedAt time.Time `form:"updated_at" json:"updated_at" gorm:"updated_at"`
+}
+
+func (m MessageTypeReq) Validate() (err error) {
+	// if m.SysName == "" || m.PastureID == 0 || m.ServiceID == 0 {
+	// 	err = errors.New("sys_name or pasture_id or service_id is empty")
+	// }
+	return
+}
+
+func (p MessageReq) Validate() error {
+	return nil
 }

+ 18 - 0
apiserver/model/model.go

@@ -1 +1,19 @@
 package model
+
+type SysPastureUrl struct {
+	ID      int    `gorm:"primary_key;AUTO_INCREMENT"`
+	SysName string `form:"sys_name" json:"sys_name"  gorm:"sys_name"`
+	Pasture string `form:"pasture" json:"pasture"  gorm:"pasture"`
+	Url     string `form:"url" json:"url"  gorm:"url"`
+}
+
+type WxMessageReq struct {
+	ToUserName   string `json:"ToUserName"`
+	FromUserName string `json:"FromUserName"`
+	CreateTime   int    `json:"CreateTime"`
+	MsgType      string `json:"MsgType"`
+	MsgId        int    `json:"MsgId"`
+	Event        string `json:"Event"`
+	EventKey     string `json:"EventKey"`
+	Content      string `json:"Content"`
+}

+ 8 - 0
apiserver/model/user.go

@@ -4,3 +4,11 @@ type User struct {
 	Phone  string `gorm:"column:phone"`
 	Openid string `gorm:"column:openid"`
 }
+
+type SysUser struct {
+	Id        string `gorm:"column:id"`
+	Openid    string `gorm:"column:open_id"`
+	User      string `gorm:"column:user"`
+	SysName   string `gorm:"column:sys_name"`
+	PastureId string `gorm:"column:pasture_id"`
+}

+ 19 - 5
apiserver/server/message.go

@@ -1,17 +1,30 @@
 package server
 
 import (
+	"encoding/json"
+
 	"github.com/gin-gonic/gin"
 	"kpt.notice/apiserver/model/http"
 )
 
 //消息存储
 func postMessage(c *gin.Context) {
+	// body, err := ioutil.ReadAll(c.Request.Body)
+	// log.Infof("postMessage body: %s", string(body))
+	// if err != nil {
+	// 	eJSON(c, nil, err)
+	// }
+
 	msgReq := new(http.MessageReq)
 	if !Bind(c, msgReq) {
 		return
 	}
-	resp, err := svc.InsertMessage(msgReq)
+
+	body, err := json.Marshal(msgReq)
+	if err != nil {
+		eJSON(c, nil, err)
+	}
+	resp, err := svc.InsertMessage(msgReq, body)
 	eJSON(c, resp, err)
 }
 
@@ -21,8 +34,9 @@ func postMsgType(c *gin.Context) {
 	if !Bind(c, msgTypeReq) {
 		return
 	}
-	res, err := svc.InsertMessageType(msgTypeReq)
-	eJSON(c, res, err)
+	resp, err := svc.InsertMsgType(msgTypeReq)
+
+	eJSON(c, resp, err)
 }
 
 // get all  message type
@@ -31,7 +45,7 @@ func getMsgType(c *gin.Context) {
 	if !Bind(c, req) {
 		return
 	}
-	res := svc.QueryMsgType(req)
-	eJSON(c, res, nil)
+	res, err := svc.QueryMsgType(req)
+	eJSON(c, res, err)
 
 }

+ 1 - 1
apiserver/server/server.go

@@ -94,7 +94,7 @@ func eJSON(c *gin.Context, data interface{}, err error) {
 	success := true
 	message := "ok"
 	if err != nil {
-		code, success, data, message = 400, false, nil, err.Error()
+		code, success, message = 400, false, err.Error()
 	}
 	resp := http.Response{
 		Code:    code,

+ 0 - 7
apiserver/server/server_test.go

@@ -1,7 +0,0 @@
-package server
-
-import "testing"
-
-func TestXxx(t *testing.T) {
-
-}

+ 10 - 9
apiserver/server/wxoffice.go

@@ -24,10 +24,9 @@ import (
 	获取临时二维码
 */
 func getCode(c *gin.Context) {
-	// sceneID := c.PostForm("scenne_id")
-	sceneID := c.Query("scene_id")
-	log.Infof("sceneID: %s", sceneID)
-	resp, err := service.CreateQRCode(sceneID)
+	sceneStr := c.Query("scene_str")
+	log.Infof("ss getcode p sceneStr===== %s", sceneStr)
+	resp, err := service.CreateQRCode(sceneStr)
 	if err != nil {
 		c.String(400, err.Error())
 	}
@@ -58,15 +57,17 @@ func tokenAuth(c *gin.Context) {
 	接收微信服务器推送的消息
 */
 func wxMessage(c *gin.Context) {
-	// wxmsg := new(http.WxMessage)
-	// if !Bind(c, wxmsg) {
-	// 	return
-	// }
 	body, err := ioutil.ReadAll(c.Request.Body)
 	if err != nil {
+		log.Errorf("wxMessage. %v", err)
 		c.String(400, err.Error())
+		return
 	}
-	output := service.ReceiveMessage(body)
+	log.Infof("se wxMessage { body}====== %s", body)
+	if err != nil {
+		c.String(400, err.Error())
+	}
+	output, err := service.ReceiveMessage(body)
 	if output == nil {
 		c.String(400, "error")
 	} else {

+ 51 - 107
apiserver/service/job.go

@@ -3,130 +3,74 @@ package service
 import (
 	"encoding/json"
 	"fmt"
-	"log"
-	"time"
 
+	"github.com/pkg/errors"
 	"github.com/robfig/cron"
+
+	"kpt.notice/apiserver/model"
 	"kpt.notice/middleware/notice"
+	"kpt.notice/pkg/log"
 )
 
 func JobInit() {
 	c := cron.New()
-	// 公众号消息
-	c.AddFunc("30 * * * * *", SendInstantMsg)
-	c.AddFunc("00 30 09 * * *", SendDelayMsg)
-	c.AddFunc("00 30 09 * * *", SendPeriodMsg)
-	// c.Start()
+	c.AddFunc("30 * * * * *", ReadMsgs)
+	c.Start()
 }
 
-// period message sending to wx
-func SendPeriodMsg() {
-	fmt.Printf("send period msg\n")
-	//query messages from db
-	msgs, err := svc.getMsgByType(3)
-
-	//read  message list
-	for _, val := range msgs {
-		fmt.Printf("message++++++++%#v\n", val)
-
-		data := make(map[string]interface{})
-		json.Unmarshal([]byte(val.MsgContent), &data)
-		targets := make([]string, 10)
-		json.Unmarshal([]byte(val.Target), &targets)
-
-		// fmt.Printf("data1=%v", data)
-		// sli := strings.Split(val.Target, ",")
-		log.Default().Printf("%#v\n", targets)
-		// users, err := svc.QueryOpenid(targets)
-		if err != nil {
-			panic(err)
-		}
-		for _, openid := range targets {
-			data["touser"] = openid
-			log.Default().Printf("data2++++++++++%v\n", data)
-			jsonstr, _ := json.Marshal(data)
-			log.Default().Printf("jsonstr++++++++\n%v", string(jsonstr))
-			resp, tmperr := notice.MsgTemplate(jsonstr)
-			log.Default().Printf("wxresp=========%#v\n", string(resp))
-			if tmperr != nil {
-				log.Default().Printf("wxresp=========%#v\n", string(resp))
-			}
-		}
+func ReadMsgs() {
+	var msgs []model.Message
+	var err error
+	if msgs, err = svc.QueryMsg(); err != nil {
+		log.Errorf("%v", err)
+		return
 	}
-}
-
-// send delay message
-func SendDelayMsg() {
-	fmt.Printf("send delay msg\n")
-	msgs, err := svc.getMsgByType(2)
-	if err != nil {
+	fmt.Println("msg len=", len(msgs))
+	if len(msgs) == 0 {
+		return
 	}
+	// fmt.Printf("%v\n", msgs)
 	for _, val := range msgs {
-		fmt.Printf("message++++++++%#v\n", val)
-
-		data := make(map[string]interface{})
-		json.Unmarshal([]byte(val.MsgContent), &data)
-		targets := make([]string, 10)
-		json.Unmarshal([]byte(val.Target), &targets)
-		log.Default().Printf("%#v\n", targets)
-		// users, err := svc.QueryOpenid(targets)
-		if err != nil {
-			panic(err)
-		}
-		for _, openid := range targets {
-			data["touser"] = openid
-			jsonstr, _ := json.Marshal(data)
-			resp, tmperr := notice.MsgTemplate(jsonstr)
-			log.Default().Printf("wxresp=========%#v\n", string(resp))
-			if tmperr == nil {
-				m := map[string]interface{}{
-					"update_at":  time.Now(),
-					"push_count": val.PushCount + 1,
-				}
-				if val.PushCount+1 == val.PushLimit {
-					m["status"] = 1
-				}
-				svc.UpdateMessage(val.RemindTypeID, val.ID, m)
-			}
-		}
+		e := SendMsg(&val)
+		log.Error(e)
 	}
 }
 
-//instant message sending to wx
-func SendInstantMsg() {
-	fmt.Printf("send instant msg\n")
-	//query messages from db
-	msgs, err := svc.getMsgByType(1)
-	if err != nil {
-	}
-	//read  message list
-	for _, val := range msgs {
-		fmt.Printf("message++++++++%#v\n", val)
+func SendMsg(val *model.Message) (err error) {
+	// if val.SysName != "tmrWatch_test" {
+	// 	return
+	// } else {
+	// 	val.Target = `["oLd1b56PwpexCa0QK4NCkza9TKyY"]`
+	// }
+	data := make(map[string]interface{})
+	targets := make([]string, 10)
 
-		data := make(map[string]interface{})
-		json.Unmarshal([]byte(val.MsgContent), &data)
-		targets := make([]string, 10)
-		json.Unmarshal([]byte(val.Target), &targets)
-
-		// fmt.Printf("data1=%v", data)
-		// sli := strings.Split(val.Target, ",")
-		log.Default().Printf("%#v\n", targets)
-		// users, err := svc.QueryOpenid(targets)
-		if err != nil {
-			panic(err)
-		}
-		for _, openid := range targets {
-			data["touser"] = openid
-			log.Default().Printf("data2++++++++++%v\n", data)
-			jsonstr, _ := json.Marshal(data)
-			log.Default().Printf("jsonstr++++++++\n%v", string(jsonstr))
-			resp, tmperr := notice.MsgTemplate(jsonstr)
-			log.Default().Printf("wxresp=========%#v\n", string(resp))
-			if tmperr == nil {
-				svc.UpdateMessage(val.RemindTypeID, val.ID, map[string]interface{}{
-					"update_at": time.Now(),
-				})
+	if e := json.Unmarshal([]byte(val.MsgContent), &data); e != nil {
+		log.Errorf("%v", err)
+		return
+	}
+	if e := json.Unmarshal([]byte(val.Target), &targets); e != nil {
+		log.Errorf("%v", err)
+		return
+	}
+	for _, openid := range targets {
+		data["touser"] = openid
+		if jsonstr, e := json.Marshal(data); e != nil {
+			err = errors.Wrap(e, "SendMessage{json marshal error of data}=%v")
+			log.Errorf("%v", err)
+			continue
+		} else {
+			if resp, tmperr := notice.MsgTemplate(jsonstr); tmperr != nil {
+				err = errors.Wrap(tmperr, "SendMessage{send message error}==%v")
+				log.Errorf("%v", err)
+			} else {
+				log.Infof("send msg success%v", string(resp))
+				if e := svc.UpdateMessage(val); e != nil {
+					err = errors.Wrap(e, "SendMessage{update message error}=%v")
+					log.Errorf("%v", err)
+				}
 			}
 		}
 	}
+	return
 }

+ 170 - 97
apiserver/service/message.go

@@ -1,144 +1,217 @@
 package service
 
 import (
-	"errors"
+	"time"
 
-	"gorm.io/gorm"
+	"github.com/pkg/errors"
 	"kpt.notice/apiserver/model"
 	"kpt.notice/apiserver/model/http"
 	"kpt.notice/pkg/log"
 	"kpt.notice/pkg/util"
 )
 
-func (svc *Service) UpdateMessage(statics int, id int, val map[string]interface{}) (err error) {
-
-	var res *gorm.DB
-	if statics == 1 {
-		// update update_at
-		res = svc.DB.Model(&model.Message{}).Where("id= ?", id).Updates(val)
-	}
-	if statics == 2 {
-		// update push_count,update_at,status
-		res = svc.DB.Model(&model.Message{}).Where("id= ?", id).Updates(val)
-	}
-	if statics == 3 {
-		// update status
-		res = svc.DB.Model(&model.Message{}).Where("id= ?", id).Updates(val)
-	}
-
-	if res.Error != nil {
-		return res.Error
+func (svc *Service) UpdateMessage(msg *model.Message) (err error) {
+	mtype := &http.MessageTypeReq{
+		SysName:   msg.SysName,
+		PastureID: msg.PastureID,
+		ServiceID: msg.ServiceID,
+	}
+	if mtypes, e := svc.QueryMsgType(mtype); e != nil {
+		err = e
+		return
+	} else if len(mtypes) == 0 {
+		err = errors.New("没有匹配的消息类型")
+		return
+	} else {
+		m := make(map[string]interface{}, 3)
+		if mtypes[0].RemindType == 1 {
+			m["status"] = 1
+		} else if mtypes[0].RemindType == 2 {
+			if mtypes[0].CycleType == 1 || mtypes[0].CycleType == 3 {
+				m["status"] = 1
+			} else {
+				m["updated_at"] = time.Now()
+				m["push_count"] = msg.PushCount + 1
+				if msg.PushCount+1 >= mtypes[0].PushLimit {
+					m["status"] = 1
+				}
+			}
+		} else if mtypes[0].RemindType == 3 {
+			m["push_count"] = msg.PushCount + 1
+			m["updated_at"] = time.Now()
+		}
+		if res := svc.DB.Table("message").Where("id=?", msg.ID).Updates(m); res.Error != nil {
+			err = errors.Wrap(res.Error, "UpdateMessage.update=")
+			log.Errorf("%v", err)
+		}
 	}
 	return
 }
 
-// send  message
-//type statics ,1:instant,
-func (svc *Service) getMsgByType(statics int) (msgs []model.Message, err error) {
-	// instant message
-	var sql string
-	if statics == 1 {
-		sql = `select * from message m join message_type mt on m.msg_type_id = mt.id 
-		where m.status = 1 and mt.remind_type_id = 1 and timestampdiff(second,m.update_at,now())>7200`
-		err = svc.DB.Exec(sql).Find(&msgs).Error
-		// err = svc.DB.Where("msg_type_id =? and status =0 and timestampdiff(second,update_at,now())>7200", 1).Find(&msgs).Error
-	}
-	if statics == 2 {
-		sql = `select m.* from message m join message_type mt on m.msg_type_id = mt.id 
-		where m.status = 1 and mt.remind_type_id = 2 and timestampdiff(hour,m.create_at,now())>=48 
-		and timestampdiff(hour,m.update_at,now())>=24 and m.push_count mt.notice_count`
-	}
-	if statics == 3 {
-		sql = `select * from message m join message_type mt on m.msg_type_id = mt.id 
-		where m.status = 1 and mt.remind_type_id = 3 
-        and    (   mt.push_date=concat('w', weekday(now() ) +1)   mt.push_date=concat('w', day(now() ) +1)  )`
+func (svc *Service) QueryMsg() (msgs []model.Message, err error) {
+
+	sql := `select m.* from message m join message_type mt
+	on m.sys_name=mt.sys_name and m.pasture_id=mt.pasture_id and m.service_id=mt.service_id
+	where m.status=0 and (
+	   mt.remind_type=1 
+	   or
+	   (
+		   mt.remind_type=2 and 
+		   timestampdiff(minute,m.created_at,now())>=mt.delay_time	and
+		   (date_format(now(),'%H:%i')>=mt.push_time or mt.push_time='')	and 
+		   (
+			   cycle_type=1 or cycle_type=3 or
+			   ( 
+				   cycle_type=2 and timestampdiff(minute,m.updated_at,now()) >=mt.interval_time 
+				   and m.push_count<mt.push_limit
+			   )
+		   )
+	   )
+	   or 
+	   (
+		   mt.remind_type=3 and 
+			(
+			   mt.date_type=1 
+			   or (mt.date_type=2 and  weekday(now() ) +1 =mt.push_date)
+			   or (mt.date_type=3 and  (day(now()) =mt.push_date or DAYOFMONTH(now())<mt.push_date))
+			) 
+			and date_format(now(),'%H:%i')>=mt.push_time
+			and 
+			(
+				 push_count=0
+				or 
+				( day(now())> day(mt.updated_at) and push_count>0)
+			)
+	   )
+	) `
+	if err = svc.DB.Raw(sql).Scan(&msgs).Error; err != nil {
+		err = errors.Wrap(err, "queryMsg{query msg exec sql err}==%v")
+		log.Errorf("%v", err)
+		return
 	}
 	return
 }
-func (svc *Service) InsertMessage(msg *http.MessageReq) (resp *http.MessageResp, err error) {
-	log.Error("InsertMessage=============enter")
+func (svc *Service) InsertMessage(msg *http.MessageReq, body []byte) (resp *http.MessageResp, err error) {
 	tmp := make(map[string]interface{})
 	tmp["miniprogram"] = msg.Miniprogram
 	msgType := &http.MessageTypeReq{
-		ID: msg.MsgTypeID,
+		SysName:   msg.SysName,
+		PastureID: msg.PastureID,
+		ServiceID: msg.ServiceID,
+	}
+
+	sysuserList, e := svc.GetSysUser(msg.Target, msg.SysName, msg.PastureID)
+	if err != nil {
+		err = e
+		return
 	}
-	mt := svc.QueryMsgType(msgType)
-	if mt == nil {
-		log.Errorf("InsertMessage=====QueryMsgType====%v", errors.New("没有匹配的模板"))
-		return nil, errors.New("没有匹配的模板")
+	var targetList []string
+	for _, user := range sysuserList {
+		targetList = append(targetList, user.Openid)
+	}
+
+	if mt, e := svc.QueryMsgType(msgType); e != nil {
+		err = e
+		return
+	} else if len(mt) == 0 {
+		err = errors.New("没有匹配的消息类型")
+		return
+	} else {
+		tmp["template_id"] = mt[0].TemplateID
 	}
-	tmp["template_id"] = mt[0].TemplateID
 	data := make(map[string]http.Tag)
 	for i, v := range msg.Keys {
 		data[v] = msg.Content[i]
 	}
 	tmp["data"] = data
 	msgDb := model.Message{
-		Target:       util.MarshalToString(msg.Target),
-		MsgTypeID:    msg.MsgTypeID,
-		RemindTypeID: mt[0].RemindTypeID,
-		MsgContent:   util.MarshalToString(tmp),
+		SysName:    msg.SysName,
+		PastureID:  msg.PastureID,
+		ServiceID:  msg.ServiceID,
+		Target:     util.MarshalToString(targetList),
+		MsgTypeID:  msg.MsgTypeID,
+		MsgContent: util.MarshalToString(tmp),
+		UpdatedAt:  time.Now(),
+		BodyData:   string(body),
 	}
 
-	result := svc.DB.Create(&msgDb)
-	if result.Error != nil {
-		log.Errorf("InsertMessage=====Create%v", result.Error)
-		return nil, result.Error
+	if err = svc.DB.Create(&msgDb).Error; err != nil {
+		err = errors.Wrap(err, "InsertMessage{insert msg}==%v")
+		log.Errorf("%v", err)
+		return
 	}
 	resp = &http.MessageResp{
-		Rows: int(result.RowsAffected),
+		ID: msgDb.ID,
 	}
-	err = result.Error
 	return
 }
 
 // query the id or remind_type of the message  by name
 func (svc *Service) QueryRemindTypeID(name string) (int, error) {
-	m := new(model.MessageType)
-	tx := svc.DB.Where("type_name = ?").First(m)
+	m := new(http.MessageTypeReq)
+	tx := svc.DB.Table("message_type").Where("type_name = ?").First(m)
 	if tx.RowsAffected == 0 {
 		return 0, errors.New("没有匹配的类型")
 	}
 	return m.ID, nil
 }
 
-func (svc *Service) InsertMessageType(req *http.MessageTypeReq) (m *model.MessageType, err error) {
-	// m = &model.MessageType{
-	// 	SysName:      req.SysName,
-	// 	TypeName:     req.TypeName,
-	// 	RemindTypeID: req.RemindTypeID,
-	// 	RemindType:   req.RemindType,
-	// 	PushDate:     req.PushDate,
-	// 	PushTime:     req.PushTime,
-	// 	IntervalTime: req.IntervalTime,
-	// 	PushLimit:    req.PushLimit,
-	// 	TemplateID:   req.TemplateID,
-	// }
-	result := svc.DB.Table("message_type").Create(req)
-	if result.Error != nil {
-		return nil, result.Error
-	}
-	return m, nil
-
+func (svc *Service) InsertMsgType(req *http.MessageTypeReq) (resp *http.MessageTypeResp, err error) {
+	if query, e := svc.QueryMsgType(req); e != nil {
+		err = e
+		return
+	} else {
+		resp = new(http.MessageTypeResp)
+		switch {
+		case len(query) == 0:
+			resp.Method = "insert"
+			if res := svc.DB.Table("message_type").Create(req); res.Error != nil {
+				err = errors.Wrap(res.Error, "InsertMsgType{create msg type===%v}")
+				log.Errorf("%v", err)
+			} else {
+				resp.RowsAffected = int(res.RowsAffected)
+			}
+			break
+		case len(query) > 0:
+			resp.Method = "update"
+			index := map[string]interface{}{
+				"service_id": req.ServiceID,
+				"pasture_id": req.PastureID,
+				"sys_name":   req.SysName,
+			}
+			log.Infof("msg type update index%v", index)
+			req.PastureID = 0
+			req.SysName = ""
+			req.ServiceID = 0
+			log.Infof("msg type update value%v", req)
+			if res := svc.DB.Table("message_type").Where(index).Updates(req); res.Error != nil {
+				err = errors.Wrap(err, "InsertMsgType{update msg type ===%v}")
+				log.Errorf("%v", err)
+			} else {
+				resp.RowsAffected = int(res.RowsAffected)
+			}
+			break
+		}
+	}
+	return
 }
 
-// func (svc *Service) queryMsgType(id int) (m *model.MessageType, err error) {
-// 	if tx.RowsAffected == 0 {
-// 		return nil, errors.New("没有匹配的模板")
-// 	}
-// 	return m, nil
-// }
-func (svc *Service) QueryMsgType(msgTypeReq *http.MessageTypeReq) (m []model.MessageType) {
-	// reqType := map[string]interface{}{
-	// 	"sys_name":   msgTypeReq.SysName,
-	// 	"pasture_id": msgTypeReq.PastureID,
-	// 	"id":         msgTypeReq.ID,
-	// })
-	svc.DB.Table("message_type").Where(msgTypeReq).Find(&m)
-	if svc.DB.Error != nil {
-		log.Errorf("QueryMsgType=====%v", svc.DB.Error)
-		return nil
-	}
-	log.Infof("result====%#v", m)
-	return m
+func (svc *Service) QueryMsgType(req *http.MessageTypeReq) (m []http.MessageTypeReq, err error) {
+	index := map[string]interface{}{}
+
+	if req.ServiceID != 0 {
+		index["service_id"] = req.ServiceID
+	}
+	if req.PastureID != 0 {
+		index["pasture_id"] = req.PastureID
+	}
+	if req.SysName != "" {
+		index["sys_name"] = req.SysName
+	}
+	log.Infof("query msg type===%v", index)
+	if err = svc.DB.Table("message_type").Where(index).Find(&m).Error; err != nil {
+		err = errors.Wrap(err, "QueryMsgType.find=")
+		log.Errorf("%v", err)
+	}
+	return
 }

+ 16 - 87
apiserver/service/send_test.go

@@ -1,102 +1,31 @@
 package service
 
 import (
+	"flag"
 	"testing"
 
 	"kpt.notice/apiserver/config"
 	"kpt.notice/pkg/log"
 )
 
-func TestQueryMsgType(t *testing.T) {
-	svc := testInit()
-	res := svc.QueryMsgType(nil)
-	t.Errorf("%#v", res)
-}
-func TestReceiveMessage(t *testing.T) {
-	config.Init()
-	log.Init(config.Conf.Log)
-	New(config.Conf)
-	log.Error("ReceiveMessage=====================")
-	b := []byte(`<xml>
-		<ToUserName><![CDATA[oLd1b56PwpexCa0QK4NCkza9TKyY]]></ToUserName>
-		<FromUserName><![CDATA[oLd1b56PwpexCa0QK4NCkza9TKyY]]></FromUserName>
-		<CreateTime>123456789</CreateTime>
-		<MsgType><![CDATA[event]]></MsgType>
-		<Event><![CDATA[subscribe]]></Event>
-		<EventKey><![CDATA[qrscene_tmr.shengmu23]]></EventKey>
-		<Ticket><![CDATA[TICKET]]></Ticket>
-	  </xml>`)
+func TestXxx(t *testing.T) {
+	flag.Parse()
 
-	ReceiveMessage(b)
-}
-func testInit() *Service {
-	config.Init()
+	config.Init("")
 	log.Init(config.Conf.Log)
-	return New(config.Conf)
-}
-func TestInsertMessage(t *testing.T) {
-	// svc := testInit()
-	// for i := 1; i < 3; i++ {
-	// 	log.Error("i=======", i)
-	// 	var m []model.MessageType
-	// 	switch {
-	// 	case i == 1:
-	// 		// defer svc.QueryMsgType(1)
-	// 		{
-	// 			if err := recover(); err != nil {
-	// 				log.Errorf("%v", err)
-	// 			} else {
-	// 				m = svc.QueryMsgType(1)
-	// 			}
-	// 		}
-	// 	case i == 2:
-	// 		svc.DB.Where("id = ?", 1).Find(&m)
-	// 	}
-	// 	log.Errorf("%#v", m)
-	// }
-	// file, err := ioutil.ReadFile("/Users/desire/kptdev/msg_push/json/message.json")
-	// if err != nil || len(file) == 0 {
-	// 	panic(err)
-	// }
-
-	// req := new(http.MessageReq)
-	// json.Unmarshal([]byte(file), req)
-	// // log.Errorf("%#v", req)
-	// svc.InsertMessage(req)
-}
-
-func TestCreateQRcode(t *testing.T) {
-	// resp, err := CreateQRCode("")
-	// if err == nil {
-	// 	m := make(map[string]string)
-	// 	json.Unmarshal(resp, &m)
-	// 	// t.Errorf("%#v", m["expire_seconds"])
-	// 	t.Errorf("%v", string(resp))
-	// 	t.Errorf("%v\n", url.QueryEscape(m["ticket"]))
-	// } else {
-	// 	t.Errorf("%#v", err)
-	// }
-}
-func TestGetMsgByType(t *testing.T) {
-	// res, err := getMsgByType(1)
-	// if err != nil {
-	// 	t.Error(err)
-	// }
-	// t.Errorf("%#v", res)
-}
-func TestUpdateStatus(t *testing.T) {
-	// GormDB()
-	// UpdateMessage(20)
-
+	svc := New(config.Conf)
+	re, err := svc.QueryMsg()
+	log.Info(re)
+	t.Log(err)
 }
-func TestMsgSend(t *testing.T) {
-	// GormDB()
-	SendInstantMsg()
 
-}
+func TestSysUser(t *testing.T) {
+	flag.Parse()
 
-func TestQueryOpenid(t *testing.T) {
-	// GormDB()
-	// res, _ := QueryOpenid([]string{"15800900542"})
-	// t.Errorf("%#v", res)
+	config.Init("")
+	log.Init(config.Conf.Log)
+	svc := New(config.Conf)
+	re, err := svc.GetSysUser([]string{"123", "123111"}, "crm", 0)
+	log.Info(re)
+	t.Log(err)
 }

+ 21 - 2
apiserver/service/service.go

@@ -1,23 +1,42 @@
 package service
 
 import (
+	"github.com/pkg/errors"
 	"gorm.io/gorm"
 	"kpt.notice/apiserver/config"
 	"kpt.notice/apiserver/dao"
+	"kpt.notice/apiserver/model"
 )
 
 var svc *Service
 
 type Service struct {
-	DB *gorm.DB
+	DB  *gorm.DB
+	Con *config.Config
 }
 
 func New(c *config.Config) (s *Service) {
 	dao := dao.New(c)
 	s = &Service{
-		DB: dao.DB,
+		DB:  dao.DB,
+		Con: c,
 	}
 	svc = s
 	JobInit()
 	return
 }
+
+// func (svc *Service) QueryDB(tname string, condition map[string]interface{}, result interface{}) (err error) {
+// 	if err = svc.DB.Table(tname).Where(condition).Find(result).Error; err != nil {
+// 		err = errors.Wrap(err, "service.QueryDB")
+// 	}
+// 	return
+// }
+
+func (svc *Service) QuerySysPastureUrl(con *model.SysPastureUrl) (result model.SysPastureUrl, err error) {
+
+	if err = svc.DB.Table("sys_pasture_url").Where(con).First(&result).Error; err != nil {
+		err = errors.Wrap(err, "service.QueryDB")
+	}
+	return
+}

+ 22 - 1
apiserver/service/user.go

@@ -1,6 +1,9 @@
 package service
 
-import "kpt.notice/apiserver/model"
+import (
+	"kpt.notice/apiserver/model"
+	"kpt.notice/pkg/log"
+)
 
 func (svc *Service) InsertUser(phone, openid string) (err error) {
 	sql := `insert user (openid,phone) values(?,?) ON DUPLICATE KEY UPDATE phone=? `
@@ -12,3 +15,21 @@ func (svc *Service) QueryOpenid(phones []string) (users []model.User, err error)
 	err = svc.DB.Where("phone in ?", phones).Find(&users).Error
 	return
 }
+
+func (svc *Service) InsertSysUser(openid, user, sysname, pastureid string) (err error) {
+	sql := ` REPLACE INTO sys_user (open_id,user,sys_name,pasture_id) VALUES(?,?,?,?) `
+	return svc.DB.Exec(sql, openid, user, sysname, pastureid).Error
+}
+
+func (svc *Service) GetSysUser(user []string, sysname string, pastureid int) ([]*model.SysUser, error) {
+	dataList := make([]*model.SysUser, 0)
+	rows := svc.DB.Table("sys_user").Select("open_id")
+	rows.Where(" sys_name = ?", sysname)
+	rows.Where(" pasture_id = ? ", pastureid)
+	err := rows.Where("user in (?) ", user).Find(&dataList).Error
+	if err != nil {
+		log.Errorf("GetSysUser-err:%v", err)
+		return nil, err
+	}
+	return dataList, nil
+}

+ 60 - 47
apiserver/service/wxoffce.go

@@ -2,16 +2,18 @@ package service
 
 import (
 	"encoding/json"
+	"encoding/xml"
 	"strconv"
 	"strings"
 	"time"
 
-	"github.com/fastwego/offiaccount/type/type_event"
+	"github.com/pkg/errors"
+
 	"github.com/fastwego/offiaccount/type/type_message"
+	"kpt.notice/apiserver/model"
 	"kpt.notice/middleware/notice"
 	"kpt.notice/pkg/http"
 	"kpt.notice/pkg/log"
-	"kpt.notice/pkg/util"
 )
 
 // 获取公众号临时二维码
@@ -33,63 +35,82 @@ func CreateQRCode(sceneID string) (body []byte, err error) {
 	}
 	return
 }
-func ReceiveMessage(body []byte) (output *type_message.ReplyMessageText) {
-	log.Error("ReceiveMessage=====================enter")
-	msg, err := notice.ServerAcc.Server.ParseXML(body)
-	if err != nil {
-		log.Errorf("ReceiveMessage==parse xml error: %v", err)
-		output = nil
+func ReceiveMessage(body []byte) (output *type_message.ReplyMessageText, err error) {
+	log.Info()
+	msg := new(model.WxMessageReq)
+	if e := xml.Unmarshal(body, msg); e != nil {
+		err = errors.Wrap(e, "service.ReceiveMessage.Unmarshal")
 	}
-	switch msg.(type) {
-	case type_message.MessageText:
-		p := msg.(type_message.MessageText)
-		output = ReceiveText(&p)
-	case type_event.EventSubscribe:
-		p := msg.(type_event.EventSubscribe)
-		output = ReceiveEvent(&p)
-	default:
-		output = nil
+	switch msg.MsgType {
+	case "text":
+		output, err = ReceiveText(msg)
+	case "event":
+		output, err = ReceiveEvent(msg)
 	}
+	log.Infof("service.ReceiveMessage{WxMessageReq====} %+v", msg)
 	return
 }
 
 /*
 	接收微信服务器推送的事件
 */
-func ReceiveEvent(msg *type_event.EventSubscribe) (output *type_message.ReplyMessageText) {
-	log.Errorf("ReceiveEvent======\n")
-	switch msg.Event.Event {
-	case "subscribe":
-		key := string(type_message.CDATA(msg.EventKey))
-		scene_id := strings.Split(key, "qrscene_")
-		m := map[string]interface{}{
-			"userinfo": scene_id[1],
-			"openid":   msg.FromUserName,
+func ReceiveEvent(msg *model.WxMessageReq) (output *type_message.ReplyMessageText, err error) {
+	if msg.Event == "subscribe" || msg.Event == "SCAN" {
+		key := msg.EventKey
+		if msg.Event == "subscribe" {
+			key = strings.Split(key, "qrscene_")[1]
+		}
+		keys := strings.Split(key, ".")
+		// m := map[string]interface{}{
+		// 	"userinfo": key,
+		// 	"openid":   msg.FromUserName,
+		// }
+		// body, e := json.Marshal(m)
+		// if e != nil {
+		// 	err = errors.Wrap(e, "service.ReceiveEvent.Marshal")
+		// }
+		// var url string
+		// if svc.Con.Env == "dev" {
+		// 	url = "http://kpttest.kptyun.com/userwxopenid/binding"
+		// } else {
+		// 	con := model.SysPastureUrl{
+		// 		SysName: keys[0],
+		// 		Pasture: keys[1],
+		// 	}
+		// res, e := svc.QuerySysPastureUrl(&con)
+		// 	if e != nil {
+		// 		err = errors.Wrap(e, "service.ReceiveEvent.QuerySysPastureUrl{没有匹配的url}=====")
+		// 	}
+		// 	url = res.Url
+		// }
+		// resp, e := http.HttpPost(url, "application/json", string(body))
+		// if e != nil {
+		// 	err = errors.Wrap(e, "service.ReceiveEvent-")
+		// }
+		var err error
+		if len(keys) == 2 {
+			err = svc.InsertSysUser(msg.FromUserName, keys[1], keys[0], "0")
+		} else {
+			err = svc.InsertSysUser(msg.FromUserName, keys[2], keys[0], keys[1])
 		}
-		json.Marshal(m)
-		url := "http://kpttest.kptyun.com/userwxopenid/binding"
-		resp := http.HttpPost(url, "application/json", util.MapToString(m))
+
 		respContent := "公众号绑定系统成功"
-		if resp == nil {
+		if err != nil {
 			respContent = "公众号绑定系统失败,请联系管理员"
 		}
 		output = WxResponse(type_message.CDATA(msg.FromUserName), type_message.CDATA(msg.ToUserName))
 		output.Content = type_message.CDATA(respContent)
-		return
-	default:
-		return nil
 	}
+	return
 }
 
 /*
 	接收微信服务器推送的文本消息
 */
-func ReceiveText(msg *type_message.MessageText) (resp *type_message.ReplyMessageText) {
-	log.Errorf("ReceiveText: %+v", msg)
-	conText := string(type_message.CDATA(msg.Content))
-	openid := string(type_message.CDATA(msg.FromUserName))
-	//update openid of message in db
-	err := svc.InsertUser(conText, openid)
+func ReceiveText(msg *model.WxMessageReq) (resp *type_message.ReplyMessageText, err error) {
+	text := msg.Content
+	openid := msg.FromUserName
+	err = svc.InsertUser(text, openid)
 	var respText string = "手机号绑定成功,欢迎使用"
 	if err != nil {
 		respText = "手机号绑定失败,请重新输入"
@@ -109,11 +130,3 @@ func WxResponse(from, to type_message.CDATA) *type_message.ReplyMessageText {
 		},
 	}
 }
-
-/*
-	发送模板消息
-*/
-// func sendMessage(c *gin.Context) {
-// 	svc.SendInstantMsg()
-
-// }

+ 21 - 0
client/main.go

@@ -0,0 +1,21 @@
+package main
+
+import (
+	"kpt.notice/apiserver/config"
+	"kpt.notice/apiserver/service"
+	"kpt.notice/local"
+	// "../config"
+	// "../local"
+	// "../service"
+)
+
+func main() {
+	LocalInit()
+	local.TestMsg()
+}
+
+func LocalInit() {
+	config.Init("/Users/desire/kptdev/notice/cmd/apiserver/conf.toml")
+	svc := service.New(config.Conf)
+	local.Init(svc)
+}

+ 2 - 1
cmd/apiserver/conf.toml

@@ -1,4 +1,5 @@
-listen = "0.0.0.0:8089"
+listen = "0.0.0.0:80"
+env = "dev"
 [db]
 dsn = "root:kepaiteng!QAZ@tcp(222.73.129.15:31306)/notice?charset=utf8&parseTime=True&loc=Local"
 idle = 5

+ 3 - 0
cmd/apiserver/linux.bat

@@ -0,0 +1,3 @@
+set GOARCH=amd64
+set GOOS=linux
+go build -o notice

+ 3 - 8
cmd/apiserver/main.go

@@ -4,22 +4,17 @@ import (
 	"flag"
 
 	"kpt.notice/apiserver/config"
+	"kpt.notice/apiserver/server"
 	"kpt.notice/pkg/log"
 
-	"kpt.notice/apiserver/server"
 	"kpt.notice/apiserver/service"
 )
 
 func main() {
 	flag.Parse()
-	// init the config
-	config.Init()
-	//log init
+	config.Init("")
 	log.Init(config.Conf.Log)
-	// service components init
 	svc := service.New(config.Conf)
-
-	// server components init
 	server.Init(svc, config.Conf)
-	//job init
+	service.JobInit()
 }

BIN
cmd/apiserver/notice


+ 9 - 0
conf.toml

@@ -0,0 +1,9 @@
+listen = "0.0.0.0:80"
+env = "dev"
+[db]
+dsn = "root:kepaiteng!QAZ@tcp(222.73.129.15:31306)/notice?charset=utf8&parseTime=True&loc=Local"
+idle = 5
+idle_timeout = 3600
+[log]
+stdout = true
+level = "info"

BIN
doc/.DS_Store


+ 69 - 0
doc/bk.json

@@ -0,0 +1,69 @@
+{
+    "pasture_id": 1,
+    "service_id": 1,
+    "sys_name": "cow",
+    "target": [
+        "oLd1b56PwpexCa0QK4NCkza9TKyY"
+    ],
+    "miniprogram": {
+        "appid": "wx9ab2b5b25701da0a",
+        "pagepath": "pages/login/login"
+    },
+    "keys": [
+        "first",
+        "keyword1",
+        "keyword2",
+        "remark"
+    ],
+    "content": [
+        {
+            "color": "#173177",
+            "value": "cowt0802"
+        },
+        {
+            "color": "#173177",
+            "value": "操作编号:1.001\nTMR名称:清底车\n饲料名称:11D\n计划重量(kg):608.70\n实际重量(kg):445.00\n误差值(kg):163.70\n准确率(%):73.11"
+        },
+        {
+            "color": "#173177",
+            "value": "2022-07-04 03:05:20"
+        },
+        {
+            "color": "#173177",
+            "value": "圣牧2"
+        }
+    ]
+}
+
+{
+    "touser":"OPENID",
+    "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
+    "url":"http://weixin.qq.com/download",  
+    "miniprogram":{
+      "appid":"xiaochengxuappid12345",
+      "pagepath":"index?foo=bar"
+    },
+    "client_msg_id":"MSG_000001",
+    "data":{
+            "first": {
+                "value":"恭喜你购买成功!",
+                "color":"#173177"
+            },
+            "keyword1":{
+                "value":"巧克力",
+                "color":"#173177"
+            },
+            "keyword2": {
+                "value":"39.8元",
+                "color":"#173177"
+            },
+            "keyword3": {
+                "value":"2014年9月22日",
+                "color":"#173177"
+            },
+            "remark":{
+                "value":"欢迎再次购买!",
+                "color":"#173177"
+            }
+    }
+}

+ 5 - 0
doc/cow.md

@@ -0,0 +1,5 @@
+https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&tofakeid=oLd1b59FHabNTGHjTNDwTsBY5eHU&token=831774852
+&lang=en_US
+
+
+lh:"oLd1b59FHabNTGHjTNDwTsBY5eHU",

+ 19 - 0
doc/cow.sql

@@ -0,0 +1,19 @@
+-- insert into message_type (sys_name,pasture_id,service_id,remind_type)
+-- values
+-- ('cow',1,1,1);
+-- select distinct id,template_id from message_type;
+-- select * from message_type order by id desc limit 1;
+-- update
+--     message_type
+-- set
+--     type_name ='cowtst',
+--     template_id = 'RLPlaCnqQZt_6s4HZuaFJYbQ9gmTfIYipTYDoKJInY8'
+-- where
+--     id = 36;
+
+-- delete from message where status =0;
+select * from message where status= 0;
+-- select
+--     *
+-- from
+--     message_type;

+ 5 - 0
doc/dreq.sh

@@ -0,0 +1,5 @@
+# http   tmrwatch.cn:80/wx/code?scene_id=tmrwatch.1.1
+# http  'tmrwatch.cn:80/notice/msgtype?sys_name=tmrwatch&pasture_id=453'
+# http https://mp.weixin.qq.com/cgi-bin/showqrcode <../josn/bind.User.json
+# http POST  tmrwatch.cn:80/notice/msgtype  < ../json/type2.json
+http GET  tmrwatch.cn/notice/msgtype?sys_name=tmrWatch_test&pasture_id=1653271339&service_id=8

+ 7 - 5
doc/json/insert_type.json

@@ -1,13 +1,15 @@
 {
     "sys_name":"tmrwatch",
-    "pasture_id":234,
-    "id":3,
+    "pasture_id":413,
+    "service_id":12,
     "type_name":"contact approve",
-    "remind_type_id":0,
-    "remind_type":"立即",
-    "push_date":"w1,w3",
+    "remind_type":1,
+    "date_type":1,
+    "delay_time":0,
+    "push_date":7,
     "push_time":"09:30",
     "interval_time":3600,
+    "cycle_type":2,
     "push_limit":1,
     "template_id":"2",
     "roles_id":"1,2,3",

+ 61 - 24
doc/json/message.json

@@ -1,38 +1,75 @@
 {
-    "msg_type_id": 1,
-    "target": [
-        "15800900542"
-    ],
+    "data": {
+        "first": {
+            "value": "混料搅拌延时异常",
+            "color": "#173177"
+        },
+        "keyword1": {
+            "value": "操作编号:3.005\n牧场:圣牧1\nTMR名称:2号车\n描述:高产2配方3.005\n饲料名称:3Y青贮玉米\n计划重量(kg):3740.39\n实际重量(kg):\u003cnil\u003e\n过程时间:00:06:47",
+            "color": "#173177"
+        },
+        "keyword2": {
+            "value": "00:06:47",
+            "color": "#173177"
+        },
+        "remark": {
+            "value": "无备注",
+            "color": "#173177"
+        }
+    },
     "miniprogram": {
         "appid": "wx9ab2b5b25701da0a",
-        "pagepath": "pages/index/index?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTY1NDIzMDMxMywiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.jKLR74kTy9tXqFH5OwlwK7zTGKvMVbrOecsaJpxbxq8"
+        "pagepath": "pages/login/login"
     },
-    "keys": [
-        "first",
-        "keyword1",
-        "keyword2",
-        "keyword3",
-        "remark"
-    ],
-    "content": [
-        {
-            "value": "混料"
+    "template_id": "RLPlaCnqQZt_6s4HZuaFJYbQ9gmTfIYipTYDoKJInY8",
+    "touser": "oLd1b56PwpexCa0QK4NCkza9TKyY"
+}
+
+{
+    "miniprogram": {
+        "appid": "wx9ab2b5b25701da0a",
+        "pagepath": "pages/login/login"
+    },
+    "template_id": "RLPlaCnqQZt_6s4HZuaFJYbQ9gmTfIYipTYDoKJInY8",
+    "touser": "oLd1b56PwpexCa0QK4NCkza9TKyY",
+    "data": {
+        "first": {
+            "value": "恭喜你购买成功!",
+            "color": "#173177"
         },
-        {
-            "value": "2014年9月22日",
+        "keyword1": {
+            "value": "巧克力",
             "color": "#173177"
         },
-        {
-            "value": "test0601",
+        "keyword2": {
+            "value": "39.8元",
             "color": "#173177"
         },
-        {
-            "value": "tmr名称:23牧场搅拌站\n饲料名称:青木",
+        "keyword3": {
+            "value": "2014年9月22日",
             "color": "#173177"
         },
-         {
-            "value": "remark",
+        "remark": {
+            "value": "欢迎再次购买!",
             "color": "#173177"
         }
-    ]
+    }
+}
+
+{
+    "sys_name": "tmrWatch_test",
+    "pasture_id": 1653271339,
+    "service_id": 8,
+    "type_name": "集团下发配方",
+    "remind_type": 1,
+    "push_date": 0,
+    "push_time": "",
+    "interval_time": 0,
+    "push_limit": 0,
+    "template_id": "RLPlaCnqQZt_6s4HZuaFJYbQ9gmTfIYipTYDoKJInY8",
+    "users_id": "",
+    "date_type": 0,
+    "cycle_type": 1,
+    "delay_time": 0,
+    "status": 0
 }

+ 17 - 0
doc/json/type2.json

@@ -0,0 +1,17 @@
+{
+    "sys_name": "tmrWatch",
+    "pasture_id": 0,
+    "service_id": 1,
+    "type_name": "",
+    "remind_type": 1,
+    "push_date": 0,
+    "push_time": "",
+    "interval_time": 0,
+    "push_limit": 0,
+    "template_id": "BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo",
+    "users_id": "",
+    "date_type": 0,
+    "cycle_type": 1,
+    "delay_time": 0,
+    "status": 0
+}

+ 7 - 0
doc/local.sh

@@ -0,0 +1,7 @@
+http POST :80/notice/message </Users/desire/kptdev/notice/doc/json/msg_t1.json
+# http  POST :80/notice/msgtype </Users/desire/kptdev/notice/doc/json/type2.json
+# http ':80/notice/msgtype?sys_name=tmrwatch&pasture_id=453'
+# http   :80/wx/code?scene_id=tmrwatch.shengmu23.123
+# http https://mp.weixin.qq.com/cgi-bin/showqrcode <../josn/bind.User.json
+# http POST kpttest.kptyun.com/userwxopenid/binding \
+#  openid=oLd1b56PwpexCa0QK4NCkza9TKyY userinfo=tmrwatch.1234.1244

+ 7 - 0
doc/md/maintenance_load.md

@@ -0,0 +1,7 @@
+# maintenance load
+## old
+1. getRepirsList
+{"name":"getRepirsList","page":1,"offset":1,"pagecount":10,"returntype":"Map","parammaps":{"pastureName":"汶上牧场","repairCode":"","eqName":"","eqCode":"","orderStatue":"","SHStatue":"","inputDatetime":"","loginId":"3","menu":"Repair","logindeptId":"20","loginpastureId":"18"}}
+2. getmaintainappearance
+{"name":"getmaintainappearance","page":1,"offset":1,"pagecount":10,"returntype":"Map","parammaps":{"maintainId":81980}}
+- sql:SELECT *, id rowId  FROM maintain_appearance WHERE maintainId=?

+ 10 - 0
doc/md/msg.md

@@ -0,0 +1,10 @@
+template_id:BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo
+- code:http://localhost/wx/code?scene_str=tmrwatch.1654779860.shengmu2.管理员
+- devoce:http://tmrwatch.cn:80/wx/code?scene_str=tmrwatch.1654779860.shengmu2.管理员
+
+-devcode http://tmrwatch.cn/wx/code?scene_str=tmrwatch.shengmu21.1244
+- http://notice.kptyun.com/wx
+- openid:oLd1b56PwpexCa0QK4NCkza9TKyY
+## 小程序
+- "pages/index/index?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTY1NDIzMDMxMywiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.jKLR74kTy9tXqFH5OwlwK7zTGKvMVbrOecsaJpxbxq8"
+- pages/login/login

+ 64 - 0
doc/md/msg_type.md

@@ -0,0 +1,64 @@
+# 消息推送服务类型设置接口
+## path
+- url:  http://tmrwatch.cn:80/notice/msgtype
+- method:   post
+- login: http://kpttest.kptyun.com/#/login
+- account: shengmu23   123456
+- template_id:BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo
+***
+## params
+### common params
+
+||||
+|  ----  | ----  | ---- |
+| sys_name | varchar(64)  | 系统名称 |     
+| pasture_id  |      int(11) | 牧场id |  
+|service_id |        int(11) |             服务id |  
+|type_name |         varchar(64) |         消息类型名 ||称 |  
+|template_id |        varchar(64) |      模板id |  
+|roles_id |           varchar(64) |         角色id |  
+|users_id  |varchar(64) |用户id |  
+|status    |int(11)     |是否启用|
+### dynamic params
+- 立即
+
+||||
+|  ----  | ----  | ---- |
+|remind_type  |       varchar(64)  |         发送方式  |
+|cycle_type  |        int(11)  |             发送机制  |
+|push_limit  |        int(11)  |             推送次数  |
+|interval_time  |     int(11)  |             发送间隔时间  |
+
+- 延时
+
+||||
+| ---- | ---- | ---- |
+| remind_type |       int(11) |             发送方式 |
+| delay_time |        int(11) |             延时时间 |
+| push_time |         varchar(64) |         推送时间 |
+| cycle_type |        int(11) |             发送机制 |
+| push_limit |        int(11) |             推送次数 |
+| interval_time |     int(11) |             发送间隔时间 |
+- 指定周期
+
+||||
+| ---- | ---- | ---- |
+|remind_type | nt(11)|发送方式 |
+|cycle_type |in(11)|发送机制 |
+|date_type |int(11)| 周期类型
+|push_date |int(11)|             推送日期 |
+|push_time |varchar(64)|         推送时间 |
+
+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"`
+    DateType     int64  `json:"date_type"`
+    CycleType    int64  `json:"cycle_type"`
+    DelayTime    int64  `json:"delay_time"`

BIN
doc/md/msg_type.pdf


+ 0 - 0
doc/md/wx.md


+ 39 - 0
doc/msg.json

@@ -0,0 +1,39 @@
+{
+    "pasture_id": 1,
+    "keys": [
+        "first",
+        "keyword1",
+        "keyword2",
+        "remark"
+    ],
+    "service_id": 1,
+    "sys_name": "cow",
+    "miniprogram": {
+        "pagepath": "pages/login/login",
+        "appid": "wx4f58d6ac1e7131b3"
+    },
+    "content": [
+        {
+            "color": "#173177",
+            "value": "奶厅数据"
+        },
+        {
+            "color": "#173177",
+            "value": "传输不及时\n传输率(%):84.11\n应挤奶量:837\n实际挤奶量:704\n"
+        },
+        {
+            "color": "#173177",
+            "value": "2022-07-08 17:14:40"
+        },
+        {
+            "color": "#173177",
+            "value": "海安向阳"
+        }
+    ],
+    "target": [
+        "oLd1b59FHabNTGHjTNDwTsBY5eHU",
+        "oLd1b55kCQSZXj3n6c3HQIia0GyI",
+        "oLd1b59hVlT3MtmYQAY4c_D4IdLs",
+        "oLd1b56PwpexCa0QK4NCkza9TKyY"
+    ]
+}

+ 44 - 0
doc/msgDoc.md

@@ -0,0 +1,44 @@
+# 消息推送服务消息发送接口
+## 地址
+- url:http://tmrwatch.cn/notice/message
+- method:post
+- content_type:json
+## 参数
+- body
+```
+{
+    "sys_name":"tmrwatch",
+    "pasture_id":1647917519,
+    "service_id":1,
+    "target": [
+        "oLd1b56PwpexCa0QK4NCkza9TKyY"
+    ],
+    "miniprogram": {
+        "appid": "wx9ab2b5b25701da0a",
+        "pagepath": "pages/login/login"
+    },
+    "keys": [
+        "first",
+        "keyword1",
+        "keyword2",
+        "remark"
+    ],
+    "content": [
+        {
+            "value": "混料"
+        },
+        {
+            "value": "2014年9月22日",
+            "color": "#173177"
+        },
+        {
+            "value": "tmr名称:23牧场搅拌站\n饲料名称:青木",
+            "color": "#173177"
+        },
+         {
+            "value": "remark",
+            "color": "#173177"
+        }
+    ]
+}
+```

BIN
doc/msgDoc.pdf


+ 64 - 0
doc/msg_type.md

@@ -0,0 +1,64 @@
+# 消息推送服务类型设置接口
+## path
+- url:  http://tmrwatch.cn:80/notice/msgtype
+- method:   post
+- login: http://kpttest.kptyun.com/#/login
+- account: shengmu23   123456
+- template_id:BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo
+***
+## params
+### common params
+
+||||
+|  ----  | ----  | ---- |
+| sys_name | varchar(64)  | 系统名称 |     
+| pasture_id  |      int(11) | 牧场id |  
+|service_id |        int(11) |             服务id |  
+|type_name |         varchar(64) |         消息类型名 ||称 |  
+|template_id |        varchar(64) |      模板id |  
+|roles_id |           varchar(64) |         角色id |  
+|users_id  |varchar(64) |用户id |  
+|status    |int(11)     |是否启用|
+### dynamic params
+- 立即
+
+||||
+|  ----  | ----  | ---- |
+|remind_type  |       varchar(64)  |         发送方式  |
+|cycle_type  |        int(11)  |             发送机制  |
+|push_limit  |        int(11)  |             推送次数  |
+|interval_time  |     int(11)  |             发送间隔时间  |
+
+- 延时
+
+||||
+| ---- | ---- | ---- |
+| remind_type |       int(11) |             发送方式 |
+| delay_time |        int(11) |             延时时间 |
+| push_time |         varchar(64) |         推送时间 |
+| cycle_type |        int(11) |             发送机制 |
+| push_limit |        int(11) |             推送次数 |
+| interval_time |     int(11) |             发送间隔时间 |
+- 指定周期
+
+||||
+| ---- | ---- | ---- |
+|remind_type | nt(11)|发送方式 |
+|cycle_type |in(11)|发送机制 |
+|date_type |int(11)| 周期类型
+|push_date |int(11)|             推送日期 |
+|push_time |varchar(64)|         推送时间 |
+
+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"`
+    DateType     int64  `json:"date_type"`
+    CycleType    int64  `json:"cycle_type"`
+    DelayTime    int64  `json:"delay_time"`

BIN
doc/notice


+ 5 - 0
doc/qt.json

@@ -0,0 +1,5 @@
+{
+    "sys_name": "tmrWatch_test",
+    "pasture_id": 1653271339,
+    "service_id": 8
+}

+ 3 - 0
doc/run_local.sh

@@ -0,0 +1,3 @@
+
+go build -o notice ../cmd/apiserver/main.go
+./notice -conf=../cmd/apiserver/conf.toml

+ 3 - 0
doc/sh/deploy.sh

@@ -0,0 +1,3 @@
+GOOS=linux go build /Users/desire/kptdev/notice/cmd/apiserver/main.go
+scp -r  main root@210.16.189.72:/usr/local/notice	
+ssh root@210.16.189.72	bash /usr/local/notice/deploy.sh

+ 0 - 3
doc/sh/devS.sh

@@ -1,3 +0,0 @@
-# http   tmrwatch.cn:8089/wx/code?scene_id=tmrwatch.shengmu23.中文
-http  'tmrwatch.cn:8089/notice/msgtype?sys_name=tmrwatch&pasture_id=3&id=1'
-# http https://mp.weixin.qq.com/cgi-bin/showqrcode <../josn/bind.User.json

+ 0 - 3
doc/sh/local.sh

@@ -1,3 +0,0 @@
-# http   :8089/wx/code?scene_id=tmrwatch.shengmu23.中文
-http ':8089/notice/msgtype?sys_name=tmrwatch&pasture_id=3&id=1'
-# http https://mp.weixin.qq.com/cgi-bin/showqrcode <../josn/bind.User.json

BIN
cmd/apiserver/main → doc/sh/main


BIN
doc/sh/notice


+ 36 - 0
doc/sql/apisql.sql

@@ -0,0 +1,36 @@
+-- create table notice.apisql(
+--     id int(11) not null auto_increment,
+--     sqlname varchar(255) not null,
+--     sqltext text not null,
+--     primary key(id)
+-- ) ENGINE = InnoDB DEFAULT CHARSET = utf8 comment 'sql语句';
+
+update apisql set 
+sqltext="select m.* from message m join message_type mt
+	 on m.sys_name=mt.sys_name and m.pasture_id=mt.pasture_id and m.service_id=mt.service_id
+	 where m.status=0 and (
+		mt.remind_type=1 
+		or
+		(
+			mt.remind_type=2 and 
+			timestampdiff(minute,m.created_at,now())>mt.delay_time	and
+			date_format(now(),'%H:%i')>mt.push_time	and 
+			(
+				cycle_type=1 or cycle_type=3 or
+				( 
+					cycle_type=2 and timestampdiff(minute,m.updated_at,now()) >mt.interval_time 
+					and m.push_count<mt.push_limit
+				)
+			)
+		)
+		or 
+		(
+			mt.remind_type=3 and 
+			 (
+				mt.date_type=1 
+				or (mt.date_type=2 and  weekday(now() ) +1 =mt.push_date)
+				or (mt.date_type=3 and  (day(now()) =mt.push_date or DAYOFMONTH(now())<mt.push_date))
+			 ) 
+			 and date_format(now(),'%H:%i')>mt.push_time
+		)
+	 ) "

+ 23 - 0
doc/sql/dict.sql

@@ -0,0 +1,23 @@
+-- -- drop table if exists dictlist;
+-- create table dictlist(
+--     id int(11) not null auto_increment,
+--     type_name varchar(50) not null,  
+--     type_id int(11) not null,
+--     value varchar(50) not null,
+--     primary key (id),
+--     index `dict_name` (type_name)
+-- )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '字典';
+
+insert into dictlist (type_name,type_id,value) values 
+-- ('remind_type','1','立即'),
+-- ('remind_type','2','延时'),
+-- ('remind_type','3','循环'),
+('cycle_type','1','单次'),
+('cycle_type','2','多次'),
+('cycle_type','3','循环至任务结束'),
+('date_type','1','每日'),
+('date_type','2','每周'),
+('date_type','3','每月');
+
+
+

+ 6 - 0
doc/sql/insert.sql

@@ -0,0 +1,6 @@
+
+insert into sys_pasture_url  (sys_name,pasture,url,pasture_name)
+values ('tmrwatch_test','1653271339','http://kpttest.kptyun.com/userwxopenid/binding','测试');
+
+insert  message_type (sys_name,pasture_id,service_id,type_name,remind_type,template_id)values ('tmrwatch_test',1653271339,2,'测试',1,'RLPlaCnqQZt_6s4HZuaFJYbQ9gmTfIYipTYDoKJInY8');
+insert  message_type (sys_name,pasture_id,service_id,type_name,remind_type,template_id)values ('tmrwatch_test',1653271339,3,'测试',1,'RLPlaCnqQZt_6s4HZuaFJYbQ9gmTfIYipTYDoKJInY8');

+ 28 - 0
doc/sql/log.sql

@@ -0,0 +1,28 @@
+select * from message m join message_type mt
+	 on m.sys_name=mt.sys_name and m.pasture_id=mt.pasture_id and m.service_id=mt.service_id
+	 where m.status=0 and (
+		mt.remind_type=1
+		or
+		(
+			mt.remind_type=2 and
+			timestampdiff(minute,m.created_at,now())>mt.delay_time	and
+			date_format(now(),'%H:%i')>mt.push_time	and
+			(
+				cycle_type=1 or cycle_type=3 or
+				(
+					cycle_type=2 and timestampdiff(minute,m.updated_at,now()) >mt.interval_time
+					and m.push_count<mt.push_limit
+				)
+			)
+		)
+		or
+		(
+			mt.remind_type=3 and
+			 (
+				mt.date_type=1
+				or (mt.date_type=2 and  weekday(now() ) +1 =mt.push_date)
+				or (mt.date_type=3 and  (day(now()) =mt.push_date or DAYOFMONTH(now())<mt.push_date))
+			 )
+			 and date_format(now(),'%H:%i')>mt.push_time
+		)
+	 )

+ 31 - 25
doc/sql/message.sql

@@ -1,34 +1,40 @@
 
 drop table if exists `notice`.`message`;
 create table `notice`.`message`(
-    `id` int(11) not null auto_increment,
+    `id` int(11) not null auto_increment default '0',
+    -- `sys_name` varchar(255) not null,
+    -- `pasture_id` int(11) not null,
+    -- `service_id` int(11) not null,
+    `msg_type_id` int(11) not null default '0',
+    `remind_type` int(11) not null default 0 comment '发送方式',
+    `date_type` int(11) not null default 0 comment '循环类型',
+    `cycle_type` int(11) not null default 0 comment '发送机制',
+
+    `push_date` int(11) not null default 0  comment '推送日期',
+    `push_time` varchar(64) not null default '' comment '推送时间',
+    `delay_time` int(11) not null default 0 comment '延迟时间',
+    `interval_time` int(11) not null default 0 comment '提醒间隔时间',
+    
+    `push_limit` int(11) not null default 0  comment '推送限制次数',
+    `template_id` varchar(64) not null default '' comment '模板id',
+
+
     `msg_type_id` int(11) not null default 0,
+    `remind_type` int(11) not null default 0,
+
     `msg_content` text not null ,
-    `target` varchar(64) not null default '',
+    `target` text not null default '',
     `push_count` int(11) not null default 0,
-    `push_limit` int(11) not null default 0,
+
+    -- `push_limit` int(11) not null default 0,
+
     `status` int(11) not null default 0,
-    `create_at` DATETIME not null default CURRENT_TIMESTAMP,
-    `update_at` DATETIME not null ON UPDATE CURRENT_TIMESTAMP ,
+    `created_at` DATETIME not null default CURRENT_TIMESTAMP,
+    `updated_at` DATETIME not null ON UPDATE CURRENT_TIMESTAMP ,
     primary key(`id`)
 )ENGINE=InnoDB DEFAULT CHARSET=utf8 comment '消息';
--- create table `user`(
---     `id` int(11) not null auto_increment,
---     openid varchar(64) not null default '',
---     phone varchar(64) not null default '',
---     primary key (`id`)
--- )ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='用户表';
-
-
-drop table if exists `msg_push`.`message`;
-create table `msg_push`.`message` (
-    `id` int(11) not null auto_increment,
-    `sys_name` varchar(64) not null default '',
-    `remind_type` varchar(64) not null default '',
-    `target` varchar(64) not null default '',
-    `content` text not null ,
-    `status` int(11) not null default 0,
-    `create_at` DATETIME not null default CURRENT_TIMESTAMP,
-    `update_at` DATETIME not null ON UPDATE CURRENT_TIMESTAMP ,
-     primary key(`id`)
-)
+
+alter table message 
+add  `body_data` text not null default '';
+
+-- drop column if exists `body_data`;

+ 34 - 0
doc/sql/mq.sql

@@ -0,0 +1,34 @@
+select m.* from message m join message_type mt
+	on m.sys_name=mt.sys_name and m.pasture_id=mt.pasture_id and m.service_id=mt.service_id
+	where m.status=0 and (
+	   mt.remind_type=1 
+	   or
+	   (
+		   mt.remind_type=2 and 
+		   timestampdiff(minute,m.created_at,now())>=mt.delay_time	and
+		   (date_format(now(),'%H:%i')>=mt.push_time or mt.push_time='')	and 
+		   (
+			   cycle_type=1 or cycle_type=3 or
+			   ( 
+				   cycle_type=2 and timestampdiff(minute,m.updated_at,now()) >=mt.interval_time 
+				   and m.push_count<mt.push_limit
+			   )
+		   )
+	   )
+	   or 
+	   (
+		   mt.remind_type=3 and 
+			(
+			   mt.date_type=1 
+			   or (mt.date_type=2 and  weekday(now() ) +1 =mt.push_date)
+			   or (mt.date_type=3 and  (day(now()) =mt.push_date or DAYOFMONTH(now())<mt.push_date))
+			) 
+			and date_format(now(),'%H:%i')>=mt.push_time
+			and 
+			(
+				 push_count=0
+				or 
+				( day(now())> day(mt.updated_at) and push_count>0)
+			)
+	   )
+	) 

+ 46 - 0
doc/sql/msg_query.sql

@@ -0,0 +1,46 @@
+select 
+-- m.*
+m.id,
+m.created_at,
+m.updated_at,
+timestampdiff(minute,m.updated_at,now())  dif,
+mt.interval_time ,
+date_format(now(),'%H:%i') now_time,
+push_time
+from message m join message_type mt
+	on m.sys_name=mt.sys_name and m.pasture_id=mt.pasture_id and m.service_id=mt.service_id
+	where
+	--  m.status=0
+	m.id  =1407
+	 and (
+	   mt.remind_type=1 
+	   or
+	   (
+		   mt.remind_type=2 and 
+		   timestampdiff(minute,m.created_at,now())>=mt.delay_time	and
+		   (date_format(now(),'%H:%i')>=mt.push_time or mt.push_time='')	and 
+		   (
+			   cycle_type=1 or cycle_type=3 or
+			   ( 
+				   cycle_type=2 and timestampdiff(minute,m.updated_at,now()) >=mt.interval_time 
+				   and m.push_count<mt.push_limit
+			   )
+		   )
+	   )
+	   or 
+	   (
+		   mt.remind_type=3 and 
+			(
+			   mt.date_type=1 
+			   or (mt.date_type=2 and  weekday(now() ) +1 =mt.push_date)
+			   or (mt.date_type=3 and  (day(now()) =mt.push_date or DAYOFMONTH(now())<mt.push_date))
+			) 
+			and date_format(now(),'%H:%i')>=mt.push_time
+			and 
+			(
+				 push_count=0
+				or 
+				( day(now())> day(mt.updated_at) and push_count>0)
+			)
+	   )
+	) 

+ 61 - 25
doc/sql/msg_type.sql

@@ -1,23 +1,59 @@
 -- -- create database if not exists `notice` default character set utf8 collate utf8_general_ci;
--- DROP TABLE IF EXISTS `notice`.`message_type`;
--- create table `notice`.`message_type`(
---     `sys_name` varchar(64) not null default '',
---     `id` int(11) unsigned not null ,
---     `pasture_id` int(11) not null default 0,
---     `type_name` varchar(64) not null default '',
---     `remind_type_id` int(11) unsigned not null default 0,
---     `remind_type` varchar(64) not null default '',
---     `push_date` varchar(64) not null default '',
---     `push_time` varchar(64) not null default '' comment '推送时间,different type have different format',
---     `interval_time` int(11) not null default 0 comment '提醒间隔时间,单位hour',
---     `push_limit` int(11) not null default 0 ,
---     `template_id` varchar(64) not null default '',
---     `roles_id` varchar(64) not null default '',
---     `users_id` varchar(64) not null default '',
---     primary key(`id`,`sys_name`,`pasture_id`),
---     index `u_msg_type` (`remind_type`)
--- )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '消息类型';
--- alter table msg_type 
+DROP TABLE IF EXISTS `notice`.`message_type`;
+create table `notice`.`message_type`(
+    `id` int(11) NOT NULL AUTO_INCREMENT comment '主键id',
+    
+    `sys_name` varchar(64) not null default '' comment '系统名称',
+    `pasture_id` int(11) not null default 0 comment '牧场id',
+    `service_id` int(11) unsigned not null 0 comment '服务id',
+    `type_name` varchar(64) not null default '' comment '消息类型名称',
+
+    `remind_type` int(11) not null default 0 comment '发送方式',
+    `date_type` int(11) not null default 0 comment '循环类型',
+    `cycle_type` int(11) not null default 0 comment '发送机制',
+
+    `push_date` int(11) not null default 0  comment '推送日期',
+    `push_time` varchar(64) not null default '' comment '推送时间',
+    `delay_time` int(11) not null default 0 comment '延迟时间',
+    `interval_time` int(11) not null default 0 comment '提醒间隔时间',
+    
+    `push_limit` int(11) not null default 0  comment '推送限制次数',
+    `template_id` varchar(64) not null default '' comment '模板id',
+    `status` int(11) not null default 0 comment '状态',
+
+    `created_at` DATETIME not null default CURRENT_TIMESTAMP,
+     `updated_at` DATETIME not null ON UPDATE CURRENT_TIMESTAMP ,
+    primary key (`id`),
+    UNIQUE index  (`service_id`,`sys_name`,`pasture_id`),
+    index  (`remind_type`),
+    index (`date_type`),
+    index (`cycle_type`)
+)ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '消息类型';
+-- show index from message_type;
+-- describe message_type;
+
+-- update message_type set remind_type =0;
+alter table message_type  
+-- drop column delay_time,
+-- add `delay_time` int(11) not null default 0 comment '延迟时间' after push_time ;
+-- drop column create_at,
+-- drop column update_at,
+-- add status int(11) not null default 0 comment '状态';
+--  add `created_at` DATETIME not null default CURRENT_TIMESTAMP,
+--  add    `updated_at` DATETIME not null ON UPDATE CURRENT_TIMESTAMP ;
+-- drop column remind_type_id,
+-- modify column remind_type int(11) unsigned not null default 0 comment '提醒类型id';
+-- modify  date_type int(11) not null default 0,
+-- modify cycle_type int(11) not null default 0;
+--  drop column cycle_type ,
+-- add column cycle_type varchar(64) not null default '' AFTER interval_time;
+-- modify column `id` int(11) NOT NULL AUTO_INCREMENT before sys_name,
+-- modify column service_id int(11) unsigned not null default 0 before type_name,
+-- add unique key (`service_id`,`sys_name`,`pasture_id`);
+-- add primary key (`id`),
+-- modify push_date int(11) not null default 0;
+-- modify column `id` int(11) NOT NULL 
+-- modify column `id` int(11) NOT NULL AUTO_INCREMENT;
 -- modify column `remind_type_id` int(11) unsigned not null default '0' FIRST remind_type;
 -- modify column `remind_type_id` int(11)  FIRST remind_type
 -- drop index u_msg_type on message_type
@@ -26,11 +62,11 @@
 -- -- add push_count int(11) unsigned not null default '0' AFTER `status`;
 -- add remind_type_id int(11) unsigned not null default '0' AFTER `status`;
 
-insert into message_type
-(sys_name,id,pasture_id,type_name,remind_type_id,remind_type,push_date,push_time,interval_time,push_limit,template_id,roles_id,users_id)
-values  
-    -- ('tmrwatch',1,1,'合同金额超期未收',3,'指定周期','w1,w3,w5','9:30','0',3,'BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo','1,2,3','1,2,3'),
-    ('tmrwatch',2,3,'合同金额超期未收',3,'指定周期','w1,w3,w5','9:30','0',3,'BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo','1,2,3','1,2,3'),
-    ('tmrwatch',1,3,'合同金额超期未收',3,'指定周期','w1,w3,w5','9:30','0',3,'BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo','1,2,3','1,2,3');
+-- insert into message_type
+-- (sys_name,id,pasture_id,type_name,remind_type_id,remind_type,push_date,push_time,interval_time,push_limit,template_id,roles_id,users_id)
+-- values  
+--     -- ('tmrwatch',1,1,'合同金额超期未收',3,'指定周期','w1,w3,w5','9:30','0',3,'BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo','1,2,3','1,2,3'),
+--     ('tmrwatch',2,3,'合同金额超期未收',3,'指定周期','w1,w3,w5','9:30','0',3,'BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo','1,2,3','1,2,3'),
+--     ('tmrwatch',1,3,'合同金额超期未收',3,'指定周期','w1,w3,w5','9:30','0',3,'BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo','1,2,3','1,2,3');
     -- ('tmrwatch','合同审批',1,'立即','0','0','2','0','BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo'),
     -- ('tmrwatch','客户回访未完成',2,'延时','48','9:30','24',3,'BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo'),

+ 41 - 0
doc/sql/pas_url.sql

@@ -0,0 +1,41 @@
+-- drop table if exists `notice`.`sys_pasture_url`;
+-- create table notice.sys_pasture_url(
+--     id int(11) not null auto_increment,
+--     sys_name varchar(50) not null,
+--     pasture varchar(50) not null,
+--     url varchar(255) not null,
+--     pasture_name varchar(50) not null,
+--     primary key (id),
+--     unique key (sys_name,pasture,url)
+-- )ENGINE=InnoDB DEFAULT CHARSET=utf8 comment '系统地址表';
+
+-- delete from notice.sys_pasture_url;
+insert into notice.sys_pasture_url(sys_name,pasture,url,pasture_name) 
+values
+('tmrwatch','1653271339',	'http://bmsm1.kptyun.com/', '1牧'),
+('tmrwatch','1654779860',	'http://bmsm2.kptyun.com/', '2牧'),
+('tmrwatch','1652667664',	'http://bmsm3.kptyun.com/', '3牧'),
+('tmrwatch','1653617396',	'http://bmsm5.kptyun.com/', '5牧'),
+('tmrwatch','1654571442',	'http://bmsm7.kptyun.com/', '7牧'),
+('tmrwatch','1648089292',	'http://bmsm8.kptyun.com/', '8牧'),
+('tmrwatch','1654653702',	'http://bmsm9.kptyun.com/', '9牧'),
+('tmrwatch','1653548321',	'http://bmsm10.kptyun.com/', '10牧'),
+('tmrwatch','1652842829',	'http://bmsm11.kptyun.com/', '11牧'),
+('tmrwatch','1652930544',	'http://bmsm12.kptyun.com/', '12牧'),
+('tmrwatch','1653188966',	'http://bmsm13.kptyun.com/', '13牧'),
+('tmrwatch','1653878925',	'http://bmsm15.kptyun.com/', '15牧'),
+('tmrwatch','1653018665',	'http://bmsm16.kptyun.com/', '16牧'),
+('tmrwatch','1653705875',	'http://bmsm17.kptyun.com/', '17牧'),
+('tmrwatch','1654866092',	'http://bmsm18.kptyun.com/', '19牧'),
+('tmrwatch','1654139897',	'http://bmsm20.kptyun.com/', '20牧'),
+('tmrwatch','1653965525',	'http://bmsm21.kptyun.com/', '21牧'),
+('tmrwatch','1647917519',	'http://bmsm23.kptyun.com/', '23牧'),
+('tmrwatch','1652758908',	'http://bmsm25.kptyun.com/', '25牧'),
+('tmrwatch','1654506056',	'http://bmsm27.kptyun.com/', '27牧');
+
+
+
+-- ('tmrwatch','shengmu21','http://kpttest.kptyun.com/userwxopenid/binding');
+-- insert into sys_pasture_url (sys_name,pasture,url) 
+-- select sys_name,"shengmu1",url from sys_pasture_url where id =1;
+-- update sys_pasture_url set pasture ='1653271339'

+ 1 - 10
doc/sql/query.sql

@@ -1,10 +1 @@
--- select m.* from message m join message_type mt on m.msg_type_id = mt.id 
--- 		where m.status = 1 and mt.remind_type_id = 2 and timestampdiff(hour,m.create_at,now())>=48 
--- 		and timestampdiff(hour,m.update_at,now())>=24 and m.push_count < mt.notice_count;
-select * from message m join message_type mt on m.msg_type_id = mt.id 
-		where m.status = 1 and mt.remind_type_id = 3 
-        and    (  find_in_set( mt.push_date,concat('w', weekday(now() ) +1) )or
-        find_in_set(  mt.push_date,concat('w', day(now() ) +1)  ))
-        
-
-
+select * from message where sys_name ='tmrwatch_test';

+ 140 - 0
doc/sql/repire/repire.sql

@@ -0,0 +1,140 @@
+ SELECT
+IFNULL(bpa1.cou,0) laidcou,
+  eq.`specification`,
+ DATE_FORMAT(mt.`chargeDate`,'%Y-%m-%d %H:%i:%s') chargeDate,
+  mt.scores,
+  mt.`chargeId`,
+  mt.`checkResult`,
+  mt.`dealTime`,
+  eq.`departmentId`,
+  mt.`details`,
+  mt.`disposeId`,
+  mt.`eqClassId`,
+  mt.`eqCode`,
+  mt.`eqId`,
+  mt.`eqName`,
+  mt.`id`,
+  mt.`orderStatue`,
+  DATE_FORMAT(mt.`orderTime`, '%Y-%m-%d %H:%i:%s') orderTime,
+  mt.`pastureId`,
+  mt.`phenomenId`,
+  mt.`pickId`,
+  mt.`positionId`,
+  mt.`repairCode`,
+  mt.`repairDept`,
+  mt.`repairNote`,
+  mt.`requesterId`,
+  DATE_FORMAT(mt.`requestTime`,'%Y-%m-%d %H:%i:%s') requestTime,
+  DATE_FORMAT(mt.`stopTime`,'%Y-%m-%d %H:%i:%s') stopTime,
+  p.`name` pastureName,
+  IF(bpa.cou  IS NULL,'未领用','已领用') LYStatue,
+  IF(rf.cou  IS NULL,'未录入','已录入') LRStatue,
+  mt.flowCompeleted SHStatue,
+  d.`name` departmentName,
+  d1.`name` repairDeptName,
+  e.`empname` requesterName,
+  e1.`empname` pickName,
+ em2.`empname`  useChargePerson,
+    em3.`empname`  chargePerson,
+		em4.`empname` shutdownPerson,
+		mt.shutdownReason,
+		DATE_FORMAT(   mt.shutdownDate,'%Y-%m-%d %H:%i:%s') shutdownDate,
+ DATE_FORMAT(   mt.useChargeDate,'%Y-%m-%d %H:%i:%s') useChargeDate,
+
+mt.workflowNote
+FROM
+  maintain mt
+  INNER JOIN pasture p
+    ON p.`id` = mt.`pastureId`
+  INNER JOIN department d1
+    ON d1.`id` = mt.`repairDept`
+  INNER JOIN emp e
+    ON e.`id` = mt.`requesterId`
+  LEFT JOIN emp e1
+    ON e1.`id` = mt.`pickId`
+  LEFT JOIN emp em2
+      ON em2.id = mt.useChargeId
+ LEFT JOIN emp em3
+      ON em3.id = mt.chargeId
+	LEFT JOIN emp em4
+			ON em4.id = mt.shutdownPerson
+
+  INNER JOIN equipment eq
+    ON eq.`id` = mt.`eqId`
+  LEFT JOIN department d
+    ON d.`id` = eq.`departmentId`
+  LEFT JOIN (SELECT RUCode,COUNT(id)cou FROM  bigpartapply GROUP BY  RUCode ) bpa
+    ON bpa.`RUCode` = mt.`repairCode`
+  LEFT JOIN (SELECT repairCode,COUNT(id)cou FROM  refuse GROUP BY  repairCode)rf
+    ON rf.`repairCode` = mt.`repairCode`
+ LEFT JOIN (SELECT RUCode,COUNT(id)cou FROM  bigpartapply WHERE statue =0 AND (SHStatus IN (2,3,5,7,9))  GROUP BY  RUCode ) bpa1
+    ON bpa1.`RUCode` = mt.`repairCode`
+WHERE
+
+
+(((mt.requesterId= ? OR mt.pickId =?) OR IFNULL((SELECT MAX(r.`datarole`) FROM `user` u
+   LEFT JOIN user_role ur
+   ON ur.`user_id`= u.`id`
+   LEFT JOIN role r
+   ON r.`id` = ur.`role_id`
+   LEFT JOIN role_menu rm
+   ON r.`id` = rm.`role_id`
+   LEFT JOIN menu m
+   ON m.`id` = rm.`menu_id`
+   WHERE u.`empid` = ? AND m.`path`=? ),0) IN (1,2,3))
+
+   AND (eq.departmentId IN (SELECT id FROM department WHERE pastureId =? AND id IN (
+
+SELECT  SUBSTRING_INDEX(SUBSTRING_INDEX(ss.www,',',b.seq+1),',',-1) AS 'ids'
+				 FROM
+					(SELECT @i:=1 i,IFNULL((SELECT GROUP_CONCAT(department_id)SSSS
+				 FROM role_department WHERE role_id = (SELECT  MAX(r.id) FROM `user` u
+					 LEFT JOIN user_role ur
+					 ON ur.`user_id`= u.`id`
+					 LEFT JOIN role r
+					 ON r.`id` = ur.`role_id`
+					 LEFT JOIN role_menu rm
+					 ON r.`id` = rm.`role_id`
+					 LEFT JOIN role_department rd
+					 ON r.`id` = rd.`role_id`
+					 LEFT JOIN menu m
+					 ON m.`id` = rm.`menu_id`
+					 WHERE u.`empid` = ? AND m.`path`=?) AND department_id IN (SELECT id FROM department WHERE pastureId = ?)),?) www) ss
+					 JOIN   sequence b ON b.seq < (LENGTH(ss.www) - LENGTH(REPLACE(ss.www,',',''))+1)
+					WHERE ss.i =1
+					GROUP BY ids
+					)
+	 )
+
+	 OR mt.pickId =? OR mt.requesterId= ? OR IFNULL((SELECT MAX(r.`datarole`) FROM `user` u
+   LEFT JOIN user_role ur
+   ON ur.`user_id`= u.`id`
+   LEFT JOIN role r
+   ON r.`id` = ur.`role_id`
+   LEFT JOIN role_menu rm
+   ON r.`id` = rm.`role_id`
+   LEFT JOIN menu m
+   ON m.`id` = rm.`menu_id`
+   WHERE u.`empid` =? AND m.`path`=? ),0) IN (2,3))
+   AND (p.id= ? OR IFNULL((SELECT  MAX(r.`datarole`) FROM `user` u
+   LEFT JOIN user_role ur
+   ON ur.`user_id`= u.`id`
+   LEFT JOIN role r
+   ON r.`id` = ur.`role_id`
+   LEFT JOIN role_menu rm
+   ON r.`id` = rm.`role_id`
+   LEFT JOIN menu m
+   ON m.`id` = rm.`menu_id`
+   WHERE u.`empid` = ? AND m.`path`=? ),0) = 3)) AND
+(p.`name`=? OR ?='现代牧业') AND (mt.repairCode LIKE CONCAT('%',?,'%')OR ?='')
+AND (mt.`eqName` LIKE CONCAT('%',?,'%')OR ?='')
+AND (mt.`eqCode` LIKE CONCAT('%',?,'%')OR ?='')
+AND (mt.`orderStatue` =? OR ?='')
+AND (DATE_FORMAT(mt.`requestTime`, '%Y-%m-%d')>=? AND DATE_FORMAT(mt.`requestTime`, '%Y-%m-%d')<=?  OR ?='')
+AND (
+   IF (?=0,mt.flowCompeleted IN (2,3) ,
+        IF(?=1,mt.flowCompeleted=5,mt.flowCompeleted IN (4,6))
+   )
+    OR ? = ''
+  )
+ORDER BY mt.`id` DESC

+ 7 - 0
doc/sql/test.sql

@@ -0,0 +1,7 @@
+-- select push_time from message_type;
+-- update message_type set push_time ='11:59';
+-- update message set status =0 where id =1404;
+select id from message where id=1407;
+-- select remind_type,delay_time,push_time,cycle_type from message_type;
+-- update message_type set 
+-- remind_type=2,delay_time=3,push_time='14:05',cycle_type=1 ;

+ 1 - 0
doc/sql/up.sql

@@ -0,0 +1 @@
+update   message set status=0 where sys_name ='tmrwatch_test';

+ 0 - 18
go.mod

@@ -13,24 +13,6 @@ require (
 )
 
 require (
-	github.com/faabiosr/cachego v0.15.0 // indirect
-	github.com/gin-contrib/sse v0.1.0 // indirect
-	github.com/go-playground/locales v0.13.0 // indirect
-	github.com/go-playground/universal-translator v0.17.0 // indirect
-	github.com/go-playground/validator/v10 v10.4.1 // indirect
-	github.com/go-sql-driver/mysql v1.6.0 // indirect
-	github.com/golang/protobuf v1.4.2 // indirect
-	github.com/jinzhu/inflection v1.0.0 // indirect
-	github.com/jinzhu/now v1.1.4 // indirect
-	github.com/json-iterator/go v1.1.9 // indirect
-	github.com/leodido/go-urn v1.2.0 // indirect
-	github.com/mattn/go-isatty v0.0.12 // indirect
-	github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
-	github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect
 	github.com/stretchr/testify v1.7.0 // indirect
-	github.com/ugorji/go/codec v1.1.7 // indirect
-	golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
 	golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac // indirect
-	google.golang.org/protobuf v1.23.0 // indirect
-	gopkg.in/yaml.v2 v2.3.0 // indirect
 )

+ 73 - 0
local/local.go

@@ -0,0 +1,73 @@
+package local
+
+import (
+	"fmt"
+	"time"
+
+	"kpt.notice/apiserver/model"
+	"kpt.notice/apiserver/service"
+	"kpt.notice/middleware/notice"
+)
+
+var s *service.Service
+
+func Init(svc *service.Service) {
+	s = svc
+}
+func TestMsg() {
+	Job()
+}
+func SendDBMsg() {
+	m := new(model.Message)
+	if e := s.DB.Table("message").Where("id = ?", 4120).Find(&m).Error; e != nil {
+		fmt.Println(e)
+	}
+	m.Target = `["oLd1b56PwpexCa0QK4NCkza9TKyY"]`
+	e := service.SendMsg(m)
+	fmt.Println(e)
+	e = s.UpdateMessage(m)
+	fmt.Println(e)
+}
+func SendAllMsg() {
+	service.ReadMsgs()
+}
+
+func Job() {
+	time.Sleep(time.Minute * 10)
+}
+
+func SendMsg() {
+	p := `{
+		"miniprogram": {
+			"appid": "wx9ab2b5b25701da0a",
+			"pagepath": "pages/login/login"
+		},
+		"template_id": "RLPlaCnqQZt_6s4HZuaFJYbQ9gmTfIYipTYDoKJInY8",
+		"touser": "oLd1b56PwpexCa0QK4NCkza9TKyY",
+		"data": {
+			"first": {
+				"value": "恭喜你购买成功!",
+				"color": "#173177"
+			},
+			"keyword1": {
+				"value": "巧克力",
+				"color": "#173177"
+			},
+			"keyword2": {
+				"value": "39.8元",
+				"color": "#173177"
+			},
+			"keyword3": {
+				"value": "2014年9月22日",
+				"color": "#173177"
+			},
+			"remark": {
+				"value": "欢迎再次购买!",
+				"color": "#173177"
+			}
+		}
+	}`
+	resp, e := notice.MsgTemplate([]byte(p))
+	fmt.Printf("%s\n", resp)
+	fmt.Println(e)
+}

+ 0 - 33
middleware/notice/notice_test.go

@@ -1,33 +0,0 @@
-package notice
-
-import (
-	"net/url"
-	"testing"
-
-	"github.com/fastwego/offiaccount/apis/user"
-)
-
-func TestInfo(t *testing.T) {
-	// res, _ := GetUserInfo()
-	params := url.Values{}
-	params.Add("openid", "oLd1b56PwpexCa0QK4NCkza9TKyY")
-	res, _ := user.Get(ServerAcc, params)
-	t.Error(string(res))
-}
-
-func TestSendMsg(t *testing.T) {
-	json := `{"data":{"first":"恭喜你购买成功!","keyword1":{"value":"巧克力"},
-	"keyword2":"39.8元","keyword3":"2014年9月22日","remark":"欢迎再次购买!"},
-	"template_id":"BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo",
-	"touser":"oLd1b56PwpexCa0QK4NCkza9TKyY"}`
-	// json2 := `{
-	// 	"touser":"oLd1b56PwpexCa0QK4NCkza9TKyY",
-	// 	"template_id":"BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo",
-	// 	"data":{
-
-	// 	}
-	// }`
-	if _, err := MsgTemplate([]byte(json)); err != nil {
-		t.Error(err)
-	}
-}

+ 23 - 10
middleware/notice/wxoffice.go

@@ -1,7 +1,11 @@
 package notice
 
 import (
+	"fmt"
+
 	"github.com/fastwego/offiaccount"
+	"kpt.notice/pkg/log"
+
 	"github.com/fastwego/offiaccount/apis/account"
 	"github.com/fastwego/offiaccount/apis/message/template"
 	"github.com/pkg/errors"
@@ -19,18 +23,20 @@ var ServerAcc *offiaccount.OffiAccount = offiaccount.New(offiaccount.Config{
 	EncodingAESKey: "6yYJ4sS5y1hJgvIXEqavV2rmCutyXkywndxUQFgX54f",
 })
 
-func CreateQRCode(sceneID string) (resp []byte, err error) {
+func CreateQRCode(sceneStr string) (r []byte, err error) {
+	log.Info("notice.CreateQRCode{sceneStr  ==> ", sceneStr)
 	// time limit in 3 days
-	json := `{
-		"action_name": "QR_SCENE", 
-		"expire_seconds":259200,
-		"action_info": {
+	pm := `{
+		"expire_seconds": 259200,
+	 	"action_name": "QR_STR_SCENE", 
+	 	"action_info": {
 			"scene": {
-				"scene_id":` + sceneID + `
+				"scene_str": "` + sceneStr + `"
 			}
-		}`
+		}
+	}`
 
-	if resp, err = account.CreateQRCode(ServerAcc, []byte(json)); err != nil {
+	if r, err = account.CreateQRCode(ServerAcc, []byte(pm)); err != nil {
 		err = errors.Wrap(err, "notice.CreateQRCode==")
 	}
 	return
@@ -39,8 +45,15 @@ func CreateQRCode(sceneID string) (resp []byte, err error) {
 /*
 send tmp message to wx
 */
-func MsgTemplate(msg []byte) ([]byte, error) {
-	return template.Send(ServerAcc, msg)
+func MsgTemplate(msg []byte) (resp []byte, err error) {
+	if resp, err = template.Send(ServerAcc, msg); err != nil {
+		err = errors.Wrap(err, "notice.MsgTemplate{}")
+		log.Error(err)
+		fmt.Println(err)
+	}
+	fmt.Println(string(resp))
+	log.Info("notice.MsgTemplate{resp ==> ", string(resp))
+	return
 }
 
 // func OfficeInit() {

BIN
main → notice


+ 7 - 8
pkg/http/client.go

@@ -22,19 +22,18 @@ func NewClient(timeout time.Duration) *Client {
 	}
 }
 
-func HttpPost(url, contentType, body string) *http.Response {
+func HttpPost(url, contentType, body string) (resp *http.Response, err error) {
 	// body := `{"userinfo":"tmr.shengmu23.bbc","openid":"123"}`
 	// url :="http://kpttest.kptyun.com/userwxopenid/binding"
 	// contentType:="application/json"
-	log.Errorf("HttpPost====enter body=======%+v\n", body)
-	resp, err := http.Post(url, contentType, strings.NewReader(body))
-	if err != nil || resp.StatusCode != 200 {
-		log.Errorf("post  err ====%+v===%+v\n", err, resp.StatusCode)
-		return nil
+	log.Infof("pkg.http.HttpPost{url:%s,contentType:%s,body:%s}", url, contentType, body)
+	resp, err = http.Post(url, contentType, strings.NewReader(body))
+	if err != nil {
+		err = errors.Wrap(err, "http.HttpPost")
+		return
 	}
 	defer resp.Body.Close()
-	log.Errorf("resp=====%+v\n", resp.StatusCode)
-	return resp
+	return
 }
 func HttpGet(url string, params map[string]string) (body []byte, err error) {
 	// url :="http://kpttest.kptyun.com/userwxopenid/binding"