Commit f232605a by mushishixian

init project

parents
Homestead.yaml
Homestead.json
# ide
.idea
*.properties
*.iml
/logs
/components
/storage/app
/storage/framework
/storage/logs
/.idea
/storage/debugbar
.DS_Store?
.DS_Store
/configs
cmd/cmd.exe
cmd/move/logs/
/cmd/dong/logs/*.log
/sh
## caipu-server
### v1.0.0
1. 上线功能xxx
# Owner
# Author
# Reviewer
# caipu-server
## 项目简介
1.GO服务DEMO
2.运行命令
go run cmd/main.go -conf=./configs/
package main
import (
"scm_server/internal/dao"
"scm_server/internal/model"
"fmt"
)
func main() {
fmt.Println(1)
//测试数据库连接
var user_info model.UserInfo
var user_company model.UserCompany
//查找公司名称
err := dao.GetDb().QueryRowx("select com_name from lie_user_company where user_id = ?",1).StructScan(&user_company)
if err != nil {
fmt.Println(err)
}
fmt.Println(user_company.Com_name)
//查找手机号
err = dao.GetCmsDb().QueryRowx("select mobile from user_info where userId = ?",1599).StructScan(&user_info)
if err != nil {
fmt.Println(err)
}
fmt.Println(user_info.Mobile)
}
package logic
import (
"scm_server/internal/dao"
"scm_server/internal/model"
"scm_server/internal/service"
"time"
)
//用户池中已下单的释放
func HaveCreateHandle() {
db := dao.GetDb()
//需要等待释放的用户
var CreateOrderHandleUser = make(map[int]int)
var assign_active model.AssignActive
var month_time = (time.Now().Unix()- 86400 * 30 * 4)
//查找第一次出不再跟随的用户ID,然后释放
rows,err := db.Queryx("select aa.user_id,turn_in_id,no_create_order from lie_assign_active as aa left join lie_user_extend ue on aa.user_id = ue.user_id where is_success = ? and ue.no_create_order = 2 and change_time < ? and latest_order_time < ?",1,month_time,month_time)
service.AdminErr(err)
for rows.Next() {
err = rows.StructScan(&assign_active)
service.AdminErr(err)
CreateOrderHandleUser[assign_active.User_Id] = assign_active.Turn_In_id
dao.GetDb().Exec("delete from lie_salesman where user_id = ?",assign_active.User_Id)
}
//查找第二次出不再跟随的用户ID,释放并且屏蔽
rows,err = db.Queryx("select aa.user_id,turn_in_id,no_create_order from lie_assign_active as aa left join lie_user_extend ue on aa.user_id = ue.user_id where is_success = 2 and ue.no_create_order = 2 and change_time < ? and latest_order_time < ?",month_time,month_time)
service.AdminErr(err)
for rows.Next() {
err = rows.StructScan(&assign_active)
service.AdminErr(err)
CreateOrderHandleUser[assign_active.User_Id] = assign_active.Turn_In_id
SetFreeHandleUser[assign_active.User_Id] = CreateOrderHandleUser[assign_active.User_Id]
dao.GetDb().Exec("delete from lie_salesman where user_id = ?",assign_active.User_Id)
}
}
package logic
import (
"scm_server/internal/dao"
"scm_server/internal/model"
"scm_server/internal/service"
"time"
)
//用户池中未下单的待处理
func NoCreateHandle() {
db := dao.GetDb()
var assign_active model.AssignActive
var NoOrderHandleUser = make(map[int]int)
var month_time = (time.Now().Unix()- 86400 * 30)
//查找第一次出不再跟随的用户ID,然后释放
rows,err := db.Queryx("select aa.user_id,turn_in_id,no_create_order from lie_assign_active as aa left join lie_user_extend ue on aa.user_id = ue.user_id where is_success = ? and ue.no_create_order = 1 and change_time < ? and latest_order_time < ?",1,month_time,month_time)
service.AdminErr(err)
for rows.Next() {
err = rows.StructScan(&assign_active)
service.AdminErr(err)
NoOrderHandleUser[assign_active.User_Id] = assign_active.Turn_In_id
dao.GetDb().Exec("delete from lie_salesman where user_id = ?",assign_active.User_Id)
}
//查找第二次出不再跟随的用户ID,释放并且屏蔽
rows,err = db.Queryx("select aa.user_id,turn_in_id,no_create_order from lie_assign_active as aa left join lie_user_extend ue on aa.user_id = ue.user_id where is_success = ? and ue.no_create_order = 1 and change_time < ? and latest_order_time < ?",2,month_time,month_time)
service.AdminErr(err)
for rows.Next() {
err = rows.StructScan(&assign_active)
service.AdminErr(err)
NoOrderHandleUser[assign_active.User_Id] = assign_active.Turn_In_id
SetFreeHandleUser[assign_active.User_Id] = NoOrderHandleUser[assign_active.User_Id]
dao.GetDb().Exec("delete from lie_salesman where user_id = ?",assign_active.User_Id)
}
}
\ No newline at end of file
package logic
import (
"scm_server/internal/dao"
"scm_server/internal/model"
"scm_server/internal/service"
"fmt"
"time"
)
//提醒客服
func Notify() {
var assign_active model.AssignActive
//查找出需要发送通知的用户,发送通知
rows,err := dao.GetDb().Queryx("select turn_in_id,aa.user_id from lie_assign_active as aa left join lie_user_extend ue on aa.user_id = ue.user_id where (ue.no_create_order = 1 and change_time < ? and change_time > ? and latest_order_time < ? ) or (ue.no_create_order = 2 and change_time < ? and change_time > ? and latest_order_time < ? ) ",
(time.Now().Unix()- 86400 * 23),(time.Now().Unix()- 86400 * 24),(time.Now().Unix()- 86400 * 23),(time.Now().Unix()- 86400 * 113),(time.Now().Unix()- 86400 * 114),(time.Now().Unix()- 86400 * 113))
service.AdminErr(err)
var user_info model.UserInfo
var user_company model.UserCompany
for rows.Next() {
_ = rows.StructScan(&assign_active)
//查找手机号
err := dao.GetCmsDb().QueryRowx("select mobile from user_info where userId = ?",assign_active.Turn_In_id).StructScan(&user_info)
if err != nil {
fmt.Println(err)
}
//查找公司名称
err = dao.GetDb().QueryRowx("select com_name from lie_user_company where user_id = ?",assign_active.User_Id).StructScan(&user_company)
if err != nil {
fmt.Println(err)
}
service.SendMessage(user_info.Mobile,"您的客户:"+user_company.Com_name+"在跟进后多天后仍未下单,还有7天将被转出,请注意查看")
}
}
package logic
import (
"scm_server/internal/dao"
"fmt"
"time"
)
//需要等地屏蔽的用户
var SetFreeHandleUser = make(map[int]int)
//释放用户
func SetFree() {
//查找出即将释放的用户,然后释放
for k,v := range SetFreeHandleUser{
_,err := dao.GetDb() .Exec("INSERT INTO `lie_not_follow_user` (`user_id`, `sale_id`, `stop_time`)VALUES(?, ?,?)",k,v,time.Now().Unix())
if err != nil {
fmt.Println("添加记录失败",k)
}
dao.GetDb().Exec("delete from lie_assign_active where user_id = ? and turn_in_id = ?",k,v)
dao.GetDb().Exec("update lie_user set is_free = 1 where user_id",k)
}
}
\ No newline at end of file
package main
import "scm_server/cmd/pond/logic"
//tpad https://www.tapd.cn/20225631/prong/stories/view/1120225631001003634
func main() {
logic.HaveCreateHandle()
logic.NoCreateHandle()
logic.Notify()
logic.SetFree()
}
package main
import (
"scm_server/cmd/queue/user_add/user_add_queue_logic"
"scm_server/configs"
"scm_server/internal/dao"
"scm_server/internal/service"
"encoding/json"
"fmt"
"github.com/streadway/amqp"
"log"
"strconv"
"time"
)
type WaitUpdateUserSale struct {
User_Id int `json:"user_id"`
Sale_Id int `json:"sale_id"`
}
func main() {
//定义队列类型和错误类型
service.ProGramErrType = "crm_update_user_sales"
conn, err := amqp.Dial("amqp://"+configs.RABBITMQDSN+"/")
if err != nil {
service.WriteErrDetail(err.Error() + "Failed to connect to RabbitMQ")
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
service.WriteErrDetail(err.Error() + "Failed to open a channel")
}
defer ch.Close()
q, err := ch.QueueDeclare(
service.ProGramErrType, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
service.WriteErrDetail(err.Error()+"Failed to declare a queue")
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
service.WriteErrDetail(err.Error() +"Failed to register a consumer")
}
forever := make(chan bool)
var updateUserSale WaitUpdateUserSale
go func() {
for d := range msgs {
fmt.Println(string(d.Body))
json.Unmarshal(d.Body,&updateUserSale)
handle(updateUserSale.User_Id,updateUserSale.Sale_Id)
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
//修改用户的客服
func handle(userId,saleId int)(result bool) {
//查找出crm中的用户
var crmUserId int
_ = dao.GetDb().QueryRowx("select user_id from lie_user where outter_uid = ?",userId).Scan(&crmUserId)
if crmUserId == 0 {
//不存在推一个队列,然后停止2秒,再检查
user_add_queue_logic.PushUserQueue(userId)
time.Sleep(2*time.Second)
_ = dao.GetDb().QueryRowx("select user_id from lie_user where outter_uid = ?",userId).Scan(&crmUserId)
if crmUserId == 0{
service.WriteErrDetail(strconv.Itoa(crmUserId)+"不存在")
return false
}
}
var timeNow = time.Now().Unix()
_,err := dao.GetDb().Exec("update lie_salesman set assign_time = ?,update_time = ?,sale_id= ? where user_id = ?",timeNow,timeNow,saleId,crmUserId)
fmt.Println(err)
_,err = dao.GetDb().Exec("insert into lie_action_log(`user_id`,`operator_id`,`create_time`,`remark`,`admin`,`event`)value(?,?,?,'转为已下单用户','admin','用户下单')",crmUserId,saleId,timeNow)
fmt.Println(err)
return true
}
package main
import (
"scm_server/configs"
"scm_server/internal/common"
"scm_server/internal/logic"
"scm_server/internal/model"
"scm_server/internal/service"
"encoding/json"
"fmt"
"github.com/streadway/amqp"
"log"
"strconv"
)
var(
InsertData model.MemberAddUserData
)
type WaitAddUser struct {
User_Id int `json:"user_id"`
}
//监听用户添加队列
func main(){
//定义队列类型和错误类型
service.ProGramErrType = "member_user_add"
//设置所有城市
common.SetCityName()
conn, err := amqp.Dial("amqp://"+configs.RABBITMQDSN+"/")
if err != nil {
service.WriteErrDetail(err.Error() + "Failed to connect to RabbitMQ")
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
service.WriteErrDetail(err.Error() + "Failed to open a channel")
}
defer ch.Close()
q, err := ch.QueueDeclare(
service.ProGramErrType, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
service.WriteErrDetail(err.Error()+"Failed to declare a queue")
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
service.WriteErrDetail(err.Error() +"Failed to register a consumer")
}
forever := make(chan bool)
var user WaitAddUser
go func() {
for d := range msgs {
json.Unmarshal(d.Body,&user)
fmt.Println(user)
handle(user.User_Id)
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
func handle(memberId int)(result bool) {
//获取当前会员的基本数据
InsertData = logic.GetMemberUserInfo(memberId)
//检测用户是否存在
if InsertData.User_Id == 0 {
service.WriteErrDetail(strconv.Itoa(memberId) + "会员系统中用户信息不存在")
return false
}
if logic.CheckMemberIdIsHave(InsertData.User_Id) != 0 {
service.WriteErrDetail(strconv.Itoa(memberId) + "crm系统中用户已经存在")
return false
}
//处理得到的用户数据
InsertData = logic.HandleData(InsertData)
//插入数据
if !logic.InsertMemberUser(InsertData) {
errSourcedata, _ := json.Marshal(InsertData)
service.WriteErrDetail("插入用户数据错误:" + string(errSourcedata))
return false
}
return true
}
\ No newline at end of file
package user_add_queue_logic
import (
"scm_server/configs"
"scm_server/internal/service"
"encoding/json"
"github.com/streadway/amqp"
)
type WaitAddUser struct {
User_Id int `json:"user_id"`
}
//推送一个用户数据
func PushUserQueue(memberId int) {
var user WaitAddUser
user.User_Id = memberId
//链接mq
conn, err := amqp.Dial("amqp://"+configs.RABBITMQDSN+"/")
defer conn.Close()
service.WriteErr(err)
//通道
ch, err := conn.Channel()
defer ch.Close()
service.WriteErr(err)
//设置数据
q, err := ch.QueueDeclare(
"member_user_add", // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
service.WriteErr(err)
sendBody,err := json.Marshal(user)
ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing {
ContentType: "text/plain",
Body: sendBody,
})
service.WriteErr(err)
}
\ No newline at end of file
package main
import (
"scm_server/internal/dao"
"scm_server/internal/model"
)
//向crm中插入数据
const INSERTFEEDBACK = "INSERT INTO `lie_feedback` (`user_id`, `outter_uid`, `ip`, `type`, `mobile`, `content`, `source`, `pf`, `status`, `sale_id`, `bom_url`, `responses`,`create_time`)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)"
//查询主库里面的fb数据
const SELECTFEEDBACK = "select `user_id`, `ip`, `type`, `mobile`, `content`, `create_time`, `source`, `pf`, `status`, `sale_id`, `bom_url`, `responses`, `create_time` from lie_feedback where id = ?"
func main() {
//增加rabbitmq推送过来的数据
var lieXinFeedBack model.Feedback
var lieXinFeedId int = 2
var User_Id int
err := dao.GetLiexinDb().QueryRowx(SELECTFEEDBACK,lieXinFeedId).StructScan(&lieXinFeedBack)
err_two := dao.GetDb().QueryRowx("select user_id from lie_user where outter_uid = ?",lieXinFeedBack.User_Id).Scan(&User_Id)
if err == nil && err_two == nil && User_Id != 0 {
lieXinFeedBack.Outter_Uid = lieXinFeedBack.User_Id
lieXinFeedBack.User_Id = User_Id
row,insertErr := dao.GetDb().Exec(INSERTFEEDBACK,lieXinFeedBack.User_Id,lieXinFeedBack.Outter_Uid,lieXinFeedBack.Ip,lieXinFeedBack.Type,lieXinFeedBack.Mobile,lieXinFeedBack.Content,lieXinFeedBack.Source, lieXinFeedBack.Pf,lieXinFeedBack.Status,lieXinFeedBack.Sale_Id,lieXinFeedBack.Bom_Url,lieXinFeedBack.Responses,lieXinFeedBack.Create_Time)
insertId,_ := row.LastInsertId()
if insertErr == nil {
dao.GetDb().Exec("update lie_user set fkid = ? where user_id = ?",insertId,User_Id)
}
}
}
\ No newline at end of file
package main
import (
"scm_server/internal/dao"
"scm_server/internal/service"
"fmt"
"time"
)
//查询需要发送消息的数据
const USERMESSAGE = "select `lie_l`.`msg_log_id`, `lie_l`.`user_id`, `lie_l`.`fol_id`, `lie_f`.`next_details`, `lie_f`.`remind_type`, `lie_f`.`remind_time`, `lie_l`.`sale_id` from `lie_msg_log` as `lie_l` left join `lie_follow_up` as `lie_f` on `lie_l`.`fol_id` = `lie_f`.`fol_id` where (`lie_l`.`remind_type` = 5) and `lie_l`.`status` <> -1 and `lie_f`.`remind_type` = 'wait_notify' and `lie_f`.`remind_time` <= ? order by `lie_l`.`create_time` desc"
//查找用户手机号
const MOBILEVALUE = "select mobile from user_info where userId = ?"
//修改消息为已经发送
const UPDATEHAVEREAD = "update lie_msg_log set remind_type = ? and create_time = ? where msg_log_id = ? "
type UserMessage struct {
User_Id int `json:"user_id"`
Fol_Id int `json:"fol_id"`
Next_Details string `json:"next_details"`
Remind_Type string `json:"remind_type"`
Remind_Time int `json:"remind_time"`
Sale_Id int `json:"sale_id"`
Msg_Log_id int `json:"msg_log_id"`
}
//给用户发送消息
func main() {
var userMessage []UserMessage
var mobile int64
var timeNow = time.Now().Unix()
//查找出需要发送的数据
err := dao.GetDb().Select(&userMessage,USERMESSAGE,timeNow)
if err != nil{
service.WriteErr(err)
}
if len(userMessage) <= 0 {
panic("暂无需要发送的消息")
}
for _,v := range userMessage{
mobile = 0
err := dao.GetCmsDb().QueryRowx(MOBILEVALUE,v.Sale_Id).Scan(&mobile)
if mobile == 0 {
continue
}
service.SendMessage(mobile,v.Next_Details)
_,err = dao.GetDb().Exec(UPDATEHAVEREAD,1,timeNow,v.Msg_Log_id)
if err != nil {
fmt.Println(err)
}
}
}
\ No newline at end of file
package customer
import (
"fmt"
"github.com/tealeg/xlsx"
)
//导入委托方的信息(excel导入)
func Import(){
excelFileName := "./cmd/source/data/customer.xlsx";
xlFile, err := xlsx.OpenFile(excelFileName)
if err != nil {
fmt.Printf("open failed: %s\n", err)
}
for _, sheet := range xlFile.Sheets {
fmt.Printf("Sheet Name: %s\n", sheet.Name)
//for _, row := range sheet.Rows {
// for _, cell := range row.Cells {
// text := cell.String()
// fmt.Printf("%s\n", text)
// }
//}
}
}
\ No newline at end of file
No preview for this file type
No preview for this file type
package main
import (
"scm_server/cmd/source/customer"
)
func main() {
customer.Import()
}
module scm_server
go 1.13
require (
github.com/jmoiron/sqlx v1.2.0 // indirect
github.com/tealeg/xlsx v1.0.5
)
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA=
github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/tealeg/xlsx v1.0.5 h1:+f8oFmvY8Gw1iUXzPk+kz+4GpbDZPK1FhPiQRd+ypgE=
github.com/tealeg/xlsx v1.0.5/go.mod h1:btRS8dz54TDnvKNosuAqxrM1QgN1udgk9O34bDCnORM=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
package common
import (
"crypto/md5"
"encoding/hex"
)
// Md5 md5()
func Md5(str string) string {
hash := md5.New()
hash.Write([]byte(str))
return hex.EncodeToString(hash.Sum(nil))
}
package dao
import (
"context"
"time"
"scm_server/internal/model"
"github.com/bilibili/kratos/pkg/cache/memcache"
"github.com/bilibili/kratos/pkg/cache/redis"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/bilibili/kratos/pkg/database/sql"
"github.com/bilibili/kratos/pkg/log"
xtime "github.com/bilibili/kratos/pkg/time"
)
// Dao dao interface
type Dao interface {
Close()
Ping(ctx context.Context) (err error)
GetUserInfoByUserId(ctx context.Context,user_id int64) (r *model.Users,err error)
}
// dao dao.
type dao struct {
db *sql.DB
redis *redis.Pool
redisExpire int32
mc *memcache.Memcache
mcExpire int32
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
// New new a dao and return.
func New() (Dao) {
var (
dc struct {
Crm *sql.Config
}
rc struct {
Demo *redis.Config
DemoExpire xtime.Duration
}
mc struct {
Demo *memcache.Config
DemoExpire xtime.Duration
}
)
checkErr(paladin.Get("mysql.toml").UnmarshalTOML(&dc))
checkErr(paladin.Get("redis.toml").UnmarshalTOML(&rc))
checkErr(paladin.Get("memcache.toml").UnmarshalTOML(&mc))
return &dao{
// mysql
db: sql.NewMySQL(dc.Crm),
// redis
redis: redis.NewPool(rc.Demo),
redisExpire: int32(time.Duration(rc.DemoExpire) / time.Second),
// memcache
mc: memcache.New(mc.Demo),
mcExpire: int32(time.Duration(mc.DemoExpire) / time.Second),
}
}
// Close close the resource.
func (d *dao) Close() {
d.mc.Close()
d.redis.Close()
d.db.Close()
}
// Ping ping the resource.
func (d *dao) Ping(ctx context.Context) (err error) {
if err = d.pingMC(ctx); err != nil {
return
}
if err = d.pingRedis(ctx); err != nil {
return
}
return d.db.Ping(ctx)
}
func (d *dao) pingMC(ctx context.Context) (err error) {
if err = d.mc.Set(ctx, &memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0}); err != nil {
log.Error("conn.Set(PING) error(%v)", err)
}
return
}
func (d *dao) pingRedis(ctx context.Context) (err error) {
conn := d.redis.Get(ctx)
defer conn.Close()
if _, err = conn.Do("SET", "ping", "pong"); err != nil {
log.Error("conn.Set(PING) error(%v)", err)
}
return
}
package dao
import (
"scm_server/configs"
"fmt"
"log"
"github.com/jmoiron/sqlx"
)
func GetDb()(*sqlx.DB) {
dbConfig := configs.GetDBOne()
db, err := sqlx.Open(dbConfig.Engine, fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", dbConfig.User, dbConfig.Pass, dbConfig.Ip, dbConfig.Port, dbConfig.Table))
if err != nil {
log.Fatalln(err)
}
return db
}
func GetCmsDb()(*sqlx.DB) {
dbConfig := configs.GetDBCms()
db, err := sqlx.Open(dbConfig.Engine, fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", dbConfig.User, dbConfig.Pass, dbConfig.Ip, dbConfig.Port, dbConfig.Table))
if err != nil {
log.Fatalln(err)
}
return db
}
func GetLiexinDb()(*sqlx.DB) {
dbConfig := configs.GetDBLiexin()
db, err := sqlx.Open(dbConfig.Engine, fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", dbConfig.User, dbConfig.Pass, dbConfig.Ip, dbConfig.Port, dbConfig.Table))
if err != nil {
log.Fatalln(err)
}
return db
}
package dao
import (
"context"
"scm_server/internal/model"
"github.com/bilibili/kratos/pkg/database/sql"
"github.com/pkg/errors"
)
const (
_user_Info_One = "SELECT user_id FROM lie_user WHERE user_id=?"
)
//通过UID获取用户信息
func (d *dao) GetUserInfoByUserId(ctx context.Context, user_id int64) (r *model.Users, err error) {
var row *sql.Row
r = new(model.Users)
row = d.db.QueryRow(ctx, _user_Info_One, user_id)
if err = row.Scan(&r.User_id); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
package logic
import (
"scm_server/internal/dao"
"scm_server/internal/model"
"scm_server/internal/service"
)
const INSERTCRMUSER = "INSERT INTO `lie_user` (" +
"`outter_uid`, `source`,`adtag`, `mobile`,`email`, `create_time`,`copy_ctime`, `customer_identity`,`name`, `channel_source`,`remark`,`ptag`,`channel_source_other`" +
")VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)"
const INSERTCOMPANY = "INSERT INTO `lie_user_company` (" +
"`user_id`, `com_name`,`address`, `fixed_tel`,`fax`, `main_brand`,`com_desc`, `create_time`)VALUES(?,?,?,?,?,?,?,?)"
const INSERTISCREATEORDER = "INSERT INTO `lie_user_extend` (`user_id`, `no_create_order`,`outter_uid`)VALUES(?,?,?)"
const INSERTSALES = "INSERT INTO `lie_salesman` (`user_id`, `sale_id`,`assign_time`)VALUES(?,?,?)"
//检测会员用户是否存在
func CheckMemberIdIsHave(memberId int)(returnUserId int){
var userId int = 0
dao.GetDb().QueryRowx("select user_id from lie_user where outter_uid = ?",memberId).Scan(&userId)
return userId
}
//增加从会员系统来的用户
func InsertMemberUser(memberInfo model.MemberAddUserData)bool {
//开启事务,增加用户数据
dbTran,_ := dao.GetDb().Begin()
insertResult, err := dbTran.Exec(INSERTCRMUSER,memberInfo.User_Id,memberInfo.Source,memberInfo.Adtag,memberInfo.Mobile,memberInfo.Email,memberInfo.Create_Time,memberInfo.Create_Time, memberInfo.Customer_identity,memberInfo.User_Name,memberInfo.Channel_source,memberInfo.Remark,memberInfo.Ptag,"")
if err != nil {
service.WriteErrDetail("插入用户数据错误:增加用户数据"+err.Error())
err = dbTran.Rollback()
return false
}
//获取插入ID
lastInsertId,err := insertResult.LastInsertId()
if err != nil {
service.WriteErrDetail("插入用户数据错误:获取插入ID"+err.Error())
err = dbTran.Rollback()
return false
}
//插入是否下单
insertResult, err = dbTran.Exec(INSERTISCREATEORDER,lastInsertId,memberInfo.No_Create_Order,memberInfo.User_Id)
if err != nil {
service.WriteErrDetail("插入用户数据错误:插入是否下单"+err.Error())
err = dbTran.Rollback()
return false
}
//插入跟进销售
insertResult, err = dbTran.Exec(INSERTSALES,lastInsertId,memberInfo.Sale_Id,memberInfo.Create_Time)
if err != nil {
service.WriteErrDetail("插入用户数据错误:插入跟进销售"+err.Error())
err = dbTran.Rollback()
return false
}
//插入公司
insertResult, err = dbTran.Exec(INSERTCOMPANY,lastInsertId,memberInfo.Com_Name,memberInfo.Com_Full_addr,memberInfo.Com_Telphone,memberInfo.Com_Fax,"",memberInfo.Com_Desc, memberInfo.Create_Time)
if err != nil {
service.WriteErrDetail("插入用户数据错误:插入公司"+err.Error())
err = dbTran.Rollback()
return false
}
dbTran.Commit()
return true
}
\ No newline at end of file
package logic
import (
"scm_server/internal/dao"
"scm_server/internal/model"
"time"
)
const CheckCustomerExistSql = `SELECT FROM lie_customer WHERE erp_id = ?`
const InsertCustomerSql = `Insert into lie_customer ('erp_client_code','name','erp_id',
'add_time','is_synced') VALUES (?,?,?,?,?)`
//检查用户是否存在
func CheckCustomerExist(erpId string) (exist bool) {
return true
}
func InsertCustomer(customer model.Customer) {
dao.GetDb().Exec(InsertCustomerSql, customer.ErpClientCode, customer.Name, customer.ErpId, time.Now().Unix(), 0)
}
package logic
import (
"scm_server/internal/common"
"scm_server/internal/dao"
"scm_server/internal/model"
"scm_server/internal/service"
"fmt"
"regexp"
"strconv"
"strings"
)
//会员系统的用户逻辑
var(
adtag = ""
ptag = ""
refer = ""
)
const(
AdtagRex = "adtag=.*"
PtagRex = "ptag=.*"
ReferRex = "refer=.*"
)
//获取会员系统的用户数据sql
const GETMEMBERUSER = "select `lie_u`.`user_id`, `lie_u`.`mobile`, `lie_u`.`user_name`, `lie_u`.`email`," +
" `lie_u`.`reg_remark`, `lie_u`.`create_device`, `lie_u`.`create_time`, `lie_c`.`com_id`, `lie_c`.`type_id`," +
" `lie_c`.`com_name`, `lie_c`.`com_desc`, `lie_c`.`com_province_id`, `lie_c`.`com_city_id`, `lie_c`.`com_area_id`," +
" `lie_c`.`com_address`, `lie_c`.`com_telphone`, `lie_c`.`com_fax`, `lie_c`.`brand_list`, `lie_i`.`work_function`," +
" `lie_i`.`user_type`, `lie_i`.`sale_id` as `userinfo_sale_id` from `lie_user_main` as `lie_u` left join `lie_user_info` as " +
"`lie_i` on `lie_u`.`user_id` = `lie_i`.`user_id` left join `lie_user_company` as `lie_c` on `lie_u`.`user_id` = `lie_c`.`user_id`" +
" where `lie_u`.`is_test` = 0 and `lie_u`.`is_type` = 0 and `lie_u`.`user_id` = ? and `lie_u`.`create_device` not in (3, 20)"
//获取会员系统的用户数据sql
func GetMemberUserInfo(memberId int) model.MemberAddUserData {
var MemberUserInfo model.MemberAddUserData
err := dao.GetLiexinDb().QueryRowx(GETMEMBERUSER,memberId).StructScan(&MemberUserInfo)
if err != nil {
service.WriteErr(err)
}
return MemberUserInfo
}
//处理基本的原始数据
func HandleData(MemberUserInfo model.MemberAddUserData) model.MemberAddUserData{
var saleId = 0
//查找交易员
err := dao.GetLiexinDb().QueryRowx("select sale_id from lie_order where user_id = ? order by create_time desc",MemberUserInfo.User_Id).Scan(&saleId)
if err != nil {
service.WriteErr(err)
}
if saleId != 0 {
MemberUserInfo.Sale_Id = saleId
}
// 个人转化为贸易商
if MemberUserInfo.Type_Id == 0 {
MemberUserInfo.Type_Id = 5
}
//来源
if MemberUserInfo.Create_Device != 2 {
MemberUserInfo.Source = 1
}else{
MemberUserInfo.Source = 2
}
// 客户身份
if MemberUserInfo.Work_Function != 0 {
MemberUserInfo.Customer_identity = MemberUserInfo.Work_Function
}
//获取oems数据
//抓取adtag和ptag,refer
adtag = regexp.MustCompile(AdtagRex).FindString(MemberUserInfo.Reg_Remark)
ptag = regexp.MustCompile(PtagRex).FindString(MemberUserInfo.Reg_Remark)
refer = regexp.MustCompile(ReferRex).FindString(MemberUserInfo.Reg_Remark)
if refer != ""{
refer = strings.Split(adtag,",")[0]
//如果是以上refer则为自营样片
if strings.Contains(refer,"sample") {
MemberUserInfo.Channel_source = 10
}
}
if ptag != "" {
ptag = strings.Split(adtag,",")[0]
MemberUserInfo.Ptag = strings.Split(ptag,",")[0]
switch ptag {
case "ptag=activity-140":
case "ptag=activity-141":
case "ptag=activity-143":
case "ptag=activity-144":
MemberUserInfo.Customer_identity = 2//如果是以上ptag则为采购用户
MemberUserInfo.Channel_source = 9//如果是以上ptag则为展会用户
break
case "ptag=activity-142":
case "ptag=activity-145":
MemberUserInfo.Customer_identity = 1//如果是以上ptag则为工程师
MemberUserInfo.Channel_source = 9//如果是以上ptag则为展会用户
break
case "ptag=sample":
case "ptag=sample-pop":
case "ptag=samplereg":
case "ptag=sample-stopnav":
MemberUserInfo.Channel_source = 10//如果是以上ptag则为自营样片
break
case "ptag=jr":
MemberUserInfo.Channel_source = 11//如果是以上ptag则为信用金融
break
case "ptag=edcp":
MemberUserInfo.Channel_source = 12//如果是以上ptag则为信用贷测评
break
}
}
if adtag != "" {
adtag = strings.Split(adtag,",")[0]
MemberUserInfo.Adtag = adtag
if adtag == "adtag=bps" {
MemberUserInfo.Channel_source = 13//如果是以上adtag则为白皮书下载用户
}
if adtag == "adtag=findchips" {
MemberUserInfo.Channel_source = 14//如果是以上adtagfindchips广告
}
}
//地址
if MemberUserInfo.Com_Province_Id != 0 && MemberUserInfo.Com_City_Id != 0 && MemberUserInfo.Com_Area_Id != 0 {
MemberUserInfo.Com_Full_addr = common.AllCity[strconv.Itoa(MemberUserInfo.Com_Province_Id)] + common.AllCity[strconv.Itoa(MemberUserInfo.Com_City_Id)] + common.AllCity[strconv.Itoa(MemberUserInfo.Com_Area_Id)] + MemberUserInfo.Com_Address
}
//oems信息
var oems model.OemsUserinfo
dao.GetDb().QueryRowx("select contract,contract_name,note,outter_uid from lie_oems_userinfo where outter_uid = ?",&oems.Outter_Uid)
if oems.Outter_Uid != 0 {
fmt.Println(oems)
if MemberUserInfo.Mobile == "" {
MemberUserInfo.Mobile = oems.Contact
}
MemberUserInfo.User_Name = oems.Contact_Name
MemberUserInfo.Channel_source = 8
MemberUserInfo.Remark = oems.Note
}
//判断是否下单
var orderId int
err = dao.GetLiexinDb().QueryRowx("select order_id from lie_order where user_id = ?",MemberUserInfo.User_Id).Scan(orderId);
if orderId != 0 {
MemberUserInfo.No_Create_Order = 2
}else{
MemberUserInfo.No_Create_Order = 1
}
return MemberUserInfo
}
\ No newline at end of file
package model
type AssignActive struct {
Id int `json:"id"`
User_Id int `json:"user_id"`
Turn_Out_id int `json:"turn_out_id"`
Turn_In_id int `json:"turn_in_id"`
Assign_id int `json:"assign_id"`
Is_Success int `json:"is_success"`
No_Create_Order int `json:"no_create_order"`
Change_Time int `json:"change_time"`
Create_time int `json:"create_time"`
}
/*
CREATE TABLE `lie_assign_active` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '转入接收日志',
`user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
`turn_out_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '转出人ID',
`turn_in_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '转入人ID',
`assign_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '分配人ID',
`is_success` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否成功',
`change_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '变更时间',
`create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COMMENT='转入接收日志表';
*/
\ No newline at end of file
package model
type Customer struct {
CustomerId int
ErpClientCode string
Name string
ErpId string
AddTime int
IsSynced int
}
package model
type Feedback struct {
User_Id int `json:"user_id"`
Outter_Uid int `json:"outter_uid"`
Ip int `json:"ip"`
Type int `json:"type"`
Mobile string `json:"mobile"`
Content string `json:"content"`
Source string `json:"source"`
Pf int `json:"pf"`
Status int `json:"status"`
Sale_Id int `json:"sale_id"`
Bom_Url string `json:"bom_url"`
Responses string `json:"responses"`
Contact_Name string `json:"contact_name"`
Company_Name string `json:"company_name"`
Company_Type int `json:"company_type"`
Note string `json:"note"`
Create_Time int `json:"create_time"`
}
/*
CREATE TABLE `lie_feedback` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '流水id',
`user_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '如果用登陆,则记录用户id',
`outter_uid` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT 'crm用户ID',
`ip` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'ip',
`type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '5.搜索无结果 6、多次搜索 7、快速找货 8、SEO落地页面反馈',
`mobile` char(16) NOT NULL DEFAULT '' COMMENT '手机号',
`content` varchar(255) NOT NULL DEFAULT ' ' COMMENT '反馈意见',
`source` varchar(100) NOT NULL DEFAULT ' ' COMMENT '页面来源',
`pf` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '1、pc 2.H5',
`status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '0为未处理,1已处理',
`sale_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '客服id',
`bom_url` varchar(255) NOT NULL DEFAULT ' ' COMMENT 'bom单excel存在OSS的地址链接',
`responses` varchar(255) NOT NULL DEFAULT ' ' COMMENT '回复内容',
`contact_name` varchar(80) NOT NULL DEFAULT ' ' COMMENT '联系名称',
`company_name` varchar(50) NOT NULL DEFAULT ' ' COMMENT '公司名称',
`company_type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '1代工厂 2终端 3代理商 4贸易商 5其它',
`note` varchar(100) NOT NULL DEFAULT ' ' COMMENT '备注',
`create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='意见反馈表';
*/
\ No newline at end of file
package model
type MemberAddUserData struct {
User_Id int `json:"user_id"`
Mobile string `json:"mobile"`
User_Name string `json:"user_name"`
Email string `json:"email"`
Reg_Remark string `json:"reg_remark"`
Remark string `json:"remark"`
Create_Device int `json:"create_device"`
Create_Time int `json:"create_time"`
Com_Id int `json:"com_id"`
Type_Id int `json:"type_id"`
Com_Name string `json:"ComName"`
Com_Desc string `json:"com_desc"`
Com_Province_Id int `json:"com_provicne_id"`
Com_City_Id int `json:"com_city_id"`
Com_Area_Id int `json:"com_area_id"`
Com_Address string `json:"com_address"`
Com_Telphone string `json:"com_telphone"`
Com_Fax string `json:"com_fax"`
Brand_List string `json:"brand_list"`
Work_Function int `json:"work_function"`
User_Type int `json:"user_type"`
Userinfo_Sale_Id int `json:"userinfo_sale_id"`
Sale_Id int `json:"sale_id"`
Adtag string `json:"adtag"`
Ptag string `json:"ptag"`
Com_Full_addr string `json:"com_full_addr"`
Channel_source int `json:"channel_source"`
Source int `json:"source"`
Customer_identity int `json:"customer_identity"`
No_Create_Order int `json:"no_create_order"`
}
\ No newline at end of file
package model
type NotFollowUser struct {
Id int `json:"id"`
User_Id int `json:"user_id"`
Sale_Id int `json:"sale_id"`
Stop_Time int `json:"Stop_time"`
Update_Time int `json:"Update_time"`
}
/*
CREATE TABLE `lie_not_follow_user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '客户ID',
`sale_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '交易员ID',
`stop_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '停止时间',
`update_time` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='客服不能跟进用户表';
*/
\ No newline at end of file
package model
type OemsUserinfo struct {
Outter_Uid int `json:"outter_uid"`
Contact string `json:"contact"`
Contact_Name string `json:"contact_name"`
Note string `json:"note"`
}
\ No newline at end of file
package model
type Salesman struct {
Id int `json:"id"`
User_Id int `json:"user_id"`
Sale_Id int `json:"sale_id"`
Assign_Time int `json:"assign_time"`
Update_Time int `json:"update_time"`
}
/*
CREATE TABLE `lie_salesman` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '客户ID',
`sale_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '交易员ID',
`assign_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '指派时间',
`update_time` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=utf8;
*/
\ No newline at end of file
package model
type UserCompany struct {
Com_name string `json:"com_name"`
}
\ No newline at end of file
package model
type UserInfo struct {
Mobile int64 `json:"mobile"`
}
\ No newline at end of file
package model
// Kratos hello kratos.
type Users struct {
User_id int64 `json:"user_id"`
}
\ No newline at end of file
package service
import (
"scm_server/internal/common"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
)
const APIMD5STR string = "fh6y5t4rr351d2c3bryi"
const APIDOMAIN string = "http://api.ichunt.com/msg/sendMessageByAuto"
const ADMINTEL int64 = 17600091664
func AdminErr(err error) {
if err != nil {
fmt.Println(err)
SendMessage(ADMINTEL,err.Error())
}
}
func SendMessage(mobile int64 , content string){
if mobile != 0 {
timeNow := time.Now().Unix()
requestContent,_ := json.Marshal(map[string]string{"content":content})
requestTel,_ := json.Marshal([]int64{mobile})
resp,err := http.PostForm(APIDOMAIN,url.Values{
"data" : {string(requestContent)},
"touser" : {string(requestTel)},
"keyword" : {"register_nopay_notify"},
"k1" : {strconv.FormatInt(int64(timeNow),10)},
"k2" : {common.Md5(common.Md5(strconv.FormatInt(int64(timeNow),10))+APIMD5STR)},
"is_ignore" : {},
})
if err != nil {
fmt.Print(err)
}
defer resp.Body.Close()
}
}
package service
import "fmt"
//错误日志
//错误类型
var ProGramErrType string = "default:"
//返回原声错误
func WriteErr(err error) {
if err != nil {
switch ProGramErrType {
default:
}
//屏幕打印,加上发送钉钉消息
fmt.Println(ProGramErrType+err.Error())
}
}
//返回详细错误
func WriteErrDetail(errString string) {
switch ProGramErrType {
default:
}
//屏幕打印,加上发送钉钉消息
fmt.Println(errString)
//SendMessage(ADMINTEL,ProGramErrType+errString)
}
\ No newline at end of file
package service
import (
"context"
"scm_server/internal/dao"
"scm_server/internal/model"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/pkg/errors"
)
// Service service.
type Service struct {
ac *paladin.Map
dao dao.Dao
}
// New new a service and return.
func New() (s *Service) {
var ac = new(paladin.TOML)
if err := paladin.Watch("application.toml", ac); err != nil {
panic(err)
}
s = &Service{
ac: ac,
dao: dao.New(),
}
return s
}
// Ping ping the resource.
func (s *Service) Ping(ctx context.Context) (err error) {
return s.dao.Ping(ctx)
}
// Close close the resource.
func (s *Service) Close() {
s.dao.Close()
}
//通过用户ID获取用户信息
func (s *Service) GetUserInfoByUserId(ctx context.Context, user_id int64) (res *model.Users, err error) {
if res, err = s.dao.GetUserInfoByUserId(ctx, user_id); err != nil {
err = errors.WithStack(err)
}
return
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment