Browse Source

新增上传图片,优化建议接口

rdluck 4 years ago
parent
commit
2c8685f1a8

+ 76 - 0
controllers/advice.go

@@ -0,0 +1,76 @@
+package controllers
+
+import (
+	"encoding/json"
+	"hongze/hongze_cygx/models"
+	"strconv"
+	"time"
+)
+
+//优化建议
+type AdviceController struct {
+	BaseAuthController
+}
+
+// @Title 新增优化建议
+// @Description 新增优化建议接口
+// @Param	request	body company.AddCygxAdviceReq true "type json string"
+// @Success Ret=200 新增成功
+// @router /approval/approve [post]
+func (this *AdviceController) ApplyApprove() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	user := this.User
+	if user == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req models.AddCygxAdviceReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.Advice == "" {
+		br.Msg = "建议内容不可为空"
+		return
+	}
+
+	companyDetail, err := models.GetCompanyDetailById(user.CompanyId)
+	if err != nil {
+		br.Msg = "新增优化建议失败!"
+		br.ErrMsg = "获取客户详情失败,Err:" + err.Error()
+		return
+	}
+	if companyDetail == nil {
+		br.Msg = "新增优化建议失败!"
+		br.ErrMsg = "客户不存在,uid:" + strconv.Itoa(user.UserId)
+		return
+	}
+	item := new(models.CygxAdvice)
+	item.UserId = user.UserId
+	item.UserRealName = user.RealName
+	item.CompanyId = user.CompanyId
+	item.CompanyName = companyDetail.CompanyName
+	item.SalesRealName = companyDetail.SellerName
+	item.Advice = req.Advice
+	item.AdviceImgUrl = req.AdviceImgUrl
+	item.CreateTime = time.Now()
+	item.Mobile = user.Mobile
+	item.Email = user.Email
+	_, err = models.AddCygxAdvice(item)
+	if err != nil {
+		br.Msg = "新增优化建议失败"
+		br.ErrMsg = "新增优化建议失败,Err:" + err.Error()
+		return
+	}
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "新增成功"
+}

+ 3 - 1
controllers/config.go

@@ -31,4 +31,6 @@ func (this *ConfigController) BrowseHistoryList() {
 	br.Ret = 200
 	br.Success = true
 	br.Data = resp
-}
+}
+
+

+ 84 - 0
controllers/resource.go

@@ -0,0 +1,84 @@
+package controllers
+
+import (
+	"hongze/hongze_cygx/models"
+	"hongze/hongze_cygx/services"
+	"hongze/hongze_cygx/utils"
+	"os"
+	"path"
+	"time"
+)
+
+//资源管理-图片上传,合同上传等
+type ResourceController struct {
+	BaseAuthController
+}
+
+// @Title 图片上传
+// @Description 图片上传接口
+// @Param   file   query   file  true       "文件"
+// @Success 200 新增成功
+// @router /image/upload [post]
+func (this *ResourceController) Upload() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	f, h, err := this.GetFile("file")
+	if err != nil {
+		br.Msg = "获取资源信息失败"
+		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
+		return
+	}
+	ext := path.Ext(h.Filename)
+	dateDir := time.Now().Format("20060102")
+	uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
+	err = os.MkdirAll(uploadDir, 777)
+	if err != nil {
+		br.Msg = "存储目录创建失败"
+		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
+		return
+	}
+	randStr := utils.GetRandStringNoSpecialChar(28)
+	fileName := randStr + ext
+	fpath := uploadDir + "/" + fileName
+	defer f.Close() //关闭上传文件
+	err = this.SaveToFile("file", fpath)
+	if err != nil {
+		br.Msg = "文件上传失败"
+		br.ErrMsg = "文件上传失败,Err:" + err.Error()
+		return
+	}
+	//上传到阿里云
+	resourceUrl, err := services.UploadAliyun(fileName, fpath)
+	if err != nil {
+		br.Msg = "文件上传失败"
+		br.ErrMsg = "文件上传失败,Err:" + err.Error()
+		return
+	}
+
+	defer func() {
+		os.Remove(fpath)
+	}()
+
+	item := new(models.Resource)
+	item.ResourceUrl = resourceUrl
+	item.ResourceType = 1
+	item.CreateTime = time.Now()
+	newId, err := models.AddResource(item)
+	if err != nil {
+		br.Msg = "资源上传失败"
+		br.ErrMsg = "资源上传失败,Err:" + err.Error()
+		return
+	}
+	resp := new(models.ResourceResp)
+	resp.Id = newId
+	resp.ResourceUrl = resourceUrl
+
+	br.Msg = "上传成功"
+	br.Ret = 200
+	br.Success = true
+	br.Data = resp
+	return
+}

+ 16 - 1
controllers/wechat.go

@@ -2,11 +2,11 @@ package controllers
 
 import (
 	"encoding/json"
+	"github.com/medivhzhan/weapp/v2"
 	"hongze/hongze_cygx/models"
 	"hongze/hongze_cygx/services"
 	"hongze/hongze_cygx/utils"
 	"strconv"
-	"github.com/medivhzhan/weapp/v2"
 	"time"
 )
 
@@ -430,3 +430,18 @@ func (this *WechatController) GetEmailCode() {
 	br.Ret = 200
 	br.Success = true
 }
+
+//
+//func init() {
+//	fmt.Println("start")
+//	sessionKey:=`CBDTrqAe0z8uvC8gFd3lJw==`
+//	rawData:=`{"nickName":"freedom","gender":0,"language":"zh_CN","city":"","province":"","country":"","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/RsZCoxzBXkoeKlKjCkWPh8DR88rtD9PlOYLB7NaFsOmwQr2DOic3m9nh2azEnkZD2mzHZ7lf0oJ53Fh8ARQr9vA/132"}`
+//	encryptedData:=`OuyYSyhocFgQSj68B4MVvJYJdLCJkSdSu0TuCU+nhcRB6Vzji8e7v/5nDJHsRLopEzUvi/fcUdJKoUtDap08kIxfFsvxKTRXn2OeaCams8Wf6dE4N27HaSpq91Ykfq7Zm33WJJi/PK4kn86t/2a1bBe2FQRrcLH40cLveglPn88MDC0N4cJ119Ab8V4OhTzIbeUNWtlD883GQL7saSsPBsiGhd4a8qoHVmQiZGVjjRJ0vH9X2K404MNKi0kmtcmTGTiecTptY/nf2ZOwohnVYFXVg6C2qFwpZw2ozRNRs7mBzBK818SBM8MHvS6gRuTwkc27/Yhn/7SH4Gq/DTDBoseEa/RENZJdYi1OqRSuS9q+qb5kfvf8GB8I6g+rA35oxvwdqhA3iyotzh91znHr1LMyqPg/ol59TL8T1GYh9ppcg5rrkgywmlF9N+YWaSqpruB9VUxoieKjZNtre1aq1GZAnxY7bwoe7a7u1Uu6vVpnP2kScJC2zK4IgmBExV4/`
+//
+//	signature:=`a1a8a81ae75388bcbb66d92a6682ef4d16d4f634`
+//	iv:=`ibri5rJxiWOT0Ar/6AfUXw==`
+//	userInfo, err := weapp.DecryptUserInfo(sessionKey, rawData, encryptedData,signature, iv)
+//	fmt.Println(userInfo)
+//	fmt.Println(err)
+//	fmt.Println("end")
+//}

+ 32 - 0
models/advice.go

@@ -0,0 +1,32 @@
+package models
+
+import (
+	"rdluck_tools/orm"
+	"time"
+)
+
+type CygxAdvice struct {
+	AdviceId      int       `orm:"column(id);pk" description:"优化建议id"`
+	UserId        int       `description:"用户id"`
+	UserRealName  string    `description:"姓名"`
+	CompanyId     int       `description:"公司id"`
+	CompanyName   string    `description:"公司名称"`
+	SalesRealName string    `description:"所属销售"`
+	Advice        string    `description:"优化建议"`
+	AdviceImgUrl  string    `description:"图片,多张用#分割"`
+	CreateTime    time.Time `description:"提交建议时间"`
+	Mobile        string    `description:"手机号"`
+	Email         string    `description:"邮箱"`
+}
+
+//添加优化建议
+func AddCygxAdvice(item *CygxAdvice) (lastId int64, err error) {
+	o := orm.NewOrm()
+	lastId, err = o.Insert(item)
+	return
+}
+
+type AddCygxAdviceReq struct {
+	Advice       string   `description:"优化建议"`
+	AdviceImgUrl string `description:"图片,多张用#分割"`
+}

+ 3 - 3
models/article.go

@@ -3,7 +3,7 @@ package models
 import "rdluck_tools/orm"
 
 type CygxArticle struct {
-	ArticleId      int    `description:"文章id"`
+	ArticleId       int    `description:"文章id"`
 	Title           string `description:"标题"`
 	TitleEn         string `description:"英文标题 "`
 	UpdateFrequency string `description:"更新周期"`
@@ -16,7 +16,7 @@ type CygxArticle struct {
 }
 
 type HomeArticle struct {
-	ArticleId       int    `description:"文章id"`
+	ArticleId        int    `description:"文章id"`
 	Title            string `description:"标题"`
 	TitleEn          string `description:"英文标题 "`
 	UpdateFrequency  string `description:"更新周期"`
@@ -42,6 +42,7 @@ type ArticleDetail struct {
 	SubCategoryName  string `description:"二级分类"`
 	IsCollect        bool   `description:"是否收藏:true,已收藏,false:未收藏"`
 	IsInterviewApply bool   `description:"是否申请访谈:true,已申请,false:未申请"`
+	BodyText         string `description:"内容"`
 }
 
 func GetArticleDetailById(articleId int) (item *ArticleDetail, err error) {
@@ -57,4 +58,3 @@ func GetArticleDetailByIdStr(articleIdStr string) (items []*ArticleDetail, err e
 	_, err = o.Raw(sql).QueryRows(&items)
 	return
 }
-

+ 4 - 2
models/company.go

@@ -6,10 +6,12 @@ type CompanyDetail struct {
 	CompanyId   int    `orm:"column(company_id);pk"`
 	CompanyName string `description:"客户名称"`
 	Status      string `description:"客户状态"`
+	SellerId    int    `description:"销售id"`
+	SellerName  string `description:"销售名称"`
 }
 
 func GetCompanyDetailById(companyId int) (item *CompanyDetail, err error) {
-	sql := ` SELECT a.company_id,a.company_name,b.status FROM company AS a
+	sql := ` SELECT a.company_id,a.company_name,b.status,b.seller_id,b.seller_name FROM company AS a
 			INNER JOIN company_product AS b ON a.company_id=b.company_id
 			WHERE a.company_id=? AND  b.product_id=2 `
 	o := orm.NewOrm()
@@ -27,4 +29,4 @@ func GetCompanyPermission(companyId int) (permission string, err error) {
 	o := orm.NewOrm()
 	err = o.Raw(sql, companyId).QueryRow(&permission)
 	return
-}
+}

+ 1 - 0
models/db.go

@@ -33,5 +33,6 @@ func init() {
 		new(WxUserCode),
 		new(CygxArticleCollect),
 		new(CygxArticleViewRecord),
+		new(CygxAdvice),
 	)
 }

+ 34 - 0
models/resource.go

@@ -0,0 +1,34 @@
+package models
+
+import (
+	"rdluck_tools/orm"
+	"time"
+)
+
+type Resource struct {
+	Id           int       `orm:"column(id);" description:"资源id"`
+	ResourceUrl  string    `description:"资源地址"`
+	CreateTime   time.Time `description:"创建时间"`
+	ResourceType int       `description:"资源类型,1:图片,2:音频,3:视频 "`
+}
+
+type ResourceResp struct {
+	Id          int64  `orm:"column(id);" description:"用户id"`
+	ResourceUrl string `description:"资源地址"`
+	PlaySeconds    uint32 `description:"播放时长,单位秒"`
+}
+
+func AddResource(item *Resource) (newId int64, err error) {
+	o := orm.NewOrm()
+	o.Using("rddp")
+	newId, err = o.Insert(item)
+	return
+}
+
+func GetResourceById(id string) (item *Resource, err error) {
+	o := orm.NewOrm()
+	o.Using("rddp")
+	sql := "SELECT * FROM resource WHERE id=? "
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}

+ 10 - 0
routers/router.go

@@ -58,6 +58,16 @@ func init() {
 				&controllers.SearchController{},
 			),
 		),
+		beego.NSNamespace("/resource",
+			beego.NSInclude(
+				&controllers.ResourceController{},
+			),
+		),
+		beego.NSNamespace("/advice",
+			beego.NSInclude(
+				&controllers.AdviceController{},
+			),
+		),
 	)
 	beego.AddNamespace(ns)
 }

+ 48 - 30
services/elasticsearch.go

@@ -5,12 +5,14 @@ import (
 	"encoding/json"
 	"fmt"
 	"hongze/hongze_cygx/models"
-	"hongze/hongze_cygx/utils"
+	"html"
 	"strconv"
+	"strings"
 
 	//"gopkg.in/olivere/elastic.v5"
 	//"gopkg.in/olivere/elastic.v5/config"
 
+	"github.com/PuerkitoBio/goquery"
 	"github.com/olivere/elastic/v7"
 	"github.com/olivere/elastic/v7/config"
 )
@@ -54,19 +56,35 @@ func SaveData() {
 		}
 	}
 
-	//item, err := models.GetArticleDetailById(3138)
-	//if err != nil {
-	//	fmt.Println("GetArticleDetailById Err:" + err.Error())
-	//	return
-	//}
-	//
-	////插入一条数据,id指定为对应的name,若不指定则随机生成
-	//resp, err := client.Index().Index(esIndex).Id(strconv.Itoa(item.ArticleId)).BodyJson(item).Do(context.Background())
-	//if err != nil {
-	//	fmt.Println("insert es failed", err.Error())
-	//	return
-	//}
-	//fmt.Println(resp.Status)
+	/*
+		3161,3190,3226,3244,3264,3285,3310,3334,3370,3397,3418,3446,3477,3497,3526,3554
+	*/
+
+	idStr := `3161,3190,3226,3244,3264,3285,3310,3334,3370,3397,3418,3446,3477,3497,3526,3554`
+	idArr := strings.Split(idStr, ",")
+	for _, v := range idArr {
+		id, _ := strconv.Atoi(v)
+		item, err := models.GetArticleDetailById(id)
+		if err != nil {
+			fmt.Println("GetArticleDetailById Err:" + err.Error())
+			return
+		}
+		content := html.UnescapeString(item.Body)
+		doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
+		if err != nil {
+			fmt.Println("create doc err:", err.Error())
+			return
+		}
+		bodyText := doc.Text()
+		item.BodyText = bodyText
+		//删除
+		resp, err := client.Index().Index(esIndex).Id(strconv.Itoa(item.ArticleId)).BodyJson(item).Do(context.Background())
+		if err != nil {
+			fmt.Println("insert es failed", err.Error())
+			return
+		}
+		fmt.Println(resp.Status)
+	}
 
 	/*
 
@@ -94,25 +112,25 @@ func SaveData() {
 
 	//根据检索条件查询
 
-	boolquery := elastic.NewBoolQuery()
+	// boolquery := elastic.NewBoolQuery()
 
-	boolquery.Should(elastic.NewMatchQuery("Body", "专家"))
-	highlight := elastic.NewHighlight()
-	highlight = highlight.Fields(elastic.NewHighlighterField("Body"))
-	highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
+	// boolquery.Should(elastic.NewMatchQuery("Body", "专家"))
+	// highlight := elastic.NewHighlight()
+	// highlight = highlight.Fields(elastic.NewHighlighterField("Body"))
+	// highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
 
-	var pageSize int
-	pageSize = 20
+	// var pageSize int
+	// pageSize = 20
 
-	searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(boolquery).Do(context.Background())
+	// searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(boolquery).Do(context.Background())
 
-	var result string
-	if searchByMatch.Hits != nil {
+	// var result string
+	// if searchByMatch.Hits != nil {
 
-	}
-	//fmt.Println(string(result))
+	// }
+	// //fmt.Println(string(result))
 
-	utils.FileLog.Info("%s", string(result))
+	// utils.FileLog.Info("%s", string(result))
 
 	//var resultType models.CygxArticle
 	//for k,item := range searchByMatch.Each(reflect.TypeOf(resultType)) {
@@ -151,10 +169,10 @@ func SearchByKeyWord(keyWord string, pageSize int) (result []*models.SearchItem,
 	var esIndex = "cygx_article"
 	boolquery := elastic.NewBoolQuery()
 
-	boolquery.Should(elastic.NewMatchQuery("Title", keyWord), elastic.NewMatchQuery("Body", keyWord))
+	boolquery.Must(elastic.NewMatchQuery("Title", keyWord), elastic.NewMatchQuery("BodyText", keyWord))
 
 	highlight := elastic.NewHighlight()
-	highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("Body"))
+	highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
 	highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
 
 	searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(boolquery).Do(context.Background())
@@ -175,7 +193,7 @@ func SearchByKeyWord(keyWord string, pageSize int) (result []*models.SearchItem,
 			}
 			searchItem := new(models.SearchItem)
 			searchItem.ArticleId, _ = strconv.Atoi(v.Id)
-			searchItem.Body = v.Highlight["Body"]
+			searchItem.Body = v.Highlight["BodyText"]
 			var title string
 			if len(v.Highlight["Title"]) > 0 {
 				title = v.Highlight["Title"][0]

+ 92 - 0
services/oss.go

@@ -0,0 +1,92 @@
+package services
+
+import (
+	"github.com/aliyun/aliyun-oss-go-sdk/oss"
+	"os"
+	"time"
+
+	"hongze/hongze_cygx/utils"
+)
+
+/*
+上传demo
+func init() {
+	fmt.Println("start")
+	randStr := utils.GetRandStringNoSpecialChar(28)
+	fileName :=  randStr + ".jpg"
+	fmt.Println("fileName:",fileName)
+	fpath:="./1.png"
+	resourceUrl,err:=UploadAliyun(fileName,fpath)
+	if err!=nil {
+		fmt.Println("UploadAliyun Err:",err.Error())
+		return
+	}
+	fmt.Println("resourceUrl:",resourceUrl)
+	fmt.Println("end")
+}
+*/
+
+//图片上传到阿里云
+func UploadAliyun(filename, filepath string) (string,error) {
+	client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
+	if err != nil {
+		return "1",err
+	}
+	bucket, err := client.Bucket(utils.Bucketname)
+	if err != nil {
+		return "2",err
+	}
+	path := utils.Upload_dir + time.Now().Format("200601/20060102/")
+	path += filename
+	err = bucket.PutObjectFromFile(path, filepath)
+	if err != nil {
+		return "3",err
+	}
+	path = utils.Imghost + path
+	return path,err
+}
+
+
+//音频上传到阿里云
+func UploadAudioAliyun(filename, filepath string) (string,error) {
+	client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
+	if err != nil {
+		return "1",err
+	}
+	bucket, err := client.Bucket(utils.Bucketname)
+	if err != nil {
+		return "2",err
+	}
+	path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
+	path += filename
+	err = bucket.PutObjectFromFile(path, filepath)
+	if err != nil {
+		return "3",err
+	}
+	path = utils.Imghost + path
+	return path,err
+}
+
+//视频上传到阿里云
+func UploadVideoAliyun(filename, filepath,savePath string) (error) {
+	defer func() {
+		os.Remove(filepath)
+	}()
+	client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
+	if err != nil {
+		return err
+	}
+	bucket, err := client.Bucket(utils.Bucketname)
+	if err != nil {
+		return err
+	}
+	//path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
+	//path += filename
+	err = bucket.PutObjectFromFile(savePath, filepath)
+	if err != nil {
+		return err
+	}
+	//path = utils.Imghost + path
+	//return path,err
+	return err
+}

+ 1 - 0
services/task.go

@@ -9,5 +9,6 @@ func Task() {
 	//keyWord := "专家"
 	//pageSize := 20
 	//SearchByKeyWord(keyWord, pageSize)
+	//SaveData()
 	fmt.Println("end")
 }