huangjiajun 3 månader sedan
förälder
incheckning
5712b2b339
100 ändrade filer med 7127 tillägg och 0 borttagningar
  1. +2
    -0
      .gitignore
  2. +9
    -0
      .idea/community_team.iml
  3. +8
    -0
      .idea/modules.xml
  4. +6
    -0
      .idea/vcs.xml
  5. +37
    -0
      Dockerfile
  6. +39
    -0
      Dockerfile-prd
  7. +38
    -0
      Dockerfile-task
  8. +32
    -0
      Makefile
  9. +49
    -0
      README.md
  10. +122
    -0
      app/cfg/cfg_app.go
  11. +3
    -0
      app/cfg/cfg_cache_key.go
  12. +4
    -0
      app/cfg/cfg_task.go
  13. +9
    -0
      app/cfg/init_cache.go
  14. +9
    -0
      app/cfg/init_cache_second.go
  15. +81
    -0
      app/cfg/init_cfg.go
  16. +12
    -0
      app/cfg/init_es.go
  17. +20
    -0
      app/cfg/init_log.go
  18. +28
    -0
      app/cfg/init_rabbitmq.go
  19. +53
    -0
      app/cfg/init_task.go
  20. +105
    -0
      app/db/db.go
  21. +15
    -0
      app/db/db_cate.go
  22. +111
    -0
      app/db/db_cloud_bundle.go
  23. +1
    -0
      app/db/db_coupon.go
  24. +31
    -0
      app/db/db_goods.go
  25. +15
    -0
      app/db/db_goods_sku.go
  26. +72
    -0
      app/db/db_order.go
  27. +86
    -0
      app/db/db_store.go
  28. +120
    -0
      app/db/db_sys_cfg.go
  29. +688
    -0
      app/db/db_sys_mod.go
  30. +194
    -0
      app/db/db_sys_mod_format_img.go
  31. +395
    -0
      app/db/db_user.go
  32. +103
    -0
      app/db/db_user_fin_flow.go
  33. +226
    -0
      app/db/db_user_level.go
  34. +578
    -0
      app/db/db_user_profile.go
  35. +249
    -0
      app/db/db_user_relate.go
  36. +104
    -0
      app/db/dbs.go
  37. +232
    -0
      app/db/dbs_map.go
  38. +55
    -0
      app/db/dbs_sys_cfg.go
  39. +19
    -0
      app/db/model/cloud_bundle.go
  40. +10
    -0
      app/db/model/community_team_cate.go
  41. +27
    -0
      app/db/model/community_team_coupon.go
  42. +25
    -0
      app/db/model/community_team_coupon_user.go
  43. +29
    -0
      app/db/model/community_team_goods.go
  44. +37
    -0
      app/db/model/community_team_order.go
  45. +13
    -0
      app/db/model/community_team_order_info.go
  46. +20
    -0
      app/db/model/community_team_sku.go
  47. +24
    -0
      app/db/model/community_team_store.go
  48. +12
    -0
      app/db/model/community_team_store_like.go
  49. +18
    -0
      app/db/model/db_mapping.go
  50. +30
    -0
      app/db/model/fin_user_flow.go
  51. +7
    -0
      app/db/model/sys_cfg.go
  52. +35
    -0
      app/db/model/sys_module.go
  53. +28
    -0
      app/db/model/sys_popup.go
  54. +22
    -0
      app/db/model/sys_push_app.go
  55. +19
    -0
      app/db/model/sys_push_sms.go
  56. +17
    -0
      app/db/model/sys_push_template.go
  57. +18
    -0
      app/db/model/sys_push_user.go
  58. +20
    -0
      app/db/model/sys_template.go
  59. +37
    -0
      app/db/model/user.go
  60. +8
    -0
      app/db/model/user_app_domain.go
  61. +8
    -0
      app/db/model/user_app_list.go
  62. +23
    -0
      app/db/model/user_level.go
  63. +102
    -0
      app/db/model/user_profile.go
  64. +13
    -0
      app/db/model/user_relate.go
  65. +17
    -0
      app/db/model/virtual_coin.go
  66. +17
    -0
      app/db/model/virtual_coin_relate.go
  67. +44
    -0
      app/db/model/wx_applet_list.go
  68. +23
    -0
      app/db/offical/db_sys_cfg.go
  69. +15
    -0
      app/db/offical/db_user_app_list.go
  70. +9
    -0
      app/db/offical/model/master_list_cfg.go
  71. +7
    -0
      app/db/offical/model/sys_cfg.go
  72. +33
    -0
      app/db/offical/model/user_app_list.go
  73. +166
    -0
      app/db/wechat_applet_info.go
  74. +42
    -0
      app/db/zhimeng_db.go
  75. +244
    -0
      app/e/code.go
  76. +72
    -0
      app/e/error.go
  77. +212
    -0
      app/e/msg.go
  78. +8
    -0
      app/e/set_cache.go
  79. +190
    -0
      app/enum/enum_merchant_coupon_scheme.go
  80. +10
    -0
      app/hdl/hdl_cate.go
  81. +16
    -0
      app/hdl/hdl_goods.go
  82. +28
    -0
      app/hdl/hdl_order.go
  83. +37
    -0
      app/hdl/hdl_pay.go
  84. +29
    -0
      app/hdl/hdl_store.go
  85. +19
    -0
      app/hdl/hdl_store_order.go
  86. +334
    -0
      app/lib/alipay/api.go
  87. +148
    -0
      app/lib/arkid/api.go
  88. +6
    -0
      app/lib/arkid/base.go
  89. +24
    -0
      app/lib/arkid/init.go
  90. +62
    -0
      app/lib/arkid/model.go
  91. +165
    -0
      app/lib/arkid/sdk.go
  92. +25
    -0
      app/lib/auth/base.go
  93. +297
    -0
      app/lib/mob/api.go
  94. +15
    -0
      app/lib/mob/main.go
  95. +16
    -0
      app/lib/qiniu/bucket_create.go
  96. +18
    -0
      app/lib/qiniu/bucket_delete.go
  97. +18
    -0
      app/lib/qiniu/bucket_get_domain.go
  98. +22
    -0
      app/lib/qiniu/init.go
  99. +55
    -0
      app/lib/qiniu/req_img_upload.go
  100. +122
    -0
      app/lib/sms/sms.go

+ 2
- 0
.gitignore Visa fil

@@ -0,0 +1,2 @@
# Binaries for programs and plugins


+ 9
- 0
.idea/community_team.iml Visa fil

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

+ 8
- 0
.idea/modules.xml Visa fil

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/community_team.iml" filepath="$PROJECT_DIR$/.idea/community_team.iml" />
</modules>
</component>
</project>

+ 6
- 0
.idea/vcs.xml Visa fil

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

+ 37
- 0
Dockerfile Visa fil

@@ -0,0 +1,37 @@
# 多重构建,减少镜像大小
# 构建:使用golang:1.13版本
FROM registry.cn-shenzhen.aliyuncs.com/fnuoos-prd/golang:1.18.4 as build

# 容器环境变量添加,会覆盖默认的变量值
ENV GO111MODULE=on
ENV GOPROXY=https://goproxy.cn,direct
ENV TZ="Asia/Shanghai"
ENV PHONE_DATA_DIR="./static/bat"
# 设置工作区
WORKDIR /go/release

# 把全部文件添加到/go/release目录
ADD . .

# 编译:把main.go编译成可执行的二进制文件,命名为zyos
RUN GOOS=linux CGO_ENABLED=0 GOARCH=amd64 go build -tags netgo -ldflags="-s -w" -installsuffix cgo -o zyos main.go

FROM ubuntu:xenial as prod
LABEL maintainer="zengzhengrong"
ENV TZ="Asia/Shanghai"
ENV PHONE_DATA_DIR="./static/bat"

COPY static/html static/html
COPY static/bat static/bat
# 时区纠正
RUN rm -f /etc/localtime \
&& ln -sv /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone
# 在build阶段复制可执行的go二进制文件app
COPY --from=build /go/release/zyos ./zyos

COPY --from=build /go/release/etc/cfg.yml /var/zyos/cfg.yml

# 启动服务
CMD ["./zyos","-c","/var/zyos/cfg.yml"]


+ 39
- 0
Dockerfile-prd Visa fil

@@ -0,0 +1,39 @@
# 多重构建,减少镜像大小
# 构建:使用golang:1.18版本(直接使用自己从香港下载回来的镜像版本,提高打包速度)
FROM registry.cn-shenzhen.aliyuncs.com/fnuoos-prd/golang:1.18.4 as build

# 容器环境变量添加,会覆盖默认的变量值
ENV GO111MODULE=on
ENV GOPROXY=https://goproxy.cn,direct
ENV TZ="Asia/Shanghai"
ENV PHONE_DATA_DIR="./static/bat"
# 设置工作区
WORKDIR /go/release

# 把全部文件添加到/go/release目录
ADD . .

# 编译:把main.go编译成可执行的二进制文件,命名为zyos
RUN GOOS=linux CGO_ENABLED=0 GOARCH=amd64 go build -tags netgo -ldflags="-s -w" -installsuffix cgo -o zyos main.go

FROM ubuntu:xenial as prod
LABEL maintainer="zengzhengrong"
ENV TZ="Asia/Shanghai"
ENV PHONE_DATA_DIR="./static/bat"

COPY static/html static/html
COPY static/bat static/bat
# 时区纠正
RUN rm -f /etc/localtime \
&& ln -sv /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone
# 在build阶段复制可执行的go二进制文件app
COPY --from=build /go/release/zyos ./zyos

COPY --from=build /go/release/etc/cfg.yml /var/zyos/cfg.yml

# 启动服务
# CMD ["./zyos","-c","/var/zyos/cfg.yml"]
CMD ["bash","-c","sysctl -w net.ipv4.tcp_tw_reuse=1 && sysctl -w net.ipv4.tcp_fin_timeout=10 && sysctl -w net.ipv4.ip_local_port_range='1024 65535' && sysctl -p && ./zyos -c /var/zyos/cfg.yml"]



+ 38
- 0
Dockerfile-task Visa fil

@@ -0,0 +1,38 @@
# 多重构建,减少镜像大小
# 构建:使用golang:1.15版本
FROM registry.cn-shenzhen.aliyuncs.com/fnuoos-prd/golang:1.18.4 as build

# 容器环境变量添加,会覆盖默认的变量值
ENV GO111MODULE=on
ENV GOPROXY=https://goproxy.cn,direct
ENV TZ="Asia/Shanghai"
ENV PHONE_DATA_DIR="./static/bat"
# 设置工作区
WORKDIR /go/release

# 把全部文件添加到/go/release目录
ADD . .

# 编译:把main.go编译成可执行的二进制文件,命名为zyos
RUN GOOS=linux CGO_ENABLED=0 GOARCH=amd64 go build -tags netgo -ldflags="-s -w" -installsuffix cgo -o zyos_order_task cmd/task/main.go

FROM ubuntu:xenial as prod
LABEL maintainer="zengzhengrong"
ENV TZ="Asia/Shanghai"
ENV PHONE_DATA_DIR="./static/bat"

COPY static/html static/html
COPY static/bat static/bat

# 时区纠正
RUN rm -f /etc/localtime \
&& ln -sv /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone
# 在build阶段复制可执行的go二进制文件app
COPY --from=build /go/release/zyos_order_task ./zyos_order_task

COPY --from=build /go/release/etc/task.yml /var/zyos/task.yml

# 启动服务
CMD ["./zyos_order_task","-c","/var/zyos/task.yml"]


+ 32
- 0
Makefile Visa fil

@@ -0,0 +1,32 @@
.PHONY: build clean tool lint help

APP=applet

all: build

build:
go build -o ./bin/$(APP) ./cmd/main.go

lite:
go build -ldflags "-s -w" -o ./bin/$(APP) ./cmd/main.go

install:
#@go build -v .
go install ./cmd/...

tool:
go vet ./...; true
gofmt -w .

lint:
golint ./...

clean:
rm -rf go-gin-example
go clean -i .

help:
@echo "make: compile packages and dependencies"
@echo "make tool: run specified go tool"
@echo "make lint: golint ./..."
@echo "make clean: remove object files and cached files"

+ 49
- 0
README.md Visa fil

@@ -0,0 +1,49 @@
# applet

## 要看 nginx.conf 和 wap conf

## 层级介绍

- hdl 做接收数据的报错, 数据校验
- svc 做数据处理的报错, 数据转换
- lib 只抛出错误给hdl或者svc进行处理, 不做数据校验
- db 可以处理db错误,其它错误返回给svc进行处理
- mw 中间件
- md 结构体

#### 介绍

基于gin的接口小程序

#### 软件架构

软件架构说明

#### 安装教程

1. xxxx
2. xxxx
3. xxxx

#### 使用说明

1. xxxx
2. xxxx
3. xxxx

#### 参与贡献

1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request

## swagger

```
// 参考:https://segmentfault.com/a/1190000013808421
// 安装命令行
go get -u github.com/swaggo/swag/cmd/swag
// 生成
swag init
```

+ 122
- 0
app/cfg/cfg_app.go Visa fil

@@ -0,0 +1,122 @@
package cfg

import (
"time"
)

type Config struct {
Debug bool `yaml:"debug"`
Prd bool `yaml:"prd"`
CurlDebug bool `yaml:"curldebug"`
SrvAddr string `yaml:"srv_addr"`
RedisAddr string `yaml:"redis_addr"`
RedisAddrSecond RedisAddrSeconds `yaml:"redis_addr_second"`
DB DBCfg `yaml:"db"`
MQ MQCfg `yaml:"mq"`
ES ESCfg `yaml:"es"`
Log LogCfg `yaml:"log"`
ArkID ArkIDCfg `yaml:"arkid"`
Admin AdminCfg `yaml:"admin"`
Official OfficialCfg `yaml:"official"`
WebsiteBackend WebsiteBackendCfg `yaml:"website_backend"`
WxappletFilepath WxappletFilepathCfg `yaml:"wxapplet_filepath"`
H5Filepath H5FilepathCfg `yaml:"h5_filepath"`
ImBusinessRpc ImBusinessRpcCfg `yaml:"im_business_rpc"`
Local bool
AppComm AppCommCfg `yaml:"app_comm"`
Zhimeng ZhimengCfg `yaml:"zm"`
Supply SupplyCfg `yaml:"supply"`
ZhiosOpen ZhiosOpenCfg `yaml:"zhios_open"`
ZhimengDB DBCfg `yaml:"zhimeng_db"`
}
type RedisAddrSeconds struct {
Addr string `json:"addr"`
Pwd string `json:"pwd"`
}
type ZhiosOpenCfg struct {
URL string `yaml:"url"`
}
type ImBusinessRpcCfg struct {
URL string `yaml:"url"`
PORT string `yaml:"port"`
}

// 公共模块
type AppCommCfg struct {
URL string `yaml:"url"`
}
type SupplyCfg struct {
URL string `yaml:"url"`
}
type ZhimengCfg struct {
URL string `yaml:"url"`
}

// OfficialCfg is 官网

type OfficialCfg struct {
URL string `yaml:"url"`
}
type WxappletFilepathCfg struct {
URL string `yaml:"url"`
}
type H5FilepathCfg struct {
URL string `yaml:"url"`
}
type WebsiteBackendCfg struct {
URL string `yaml:"url"`
}

// AdminCfg is 后台接口调用需要
type AdminCfg struct {
URL string `yaml:"url"`
IURL string `yaml:"iurl"`
AesKey string `yaml:"api_aes_key"`
AesIV string `yaml:"api_aes_iv"`
}

type ArkIDCfg struct {
Admin string `yaml:"admin"`
AdminPassword string `yaml:"admin_password"`
Url string `yaml:"url`
}

//数据库配置结构体
type DBCfg struct {
Host string `yaml:"host"` //ip及端口
Name string `yaml:"name"` //库名
User string `yaml:"user"` //用户
Psw string `yaml:"psw"` //密码
ShowLog bool `yaml:"show_log"` //是否显示SQL语句
MaxLifetime time.Duration `yaml:"max_lifetime"`
MaxOpenConns int `yaml:"max_open_conns"`
MaxIdleConns int `yaml:"max_idle_conns"`
Path string `yaml:"path"` //日志文件存放路径
}

type MQCfg struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
User string `yaml:"user"`
Pwd string `yaml:"pwd"`
}
type ESCfg struct {
Url string `yaml:"url"`
User string `yaml:"user"`
Pwd string `yaml:"pwd"`
}

//日志配置结构体
type LogCfg struct {
AppName string `yaml:"app_name" `
Level string `yaml:"level"`
IsStdOut bool `yaml:"is_stdout"`
TimeFormat string `yaml:"time_format"` // second, milli, nano, standard, iso,
Encoding string `yaml:"encoding"` // console, json

IsFileOut bool `yaml:"is_file_out"`
FileDir string `yaml:"file_dir"`
FileName string `yaml:"file_name"`
FileMaxSize int `yaml:"file_max_size"`
FileMaxAge int `yaml:"file_max_age"`
}

+ 3
- 0
app/cfg/cfg_cache_key.go Visa fil

@@ -0,0 +1,3 @@
package cfg

// 统一管理缓存

+ 4
- 0
app/cfg/cfg_task.go Visa fil

@@ -0,0 +1,4 @@
package cfg

type TaskConfig struct {
}

+ 9
- 0
app/cfg/init_cache.go Visa fil

@@ -0,0 +1,9 @@
package cfg

import (
"applet/app/utils/cache"
)

func InitCache() {
cache.NewRedis(RedisAddr)
}

+ 9
- 0
app/cfg/init_cache_second.go Visa fil

@@ -0,0 +1,9 @@
package cfg

import (
"applet/app/utils/cachesecond"
)

func InitCacheSecond() {
cachesecond.NewRedis(RedisAddrSecond.Addr, RedisAddrSecond.Pwd)
}

+ 81
- 0
app/cfg/init_cfg.go Visa fil

@@ -0,0 +1,81 @@
package cfg

import (
"flag"
"io/ioutil"

"gopkg.in/yaml.v2"
)

//配置文件数据,全局变量
var (
Debug bool
Prd bool
CurlDebug bool
SrvAddr string
RedisAddr string
RedisAddrSecond *RedisAddrSeconds
DB *DBCfg
MQ *MQCfg
ES *ESCfg
Log *LogCfg
ArkID *ArkIDCfg
Admin *AdminCfg
Official *OfficialCfg
WxappletFilepath *WxappletFilepathCfg
H5Filepath *H5FilepathCfg
Local bool
AppComm *AppCommCfg
Zhimeng *ZhimengCfg
WebsiteBackend *WebsiteBackendCfg
Supply *SupplyCfg
ImBusinessRpc *ImBusinessRpcCfg
ZhiosOpen *ZhiosOpenCfg
ZhimengDB *DBCfg
)

//初始化配置文件,将cfg.yml读入到内存
func InitCfg() {
//用指定的名称、默认值、使用信息注册一个string类型flag。
path := flag.String("c", "etc/cfg.yml", "config file")
//解析命令行参数写入注册的flag里。
//解析之后,flag的值可以直接使用。
flag.Parse()
var (
c []byte
err error
conf *Config
)
if c, err = ioutil.ReadFile(*path); err != nil {
panic(err)
}
//yaml.Unmarshal反序列化映射到Config
if err = yaml.Unmarshal(c, &conf); err != nil {
panic(err)
}
//数据读入内存
Prd = conf.Prd
Debug = conf.Debug
Local = conf.Local
CurlDebug = conf.CurlDebug
DB = &conf.DB
MQ = &conf.MQ
Log = &conf.Log
ArkID = &conf.ArkID
RedisAddr = conf.RedisAddr
RedisAddrSecond = &conf.RedisAddrSecond
SrvAddr = conf.SrvAddr
Admin = &conf.Admin
Official = &conf.Official
WxappletFilepath = &conf.WxappletFilepath
AppComm = &conf.AppComm
Zhimeng = &conf.Zhimeng
Supply = &conf.Supply
H5Filepath = &conf.H5Filepath
WebsiteBackend = &conf.WebsiteBackend
ImBusinessRpc = &conf.ImBusinessRpc
ES = &conf.ES
ZhiosOpen = &conf.ZhiosOpen
ZhimengDB = &conf.ZhimengDB

}

+ 12
- 0
app/cfg/init_es.go Visa fil

@@ -0,0 +1,12 @@
package cfg

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es"
"encoding/json"
)

func InitEs() {
data, _ := json.Marshal(ES)
filePutContents("init_es", string(data))
es.Init(ES.Url, ES.User, ES.Pwd)
}

+ 20
- 0
app/cfg/init_log.go Visa fil

@@ -0,0 +1,20 @@
package cfg

import "applet/app/utils/logx"

func InitLog() {
logx.InitDefaultLogger(&logx.LogConfig{
AppName: Log.AppName,
Level: Log.Level,
StacktraceLevel: "error",
IsStdOut: Log.IsStdOut,
TimeFormat: Log.TimeFormat,
Encoding: Log.Encoding,
IsFileOut: Log.IsFileOut,
FileDir: Log.FileDir,
FileName: Log.FileName,
FileMaxSize: Log.FileMaxSize,
FileMaxAge: Log.FileMaxAge,
Skip: 2,
})
}

+ 28
- 0
app/cfg/init_rabbitmq.go Visa fil

@@ -0,0 +1,28 @@
package cfg

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit"
"encoding/json"
"os"
"strings"
"time"
)

func InitMq() {
data, _ := json.Marshal(MQ)
filePutContents("init_rabbit_mq", string(data))
err := rabbit.Init(MQ.Host, MQ.Port, MQ.User, MQ.Pwd)
if err != nil {
filePutContents("init_rabbit_mq", err.Error())
return
}
}

func filePutContents(fileName string, content string) {
fd, _ := os.OpenFile("./tmp/"+fileName+".log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
fd_time := time.Now().Format("2006-01-02 15:04:05")
fd_content := strings.Join([]string{"[", fd_time, "] ", content, "\n"}, "")
buf := []byte(fd_content)
fd.Write(buf)
fd.Close()
}

+ 53
- 0
app/cfg/init_task.go Visa fil

@@ -0,0 +1,53 @@
package cfg

import (
"flag"
"io/ioutil"

"gopkg.in/yaml.v2"

mc "applet/app/utils/cache/cache"
"applet/app/utils/logx"
)

func InitTaskCfg() {
path := flag.String("c", "etc/task.yml", "config file")
flag.Parse()
var (
c []byte
err error
conf *Config
)
if c, err = ioutil.ReadFile(*path); err != nil {
panic(err)
}
if err = yaml.Unmarshal(c, &conf); err != nil {
panic(err)
}
Prd = conf.Prd
Debug = conf.Debug
DB = &conf.DB
MQ = &conf.MQ
ES = &conf.ES
Log = &conf.Log
Admin = &conf.Admin
RedisAddr = conf.RedisAddr
RedisAddrSecond = &conf.RedisAddrSecond
Local = conf.Local
AppComm = &conf.AppComm
Zhimeng = &conf.Zhimeng
Supply = &conf.Supply
ZhiosOpen = &conf.ZhiosOpen
ZhimengDB = &conf.ZhimengDB

}

var MemCache mc.Cache

func InitMemCache() {
var err error
MemCache, err = mc.NewCache("memory", `{"interval":60}`)
if err != nil {
logx.Fatal(err.Error())
}
}

+ 105
- 0
app/db/db.go Visa fil

@@ -0,0 +1,105 @@
package db

import (
"fmt"
"os"
"time"

_ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic
"xorm.io/xorm"
"xorm.io/xorm/log"

"applet/app/cfg"
"applet/app/utils/logx"
)

var Db *xorm.Engine

// 根据DB配置文件初始化数据库
func InitDB(c *cfg.DBCfg) error {
var (
err error
f *os.File
)
//创建Orm引擎
if Db, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil {
return err
}
Db.SetConnMaxLifetime(c.MaxLifetime * time.Second) //设置最长连接时间
Db.SetMaxOpenConns(c.MaxOpenConns) //设置最大打开连接数
Db.SetMaxIdleConns(c.MaxIdleConns) //设置连接池的空闲数大小
if err = Db.Ping(); err != nil { //尝试ping数据库
return err
}
if c.ShowLog { //根据配置文件设置日志
Db.ShowSQL(true) //设置是否打印sql
Db.Logger().SetLevel(0) //设置日志等级
//修改日志文件存放路径文件名是%s.log
path := fmt.Sprintf(c.Path, c.Name)
f, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
os.RemoveAll(c.Path)
if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil {
return err
}
}
logger := log.NewSimpleLogger(f)
logger.ShowSQL(true)
Db.SetLogger(logger)
}
return nil
}

/********************************************* 公用方法 *********************************************/

// 数据批量插入
func DbInsertBatch(Db *xorm.Engine, m ...interface{}) error {
if len(m) == 0 {
return nil
}
id, err := Db.Insert(m...)
if id == 0 || err != nil {
return logx.Warn("cannot insert data :", err)
}
return nil
}

// QueryNativeString 查询原生sql
func QueryNativeString(Db *xorm.Engine, sql string, args ...interface{}) ([]map[string]string, error) {
results, err := Db.SQL(sql, args...).QueryString()
return results, err
}
func QueryNativeStringWithSess(sess *xorm.Session, sql string, args ...interface{}) ([]map[string]string, error) {
results, err := sess.SQL(sql, args...).QueryString()
return results, err
}

// UpdateComm common update
func UpdateComm(Db *xorm.Engine, id interface{}, model interface{}) (int64, error) {
row, err := Db.ID(id).Update(model)
return row, err
}

// InsertComm common insert
func InsertComm(Db *xorm.Engine, model interface{}) (int64, error) {
row, err := Db.InsertOne(model)
return row, err
}

// InsertCommWithSession common insert
func InsertCommWithSession(session *xorm.Session, model interface{}) (int64, error) {
row, err := session.InsertOne(model)
return row, err
}

// GetComm
// payload *model
// return *model,has,err
func GetComm(Db *xorm.Engine, model interface{}) (interface{}, bool, error) {
has, err := Db.Get(model)
if err != nil {
_ = logx.Warn(err)
return nil, false, err
}
return model, has, nil
}

+ 15
- 0
app/db/db_cate.go Visa fil

@@ -0,0 +1,15 @@
package db

import (
"applet/app/db/model"
"xorm.io/xorm"
)

func GetCate(eg *xorm.Engine, storeId string) *[]model.CommunityTeamCate {
var data []model.CommunityTeamCate
err := eg.Where("is_show=1 and uid=?", storeId).OrderBy("sort desc,id desc").Find(&data)
if err != nil {
return nil
}
return &data
}

+ 111
- 0
app/db/db_cloud_bundle.go Visa fil

@@ -0,0 +1,111 @@
package db

import (
"applet/app/db/model"
"applet/app/md"
"errors"
"fmt"
"github.com/gin-gonic/gin"

"xorm.io/xorm"
)

// GetCloudBundleByVersion is 根据版本 获取打包记录
func GetCloudBundleByVersion(Db *xorm.Engine, appverison string, os, ep int) (*model.CloudBundle, error) {
m := new(model.CloudBundle)
has, err := Db.Where("version = ? and os = ? and template_during_audit<>'' and ep=?", appverison, os, ep).Get(m)
if err != nil {
return nil, err
}
if !has {
return nil, errors.New("not Found")
}
return m, nil
}

// GetCloudBundleByVersionPlatform is 根据版本\os 获取打包记录
func GetCloudBundleByVersionPlatform(Db *xorm.Engine, appverison string, platform string, appType string) (*model.CloudBundle, error) {
m := new(model.CloudBundle)
var tag int
var ep = 0
if platform == "ios" {
tag = 2
} else {
tag = 1
}
if appType == "daogou" || appType == "" {
ep = 0
} else {
ep = 1
}
has, err := Db.Where("version = ? and os=? and ep=?", appverison, tag, ep).Desc("build_number").Get(m)
if err != nil {
return nil, err
}
if !has {
return nil, errors.New("not Found")
}
return m, nil
}

// GetCloudBundleByVersionPlatformWithAudit is 根据版本\os 获取打包记录
func GetCloudBundleByVersionPlatformWithAudit(Db *xorm.Engine, appverison string, platform string, appType string) (*model.CloudBundle, error) {
m := new(model.CloudBundle)
var tag int
var ep = 0
if platform == "ios" {
tag = 2
} else {
tag = 1
}
if appType == "daogou" || appType == "" {
ep = 0
} else {
ep = 1
}
has, err := Db.Where("version = ? and os=? and ep=? and template_during_audit<>''", appverison, tag, ep).Desc("build_number").Get(m)
if err != nil {
return nil, err
}
if !has {
return nil, errors.New("not Found")
}
return m, nil
}
func GetCloudBuild(c *gin.Context, platform string) string {
appVersion := c.GetHeader("app_version_name")
ep := 0
if c.GetString("app_type") != "" && c.GetString("app_type") != "daogou" {
ep = 1
}
if platform == "" {
platform = c.GetHeader("platform")
}

version := ""
os := 0
switch platform {
case md.PLATFORM_ANDROID:
if ep == 1 {
version = SysCfgGet(c, "biz_android_audit_version")
} else {
version = SysCfgGet(c, "android_audit_version")
}
os = 1
case md.PLATFORM_IOS:
if ep == 1 {
version = SysCfgGet(c, "biz_ios_audit_version")
} else {
version = SysCfgGet(c, "ios_audit_version")
}
os = 2
}
var data model.CloudBundle
get, err := DBs[c.GetString("mid")].Where("is_auditing=1 and os=? and ep=? and version=?", os, ep, appVersion).Get(&data)
fmt.Println(get)
fmt.Println(err)
if data.Version != "" {
version = data.Version
}
return version
}

+ 1
- 0
app/db/db_coupon.go Visa fil

@@ -0,0 +1 @@
package db

+ 31
- 0
app/db/db_goods.go Visa fil

@@ -0,0 +1,31 @@
package db

import (
"applet/app/db/model"
"applet/app/utils"
"xorm.io/xorm"
)

func GetGoods(eg *xorm.Engine, arg map[string]string) *[]model.CommunityTeamGoods {
var data []model.CommunityTeamGoods
sess := eg.Where("store_type=0 and state=0")
if arg["cid"] != "" {
sess.And("cid=?", arg["cid"])
}
limit := utils.StrToInt(arg["size"])
start := (utils.StrToInt(arg["p"]) - 1) * limit
err := sess.OrderBy("sale_count desc,id desc").Limit(limit, start).Find(&data)
if err != nil {
return nil
}
return &data
}

func GetGoodsSess(sess *xorm.Session, id int) *model.CommunityTeamGoods {
var data model.CommunityTeamGoods
get, err := sess.Where("id=?", id).Get(&data)
if get == false || err != nil {
return nil
}
return &data
}

+ 15
- 0
app/db/db_goods_sku.go Visa fil

@@ -0,0 +1,15 @@
package db

import (
"applet/app/db/model"
"xorm.io/xorm"
)

func GetGoodsSku(eg *xorm.Engine, goodsId string) *[]model.CommunityTeamSku {
var data []model.CommunityTeamSku
err := eg.Where("goods_id=?", goodsId).Find(&data)
if err != nil {
return nil
}
return &data
}

+ 72
- 0
app/db/db_order.go Visa fil

@@ -0,0 +1,72 @@
package db

import (
"applet/app/db/model"
"applet/app/utils"
"xorm.io/xorm"
)

func GetOrderEg(eg *xorm.Engine, oid string) *model.CommunityTeamOrder {
var data model.CommunityTeamOrder
get, err := eg.Where("oid=?", oid).Get(&data)
if get == false || err != nil {
return nil
}
return &data
}
func GetOrder(sess *xorm.Session, oid string) *model.CommunityTeamOrder {
var data model.CommunityTeamOrder
get, err := sess.Where("oid=?", oid).Get(&data)
if get == false || err != nil {
return nil
}
return &data
}
func GetOrderInfo(sess *xorm.Session, oid string) *[]model.CommunityTeamOrderInfo {
var data []model.CommunityTeamOrderInfo
err := sess.Where("oid=?", oid).Find(&data)
if err != nil {
return nil
}
return &data
}
func GetOrderInfoAllEg(eg *xorm.Engine, oid string) *[]model.CommunityTeamOrderInfo {
var data []model.CommunityTeamOrderInfo
err := eg.Where("oid=?", oid).Find(&data)
if err != nil {
return nil
}
return &data
}
func GetOrderInfoEg(eg *xorm.Engine, oid string) *model.CommunityTeamOrderInfo {
var data model.CommunityTeamOrderInfo
get, err := eg.Where("oid=?", oid).Asc("id").Get(&data)
if get == false || err != nil {
return nil
}
return &data
}

func GetOrderList(eg *xorm.Engine, arg map[string]string) *[]model.CommunityTeamOrder {
var data []model.CommunityTeamOrder
sess := eg.Where("1=1")
if arg["uid"] != "" {
sess.And("uid=?", arg["uid"])
}
if arg["state"] != "" {
sess.And("state=?", arg["state"])
}
if arg["store_uid"] != "" {
sess.And("store_uid=?", arg["store_uid"])
}
if arg["code"] != "" {
sess.And("code=?", arg["code"])
}
limit := utils.StrToInt(arg["size"])
start := (utils.StrToInt(arg["p"]) - 1) * limit
err := sess.OrderBy("id desc").Limit(limit, start).Find(&data)
if err != nil {
return nil
}
return &data
}

+ 86
- 0
app/db/db_store.go Visa fil

@@ -0,0 +1,86 @@
package db

import (
"applet/app/db/model"
"applet/app/utils"
"fmt"
"xorm.io/xorm"
)

func GetStore(eg *xorm.Engine, arg map[string]string) []map[string]string {
lng := utils.StrToFloat64(arg["lng"])
lat := utils.StrToFloat64(arg["lat"])
sel := ` *,sqrt( ( (( %f - lng)*PI()*12656*cos((( %f +lat)/2)*PI()/180)/180) * (( %f - lng)*PI()*12656*cos (((%f+lat)/2)*PI()/180)/180) ) + ( ((%f-lat)*PI()*12656/180) * ((%f-lat)*PI()*12656/180) ) ) AS km`
sel = fmt.Sprintf(sel, lng, lat, lng, lat, lat, lat)
sql := `select %s from community_team_store where %s %s`
where := "1=1"
if arg["parent_uid"] != "" {
where += " and store_type=2 and parent_uid=" + arg["parent_uid"]
} else if arg["uid"] != "" {
where += " and store_type=1 and uid=" + arg["parent_uid"]
} else {
where += " and store_type=" + arg["store_type"]
}
if arg["city"] != "" {
where += " and city='" + arg["city"] + "'"
}
if arg["name"] != "" {
where += " and name like '%" + arg["name"] + "'"
}
start := (utils.StrToInt(arg["p"]) - 1) * utils.StrToInt(arg["size"])
group := " order by %s limit " + utils.IntToStr(start) + "," + arg["size"]
groupStr := "fan desc,km asc,id asc"
if arg["cid"] == "1" {
groupStr = "km asc,id asc"
}
group = fmt.Sprintf(group, groupStr)
sql = fmt.Sprintf(sql, sel, where, group)
fmt.Println(sql)
nativeString, _ := QueryNativeString(eg, sql)
return nativeString
}
func GetStoreLike(eg *xorm.Engine, arg map[string]string) []map[string]string {
lng := utils.StrToFloat64(arg["lng"])
lat := utils.StrToFloat64(arg["lat"])
sel := ` cts.*,sqrt( ( (( %f - cts.lng)*PI()*12656*cos((( %f +cts.lat)/2)*PI()/180)/180) * (( %f - cts.lng)*PI()*12656*cos (((%f+cts.lat)/2)*PI()/180)/180) ) + ( ((%f-cts.lat)*PI()*12656/180) * ((%f-cts.lat)*PI()*12656/180) ) ) AS km`
sel = fmt.Sprintf(sel, lng, lat, lng, lat, lat, lat)
sql := `select %s from community_team_store_like ctsl
left join community_team_store cts on ctsl.store_id=cts.id
where %s %s`
where := "cts.state=1"
if arg["parent_uid"] != "" {
where += " and cts.store_type=2 and cts.parent_uid=" + arg["parent_uid"]
} else if arg["uid"] != "" {
where += " and cts.store_type=1 and cts.uid=" + arg["parent_uid"]
} else {
where += " and cts.store_type=" + arg["store_type"]
}
if arg["city"] != "" {
where += " and cts.city='" + arg["city"] + "'"
}
if arg["name"] != "" {
where += " and cts.name like '%" + arg["name"] + "'"
}
start := (utils.StrToInt(arg["p"]) - 1) * utils.StrToInt(arg["size"])
group := " order by km asc,cts.id asc limit " + utils.IntToStr(start) + "," + arg["size"]
sql = fmt.Sprintf(sql, sel, where, group)
fmt.Println(sql)
nativeString, _ := QueryNativeString(eg, sql)
return nativeString
}
func GetStoreId(sess *xorm.Session, id string) *model.CommunityTeamStore {
var data model.CommunityTeamStore
get, err := sess.Where("id=?", id).Get(&data)
if get == false || err != nil {
return nil
}
return &data
}
func GetStoreIdEg(eg *xorm.Engine, id string) *model.CommunityTeamStore {
var data model.CommunityTeamStore
get, err := eg.Where("id=?", id).Get(&data)
if get == false || err != nil {
return nil
}
return &data
}

+ 120
- 0
app/db/db_sys_cfg.go Visa fil

@@ -0,0 +1,120 @@
package db

import (
"applet/app/db/model"
"applet/app/md"
"applet/app/utils/cache"
"applet/app/utils/logx"
"fmt"
"xorm.io/xorm"
)

// 系统配置get
func SysCfgGetAll(Db *xorm.Engine) (*[]model.SysCfg, error) {
var cfgList []model.SysCfg
if err := Db.Cols("key,val,memo").Find(&cfgList); err != nil {
return nil, logx.Error(err)
}
return &cfgList, nil
}

// 获取一条记录
func SysCfgGetOne(Db *xorm.Engine, key string) (*model.SysCfg, error) {
var cfgList model.SysCfg
if has, err := Db.Where("`key`=?", key).Get(&cfgList); err != nil || has == false {
return nil, logx.Error(err)
}
return &cfgList, nil
}
func SysCfgGetOneData(Db *xorm.Engine, key string) string {
var cfgList model.SysCfg
if has, err := Db.Where("`key`=?", key).Get(&cfgList); err != nil || has == false {
return ""
}
return cfgList.Val
}

// 返回最后插入id
func SysCfgInsert(Db *xorm.Engine, key, val, memo string) bool {
cfg := model.SysCfg{Key: key, Val: val, Memo: memo}
_, err := Db.InsertOne(&cfg)
if err != nil {
logx.Error(err)
return false
}
return true
}

func SysCfgUpdate(Db *xorm.Engine, key, val, memo string) bool {
cfg := model.SysCfg{Key: key, Val: val, Memo: memo}
_, err := Db.Where("`key`=?", key).Cols("val,memo").Update(&cfg)
if err != nil {
logx.Error(err)
return false
}
return true
}

// 单条记录获取DB
func SysCfgGetWithDb(eg *xorm.Engine, masterId string, HKey string) string {
cacheKey := fmt.Sprintf(md.AppCfgCacheKey, masterId) + HKey
get, err := cache.GetString(cacheKey)
if err != nil || get == "" {
cfg, err := SysCfgGetOne(eg, HKey)
if err != nil || cfg == nil {
_ = logx.Error(err)
return ""
}

// key是否存在
cacheKeyExist := false
if cache.Exists(cacheKey) {
cacheKeyExist = true
}

// 设置缓存
_, err = cache.SetEx(cacheKey, cfg.Val, 30)
if err != nil {
_ = logx.Error(err)
return ""
}
if !cacheKeyExist { // 如果是首次设置 设置过期时间
_, err := cache.Expire(cacheKey, md.CfgCacheTime)
if err != nil {
_ = logx.Error(err)
return ""
}
}
return cfg.Val
}
return get
}
func SysCfgGetWithStr(eg *xorm.Engine, masterId string, HKey string) string {

cfg, err := SysCfgGetOne(eg, HKey)
if err != nil || cfg == nil {
_ = logx.Error(err)
return ""
}
return cfg.Val
}

// 多条记录获取DB
func SysCfgFindWithDb(eg *xorm.Engine, masterId string, keys ...string) map[string]string {
res := map[string]string{}
//TODO::判断keys长度(大于10个直接查数据库)
if len(keys) > 10 {
cfgList, _ := SysCfgGetAll(eg)
if cfgList == nil {
return nil
}
for _, v := range *cfgList {
res[v.Key] = v.Val
}
} else {
for _, key := range keys {
res[key] = SysCfgGetWithDb(eg, masterId, key)
}
}
return res
}

+ 688
- 0
app/db/db_sys_mod.go Visa fil

@@ -0,0 +1,688 @@
package db

import (
"applet/app/db/model"
"applet/app/e"
"applet/app/utils"
"applet/app/utils/logx"
"errors"
"fmt"
"strconv"
"strings"

"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
"xorm.io/xorm"
)

// 返回所有, 不管是否显示
func SysModFindAll(Db *xorm.Engine) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.Find(&m); err != nil {
return nil, err
}
return &m, nil
}

// 查找主模块数据
func SysModFindMain(Db *xorm.Engine) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.Where("mod_pid = 0 AND state = 1 AND position = 'base'").
Asc("sort").
Find(&m); err != nil {
return nil, err
}
return &m, nil
}

// 用父ID查找子模块数据
func SysModFindByPId(c *gin.Context, Db *xorm.Engine, id int) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.Where("state = 1").Where("mod_pid = ?", id).
Asc("sort").
Find(&m); err != nil {
return nil, err
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
var ms []model.SysModule
modname_list := []string{"product", "search_result_taobao_item", "hot_rank_tab_view"}
for _, item := range *mm.(*[]model.SysModule) {
if item.ModName == "product_detail_title" {
if strings.Contains(item.Data, "tmall") == false {
item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"天猫\",\"type\":\"tmall\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
}
if strings.Contains(item.Data, "kuaishou") == false {
item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"快手\",\"type\":\"kuaishou\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
}
if strings.Contains(item.Data, "tikTok") == false {
item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"抖音\",\"type\":\"tikTok\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
}
}

if strings.Contains(item.Data, "tmall") == false && utils.InArr(item.ModName, modname_list) {
item.Data = strings.Replace(item.Data, "{\"index\":\"6\",\"type\":\"kaola\",\"platform_name\":\"考拉\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", "{\"index\":\"6\",\"type\":\"kaola\",\"platform_name\":\"考拉\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"},{\"index\":\"7\",\"type\":\"tmall\",\"platform_name\":\"天猫\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", 1)
item.Data = strings.Replace(item.Data, "{\"type\":\"kaola\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", "{\"type\":\"kaola\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"},{\"type\":\"tmall\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", 1)
}
if strings.Contains(item.Data, "优惠卷") {
item.Data = strings.Replace(item.Data, "优惠卷", "优惠券", -1)
}
item.Data = strings.ReplaceAll(item.Data, "\\/", "/")
item.Data = strings.ReplaceAll(item.Data, "\\u0026", "&")

ms = append(ms, item)
}
return &ms, nil
}

// 用父ID查找子模块数据
func SysModFindByPIds(c *gin.Context, Db *xorm.Engine, ids ...int) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.In("mod_pid", ids).Where("state = 1").
Asc("sort").
Find(&m); err != nil {
return nil, err
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
var ms []model.SysModule
for _, item := range *mm.(*[]model.SysModule) {
//数据里面
if strings.Contains(item.Data, "tmall") == false && item.ModName == "product" {
item.Data = strings.Replace(item.Data, "{\"index\":\"6\",\"type\":\"kaola\",\"platform_name\":\"考拉\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", "{\"index\":\"6\",\"type\":\"kaola\",\"platform_name\":\"考拉\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"},{\"index\":\"7\",\"type\":\"tmall\",\"platform_name\":\"天猫\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", 1)
}
item = SysModDataByReplace(c, item)
ms = append(ms, item)
}

return &ms, nil
}

// 用IDS找对应模块数据
func SysModFindByIds(Db *xorm.Engine, ids ...int) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.In("mod_id", ids).Where("state = 1").
Cols("mod_id,mod_pid,mod_name,position,skip_identifier,title,subtitle,url,margin,aspect_ratio,icon,img,font_color,bg_img,bg_color,bg_color_t,badge,path,data,sort").
Asc("sort").Find(&m); err != nil {
return nil, err
}

return &m, nil
}

// ID查找对应模块
func SysModFindById(c *gin.Context, Db *xorm.Engine, id string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND mod_id = ?", id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}

return mm.(*model.SysModule), nil
}

// SysModFindByTmpId is 根据模板
func SysModFindByTmpId(c *gin.Context, Db *xorm.Engine, id string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND template_id = ?", id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
}

// Name查找对应模块
func SysModFindByName(c *gin.Context, Db *xorm.Engine, name string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND mod_name = ?", name).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
}

// SysModFindByName is Name查找对应模块
func SysModFindByNames(names ...string) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.In("mod_name", names).Where("state = 1").
Cols("mod_id,mod_pid,mod_name,position,skip_identifier,title,subtitle,url,margin,aspect_ratio,icon,img,font_color,bg_img,bg_color,bg_color_t,badge,path,data,sort").
Find(&m); err != nil {
return nil, err
}
return &m, nil
}

// SysModFindByPosition is 根据位置查找对应模块
func SysModFindByPosition(Db *xorm.Engine, positions ...string) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.In("position", positions).Where("state = 1").Find(&m); err != nil {
return nil, err
}
return &m, nil
}

// 根据跳转标识 查找对应模块
func SysModFindBySkipIdentifier(c *gin.Context, Db *xorm.Engine, name string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND skip_identifier = ?", name).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
}

func SysModFindBySkipIdentifierWithUid(c *gin.Context, Db *xorm.Engine, name string, uid int) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND skip_identifier = ? and uid=?", name, uid).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
}

// 根据跳转标识和位置 查找对应模块list
func SysModFindBySkipIdentifierAndPosition(c *gin.Context, Db *xorm.Engine, name string, position string) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.Where("state = 1 AND skip_identifier = ? AND position = ?", name, position).
Cols("mod_id,mod_pid,mod_name,position,skip_identifier,title,subtitle,url,margin,aspect_ratio,icon,img,font_color,bg_img,bg_color,bg_color_t,badge,path,data,sort").
Asc("sort").Find(&m); err != nil {
return nil, err
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*[]model.SysModule), nil
}
func SysModFindByTempId(Db *xorm.Engine, ids []int) (*[]model.SysModule, error) {
var m []model.SysModule
if err := Db.Where("state = 1 ").In("template_id", ids).Asc("sort").Find(&m); err != nil {
return nil, err
}
return &m, nil
}

// SysModFindByTemplateIDAndSkip is 根据模板id 查找对应模块
func SysModFindByTemplateIDAndSkip(Db *xorm.Engine, id interface{}, skip string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND template_id = ? AND skip_identifier = ?", id, skip).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// SysModFindByTemplateIDAndPID is 根据模板id 和pid =0 查找父模块
func SysModFindByTemplateIDAndPID(Db *xorm.Engine, id interface{}, pid interface{}) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND template_id = ? AND mod_pid = ?", id, pid).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}

return &m, nil
}

// SysModFindByTemplateIDAndModName is 根据模板id 和mod name 查找模块
func SysModFindByTemplateIDAndModName(Db *xorm.Engine, id interface{}, modName string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND template_id = ? AND mod_name = ?", id, modName).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

func SysModFindByTemplateIDAndModNameWithIds(Db *xorm.Engine, ids []int, modName string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.In("template_id", ids).And(" mod_name = ?", modName).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// SysModFindNavIsUsed 查找正在使用的底部导航栏模板
func SysModFindNavIsUsedByPlatform(c *gin.Context, Db *xorm.Engine, platform string) (*model.SysModule, error) {
var (
tm model.SysTemplate
m model.SysModule
)

mid := c.GetString("mid")
fmt.Println("===================================app_type", c.GetString("app_type"))
if c.GetString("app_type") != "" && c.GetString("app_type") != "daogou" {
var (
tempType string
)
switch c.GetString("app_type") {
case "o2o":
tempType = "o2o_store_bottomNav"

}

switch platform {
case "ios":
if has, err := Db.Where("is_use = 1 AND type = ? AND platform = 2 ", tempType).
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
appVersion := GetCloudBuild(c, platform)
if c.GetHeader("app_version_name") == appVersion && c.GetHeader("app_version_name") != "" {
m, err := GetCloudBundleByVersion(Db, appVersion, 2, 1)
if err != nil {
return nil, logx.Warn(err)
}
tm.Id = int(gjson.Get(m.TemplateDuringAudit, "bottom").Int())
}
case "android":
has, err := Db.Where("is_use = 1 AND type = ? AND platform = 2 ", tempType).Cols("id,uid,name,is_use,is_system").Get(&tm)
if err != nil || has == false {
return nil, logx.Warn(err)
}
fmt.Println("===================================app_type", tm)

appVersion := GetCloudBuild(c, platform)
fmt.Println("===================================app_type", appVersion)

if appVersion != "" && c.GetHeader("app_version_name") == appVersion {
m, err := GetCloudBundleByVersion(Db, appVersion, 1, 1)
if err != nil {
return nil, logx.Warn(err)
}
fmt.Println("===================================app_type", m)

tm.Id = int(gjson.Get(m.TemplateDuringAudit, "bottom").Int())
}
case "wx_applet", "wap":
if has, err := Db.Where("is_use = 1 AND type = ? AND platform = 4 ", tempType).
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
case "baidu_applet":
if has, err := Db.Where("is_use = 1 AND type = ? AND platform = 4 ", tempType).
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
case "toutiao_applet":
if has, err := Db.Where("is_use = 1 AND type = ? AND platform = 4 ", tempType).
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
case "alipay_applet":
if has, err := Db.Where("is_use = 1 AND type = ? AND platform = 4 ", tempType).
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
default:
return &m, errors.New("Platform not support")
}
if has, err := Db.Where("state = 1 AND template_id = ?", tm.Id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}

fmt.Println("===================================app_type", m)
if tempType == "o2o_store_bottomNav" {
bottomMap := make(map[string]interface{})
utils.Unserialize([]byte(m.Data), &bottomMap)
list, ok := bottomMap["list"]
if ok {
m.Data = string(utils.MarshalJSONCamelCase2JsonSnakeCase(utils.SerializeStr(list)))
}
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
}
switch platform {
case "ios":
if has, err := Db.Where("is_use = 1 AND type = 'bottom' AND platform = 2 ").
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
appVersion := GetCloudBuild(c, platform)
if c.GetHeader("app_version_name") == appVersion && c.GetHeader("app_version_name") != "" {
m, err := GetCloudBundleByVersion(Db, appVersion, 2, 0)
if err != nil {
return nil, logx.Warn(err)
}
tm.Id = int(gjson.Get(m.TemplateDuringAudit, "bottom").Int())
}

if has, err := Db.Where("state = 1 AND template_id = ? AND mod_name = 'bottom_nav'", tm.Id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
case "android":
has, err := Db.Where("is_use = 1 AND type = 'bottom' AND platform = 2 ").Cols("id,uid,name,is_use,is_system").Get(&tm)
if err != nil || has == false {
return nil, logx.Warn(err)
}
appVersion := GetCloudBuild(c, platform)
if appVersion != "" && c.GetHeader("app_version_name") == appVersion {
m, err := GetCloudBundleByVersion(Db, appVersion, 1, 0)
if err != nil {
return nil, logx.Warn(err)
}
tm.Id = int(gjson.Get(m.TemplateDuringAudit, "bottom").Int())
}
if has, err := Db.Where("state = 1 AND template_id = ? AND mod_name = 'bottom_nav'", tm.Id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
case "wx_applet", "wap":
wxAppletCfg := GetAppletKey(c, Db)
id := utils.StrToInt(wxAppletCfg["bottom_nav_css_id"])
if id == 0 {
return nil, e.NewErr(400, "找不到模板配置")
}
if has, err := Db.Where("state = 1 AND template_id = ? AND mod_name = 'bottom_nav'", id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
case "baidu_applet":
if has, err := Db.Where("is_use = 1 AND type = 'bottom' AND platform = 4 ").
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
appVersion := SysCfgGetWithDb(Db, mid, "baidu_audit_version")

if appVersion != "" && c.GetHeader("app_version_name") == appVersion {
m := SysCfgGetWithDb(Db, mid, "baidu_audit_template")
if m == "" {
return nil, e.NewErr(400, "找不到模板配置")
}
tm.Id = int(gjson.Get(m, "bottom").Int())
}
if has, err := Db.Where("state = 1 AND template_id = ? AND mod_name = 'bottom_nav'", tm.Id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
case "toutiao_applet":
if has, err := Db.Where("is_use = 1 AND type = 'bottom' AND platform = 4 ").
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
appVersion := SysCfgGetWithDb(Db, mid, "tt_audit_version")
if appVersion != "" && c.GetHeader("app_version_name") == appVersion {
m := SysCfgGetWithDb(Db, mid, "tt_audit_template")
if m == "" {
return nil, errors.New("找不到模板配置")
}
tm.Id = int(gjson.Get(m, "bottom").Int())
}
if has, err := Db.Where("state = 1 AND template_id = ? AND mod_name = 'bottom_nav'", tm.Id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
case "alipay_applet":
if has, err := Db.Where("is_use = 1 AND type = 'bottom' AND platform = 4 ").
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
return nil, logx.Warn(err)
}
appVersion := SysCfgGetWithDb(Db, mid, "zfb_audit_version")
if appVersion != "" && c.GetHeader("app_version_name") == appVersion {
m := SysCfgGetWithDb(Db, mid, "zfb_audit_template")
if m == "" {
return nil, errors.New("找不到模板配置")
}
tm.Id = int(gjson.Get(m, "bottom").Int())
}
if has, err := Db.Where("state = 1 AND template_id = ? AND mod_name = 'bottom_nav'", tm.Id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
default:
return &m, errors.New("Platform not support")
}

}

// SysModFindBySkipIdentifierAndModName is 根据mod_name和位置 查找对应模块
func SysModFindBySkipIdentifierAndModName(c *gin.Context, Db *xorm.Engine, name string, modName string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND skip_identifier = ? AND mod_name = ?", name, modName).Get(&m); err != nil || !has {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
}

// SysModFindByModName is 根据mod_name和位置 查找对应模块
func SysModFindByModName(c *gin.Context, Db *xorm.Engine, modName string) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND mod_name = ?", modName).Get(&m); err != nil || !has {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
}

// 根据跳转标识和平台类型查找
func SysModFindBySkipIdentifierAndPlatform(c *gin.Context, Db *xorm.Engine, name string, platform int) (*model.SysModule, error) {
var m model.SysModule
if has, err := Db.Where("state = 1 AND skip_identifier = ? AND platform = ?", name, platform).Get(&m); err != nil || !has {
return nil, logx.Warn(err)
}
mm, err := sysModFormat(c, &m)
if err != nil {
return nil, err
}
return mm.(*model.SysModule), nil
}

// 公共处理modData的链接
func SysModDataByReplace(c *gin.Context, mod model.SysModule) model.SysModule {
//替换链接的一些参数
if strings.Contains(mod.Data, "[replace_APP_URL]") {
mod.Data = strings.Replace(mod.Data, "[replace_APP_URL]", c.GetString("domain_wap_base"), -1)
}
if strings.Contains(mod.Data, "[replace_masterId]") {
mod.Data = strings.Replace(mod.Data, "[replace_masterId]", c.GetString("mid"), -1)
}
if strings.Contains(mod.Data, "[replace_platform]") {
mod.Data = strings.Replace(mod.Data, "[replace_platform]", c.GetHeader("Platform"), -1)
}
if strings.Contains(mod.Data, "优惠卷") {
mod.Data = strings.Replace(mod.Data, "优惠卷", "优惠券", -1)
}
if strings.Contains(mod.Data, "[replace_uid]") {
token := c.GetHeader("Authorization")
// 按空格分割
parts := strings.SplitN(token, " ", 2)
if len(parts) == 2 && parts[0] == "Bearer" {
// parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它
mc, _ := utils.ParseToken(parts[1])
mod.Data = strings.Replace(mod.Data, "[replace_uid]", strconv.Itoa(mc.UID), -1)
}
}
//if strings.Contains(mod.Data, "\"child_category_id") && strings.Contains(mod.Data, "\"category_id") {
// //如果存在这两个字段,要换一下
// mod.Data = strings.ReplaceAll(mod.Data, "\"category_id", "\"null_category_id")
// mod.Data = strings.ReplaceAll(mod.Data, "\"child_category_id", "\"category_id")
//}
return mod
}

// 公共处理modData的链接
func StringByReplace(c *gin.Context, skip string) string {
//替换链接的一些参数
if strings.Contains(skip, "[replace_APP_URL]") {
skip = strings.Replace(skip, "[replace_APP_URL]", c.GetString("domain_wap_base"), -1)
}
if strings.Contains(skip, "[replace_masterId]") {
skip = strings.Replace(skip, "[replace_masterId]", c.GetString("mid"), -1)
}
if strings.Contains(skip, "[replace_platform]") {
skip = strings.Replace(skip, "[replace_platform]", c.GetHeader("Platform"), -1)
}
if strings.Contains(skip, "优惠卷") {
skip = strings.Replace(skip, "优惠卷", "优惠券", -1)
}
if strings.Contains(skip, "[replace_uid]") {
token := c.GetHeader("Authorization")
// 按空格分割
parts := strings.SplitN(token, " ", 2)
if len(parts) == 2 && parts[0] == "Bearer" {
// parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它
mc, _ := utils.ParseToken(parts[1])
skip = strings.Replace(skip, "[replace_uid]", strconv.Itoa(mc.UID), -1)
}
}

//if strings.Contains(mod.Data, "\"child_category_id") && strings.Contains(mod.Data, "\"category_id") {
// //如果存在这两个字段,要换一下
// mod.Data = strings.ReplaceAll(mod.Data, "\"category_id", "\"null_category_id")
// mod.Data = strings.ReplaceAll(mod.Data, "\"child_category_id", "\"category_id")
//}
return skip
}

// 公共处理modSkip的链接 首页弹窗
func SysModSkipByReplace(c *gin.Context, mod *model.SysPopup) *model.SysPopup {
//替换链接的一些参数
if strings.Contains(mod.Skip, "[replace_APP_URL]") {
mod.Skip = strings.Replace(mod.Skip, "[replace_APP_URL]", c.GetString("domain_wap_base"), -1)
}
if strings.Contains(mod.Skip, "[replace_masterId]") {
mod.Skip = strings.Replace(mod.Skip, "[replace_masterId]", c.GetString("mid"), -1)
}
if strings.Contains(mod.Skip, "[replace_platform]") {
mod.Skip = strings.Replace(mod.Skip, "[replace_platform]", c.GetHeader("Platform"), -1)
}
if strings.Contains(mod.Skip, "优惠卷") {
mod.Skip = strings.Replace(mod.Skip, "优惠卷", "优惠券", -1)
}
if strings.Contains(mod.Skip, "[replace_uid]") {
token := c.GetHeader("Authorization")
// 按空格分割
parts := strings.SplitN(token, " ", 2)
if len(parts) == 2 && parts[0] == "Bearer" {
// parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它
mc, _ := utils.ParseToken(parts[1])
mod.Skip = strings.Replace(mod.Skip, "[replace_uid]", strconv.Itoa(mc.UID), -1)
}
}

//if strings.Contains(mod.Data, "\"child_category_id") && strings.Contains(mod.Data, "\"category_id") {
// //如果存在这两个字段,要换一下
// mod.Data = strings.ReplaceAll(mod.Data, "\"category_id", "\"null_category_id")
// mod.Data = strings.ReplaceAll(mod.Data, "\"child_category_id", "\"category_id")
//}
return mod
}

// 公共处理modData的链接
func SysModDataByReplaceSecond(c *gin.Context, mod *model.SysModule) *model.SysModule {
//替换链接的一些参数
if strings.Contains(mod.Data, "[replace_APP_URL]") {
mod.Data = strings.Replace(mod.Data, "[replace_APP_URL]", c.GetString("domain_wap_base"), -1)
}
if strings.Contains(mod.Data, "[replace_masterId]") {
mod.Data = strings.Replace(mod.Data, "[replace_masterId]", c.GetString("mid"), -1)
}
if strings.Contains(mod.Data, "优惠卷") {
mod.Data = strings.Replace(mod.Data, "优惠卷", "优惠券", -1)
}
if strings.Contains(mod.Data, "[replace_uid]") {
token := c.GetHeader("Authorization")
// 按空格分割
parts := strings.SplitN(token, " ", 2)
if len(parts) == 2 && parts[0] == "Bearer" {
// parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它
mc, _ := utils.ParseToken(parts[1])
if mc == nil {
mod.Data = strings.Replace(mod.Data, "[replace_uid]", "0", -1)
} else {
mod.Data = strings.Replace(mod.Data, "[replace_uid]", strconv.Itoa(mc.UID), -1)
}
}
}

if mod.ModName == "product" && strings.Contains(mod.Data, "product_3") {
if strings.Contains(mod.Data, "second_kill_style") == false {
mod.Data = strings.ReplaceAll(mod.Data, "\"coupon_commission\"", "\"second_kill_style\":{\"btn_bg_img\":\"http://ossn.izhim.net/gift.png\",\"left_stock_text_color\":\"#D59E21\",\"buy_now_text_color\":\"#D59E21\",\"is_show\":\"0\"},\"coupon_commission\"")
}
}
mod.Data = strings.ReplaceAll(mod.Data, "\\/", "/")
mod.Data = strings.ReplaceAll(mod.Data, "\\u0026", "&")

//if strings.Contains(mod.Data, "\"child_category_id") && strings.Contains(mod.Data, "\"category_id") {
// //如果存在这两个字段,要换一下
// mod.Data = strings.ReplaceAll(mod.Data, "\"category_id", "\"null_category_id")
// mod.Data = strings.ReplaceAll(mod.Data, "\"child_category_id", "\"category_id")
//}
return mod
}

+ 194
- 0
app/db/db_sys_mod_format_img.go Visa fil

@@ -0,0 +1,194 @@
package db

import (
"applet/app/db/model"
"applet/app/utils"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/syyongx/php2go"
"regexp"
"strings"
)

func sysModFormat(c *gin.Context, m interface{}) (interface{}, error) {
var mods []model.SysModule
protocol := SysCfgGet(c, "file_bucket_scheme")
domain := SysCfgGet(c, "file_bucket_host")
//fmt.Println(protocol, domain)
if protocol == "" || domain == "" {
return nil, errors.New("System configuration error, object storage protocol and domain name not found")
}
modname_list := []string{"product", "search_result_taobao_item", "hot_rank_tab_view"}
switch m.(type) {
case *[]model.SysModule:
ms := m.(*[]model.SysModule)
for _, item := range *ms {
item.Data = ReformatStr(protocol, domain, item.Data, c)
if item.ModName == "product_detail_title" {
if strings.Contains(item.Data, "tmall") == false {
item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"天猫\",\"type\":\"tmall\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
}
if strings.Contains(item.Data, "kuaishou") == false {
item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"快手\",\"type\":\"kuaishou\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
}
if strings.Contains(item.Data, "tikTok") == false {
item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"抖音\",\"type\":\"tikTok\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
}
}

if strings.Contains(item.Data, "tmall") == false && utils.InArr(item.ModName, modname_list) {
item.Data = strings.Replace(item.Data, "{\"index\":\"6\",\"type\":\"kaola\",\"platform_name\":\"考拉\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", "{\"index\":\"6\",\"type\":\"kaola\",\"platform_name\":\"考拉\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"},{\"index\":\"7\",\"type\":\"tmall\",\"platform_name\":\"天猫\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", 1)
item.Data = strings.Replace(item.Data, "{\"type\":\"kaola\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", "{\"type\":\"kaola\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"},{\"type\":\"tmall\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", 1)
}
if strings.Contains(item.Data, "\"virtual_coin_pre_fix_name\":") == false && item.ModName == "product" {
item.Data = strings.ReplaceAll(item.Data, "\"virtual_coin_name\":", "\"virtual_coin_pre_fix_name\":\"返\",\"virtual_coin_name\":")
}
item = SysModDataByReplace(c, item)

mods = append(mods, item)
}
return &mods, nil
case *model.SysModule:
m := m.(*model.SysModule)
m.Data = ReformatStr(protocol, domain, m.Data, c)
m = SysModDataByReplaceSecond(c, m)
return m, nil
case []*model.UserLevel:
ms := m.([]*model.UserLevel)
for _, item := range ms {
item.CssSet = ReformatStr(protocol, domain, item.CssSet, c)
}
return ms, nil
case []*model.SysPushUser:
ms := m.([]*model.SysPushUser)
for _, item := range ms {
item.SendData = ReformatStr(protocol, domain, item.SendData, c)
}
return ms, nil
case *model.SysPushUser:
m := m.(*model.SysPushUser)
m.SendData = ReformatStr(protocol, domain, m.SendData, c)
return m, nil
default:
return nil, nil
}
}

func ReformatComm(str, protocol, domain string) string {
// PNG
replaceList := reformatImg(str)
l := removeDuplicateElement(replaceList)
for _, s := range l {
if strings.Contains(s, "http") {
continue
}
ss := s
s = strings.ReplaceAll(s, `\`, "")
s = strings.ReplaceAll(s, `"`, "")
s = php2go.Rawurlencode(s)
new := fmt.Sprintf("%s://%s/%s", protocol, domain, s)
//if skipHTTPPng(new) {
// continue
//}
str = strings.Replace(str, ss, `"`+new+`"`, -1)
}
return str
}
func ReformatStr(protocol, domain, str string, c *gin.Context) string {
//protocol := SysCfgGet(c, "file_bucket_scheme")
//domain := SysCfgGet(c, "file_bucket_host")

// PNG
str = ReformatComm(str, protocol, domain)
return str
}

// 正则匹配
func reformatPng(data string) []string {
re, _ := regexp.Compile(`"([^\"]*.png")`)
list := re.FindAllString(data, -1)
return list
}
func reformatJpeg(data string) []string {
re, _ := regexp.Compile(`"([^\"]*.jpeg")`)
list := re.FindAllString(data, -1)
return list
}
func reformatMp4(data string) []string {
re, _ := regexp.Compile(`"([^\"]*.mp4")`)
list := re.FindAllString(data, -1)
return list
}

func skipHTTPPng(data string) bool {
re, _ := regexp.Compile(`(http|https):\/\/([^\"]*.png)`)
return re.MatchString(data)
}

// 正则匹配
func reformatJPG(data string) []string {
re, _ := regexp.Compile(`"([^\"]*.jpg")`)
list := re.FindAllString(data, -1)
return list
}

// 正则匹配
func reformatGIF(data string) []string {
re, _ := regexp.Compile(`"([^\"]*.gif")`)
list := re.FindAllString(data, -1)
return list
}
func reformatImg(data string) []string {
re, _ := regexp.Compile(`"([^\"]*.(png|jpg|jpeg|gif|mp4)")`)
list := re.FindAllString(data, -1)
return list
}

func removeDuplicateElement(addrs []string) []string {
result := make([]string, 0, len(addrs))
temp := map[string]int{}
i := 1
for _, item := range addrs {
if _, ok := temp[item]; !ok {
temp[item] = i
result = append(result, item)
continue
}
temp[item] = temp[item] + 1
}
// fmt.Println(temp)
return result
}

// 单条记录获取DB
func SysCfgGet(c *gin.Context, key string) string {
res := SysCfgFind(c, key)
//fmt.Println(res)
if _, ok := res[key]; !ok {
return ""
}
return res[key]
}

// 多条记录获取
func SysCfgFind(c *gin.Context, keys ...string) map[string]string {
eg := DBs[c.GetString("mid")]
masterId := c.GetString("mid")
res := map[string]string{}
//TODO::判断keys长度(大于10个直接查数据库)
if len(keys) > 10 {
cfgList, _ := SysCfgGetAll(eg)
if cfgList == nil {
return nil
}
for _, v := range *cfgList {
res[v.Key] = v.Val
}
} else {
for _, key := range keys {
res[key] = SysCfgGetWithDb(eg, masterId, key)
}
}
return res
}

+ 395
- 0
app/db/db_user.go Visa fil

@@ -0,0 +1,395 @@
package db

import (
"applet/app/db/model"
"applet/app/utils/logx"
"fmt"
"strings"
"xorm.io/xorm"
)

// UserisExistByUsernameAndPassword is usernameAndPassword exist
func UserisExistByUsernameAndPassword(Db *xorm.Engine, username, password, zone string) (*model.User, error) {
var user model.User
sess := Db.Where("(username = ? or phone=?) ", username, username)
if zone != "" && zone != "86" {
sess = sess.And("zone=?", zone)
}
has, err := sess.Get(&user)
if err != nil || has == false {
return nil, err
}
return &user, nil
}

// UserisExistByMobile is exist
func UserisExistByMobile(Db *xorm.Engine, n string) (bool, error) {
has, err := Db.Where("phone = ? and phone<>''", n).Exist(&model.User{})

if err != nil {
return false, err
}
return has, nil
}
func UserisFindByMobile(sess *xorm.Session, n string) *model.User {
var data model.User
has, err := sess.Where("phone = ? and phone<>''", n).Get(&data)

if err != nil || has == false {
return nil
}
return &data
}

// UserInByUIDByLevel is In查询 以及是否是有效用户
func UserInByUIDByLevel(Db *xorm.Engine, ids []int, levelID interface{}) (*[]model.User, error) {
var m []model.User
if err := Db.In("uid", ids).Where("level = ?", levelID).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserFindByMobile search user by mobile
func UserFindByMobile(Db *xorm.Engine, mobile string) (*model.User, error) {
var m model.User
if has, err := Db.Where("(phone = ? OR uid = ?) AND delete_at = 0", mobile, mobile).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserFindExistByMobile search user by mobile
func UserFindExistByMobile(Db *xorm.Engine, mobile string) (*model.User, bool, error) {
var m model.User
has, err := Db.Where("(phone = ? OR uid = ?) AND delete_at = 0", mobile, mobile).Get(&m)
if err != nil {
logx.Infof("UserFindExistByMobile err")
return nil, false, logx.Warn(err)
}
return &m, has, nil
}

// UserFindByMobile search user by mobile
func UserFindByMobileAll(Db *xorm.Engine, mobile string) (*model.User, error) {
var m model.User
if has, err := Db.Where("(phone = ? OR uid = ?)", mobile, mobile).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserGetByMobileIgnoreDelete search user by mobile ignore delete
func UserGetByMobileIgnoreDelete(Db *xorm.Engine, mobile, zone string) (*model.User, bool, error) {
m := new(model.User)
sess := Db.Where("phone = ?", mobile)
if zone != "" && zone != "86" {
sess = sess.And("zone=?", zone)
}
has, err := sess.Get(m)
if err != nil {
return nil, false, logx.Warn(err)
}
return m, has, nil
}

// UsersFindByMobileLike search users by mobile
func UsersFindByMobileLike(Db *xorm.Engine, mobile string) (*[]model.User, error) {
var m []model.User
if err := Db.Where("phone like ?", "%"+mobile+"%").
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersFindByNickNameLike search users by nickname
func UsersFindByNickNameLike(Db *xorm.Engine, nickname string) (*[]model.User, error) {
var m []model.User
if err := Db.Where("nickname like ?", "%"+nickname+"%").
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UsersFindByInviteCode(Db *xorm.Engine, nickname string) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.Where("invite_code like ? or custom_invite_code like ?", "%"+strings.ToLower(nickname)+"%", "%"+strings.ToLower(nickname)+"%").
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UsersFindByInviteCodeMust(Db *xorm.Engine, nickname string) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.Where("invite_code = ? or custom_invite_code = ?", strings.ToLower(nickname), strings.ToLower(nickname)).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersInByIds is 根据ids 查找users
func UsersInByIds(Db *xorm.Engine, ids []int, limit, start int) (*[]model.User, error) {
var m []model.User
if limit == 0 && start == 0 {
if err := Db.In("uid", ids).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.In("uid", ids).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersInByIdsWhereLv is 根据ids和 lv会员等级 查找users
func UsersInByIdsWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int) (*[]model.User, error) {
var m []model.User
if limit == 0 && start == 0 {
if err := Db.Where("level = ?", lv).In("uid", ids).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.Where("level = ?", lv).In("uid", ids).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersInByIdsByAscWhereLv is 根据ids和 lv会员等级 查找users 升排序
func UsersInByIdsByAscWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int, c string) (*[]model.User, error) {
var m []model.User
if limit == 0 && start == 0 {
if err := Db.Where("level = ?", lv).In("uid", ids).Asc(c).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.Where("level = ?", lv).In("uid", ids).Asc(c).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersInByIdsByDescWhereLv is 根据ids和 lv会员等级 查找users 降排序
func UsersInByIdsByDescWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int, c string) (*[]model.User, error) {
var m []model.User
if limit == 0 && start == 0 {
if err := Db.Where("level = ?", lv).In("uid", ids).Desc(c).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.Where("level = ?", lv).In("uid", ids).Desc(c).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserFindByPhoneOrUsername(Db *xorm.Engine, mobile string) (*model.User, error) {
var m model.User
if has, err := Db.Where("(phone = ? or username=?) AND delete_at = 0", mobile, mobile).
Get(&m); err != nil || has == false {
return nil, err
}
return &m, nil
}

// UserFindByArkidUserName search user by mobile
func UserFindByArkidUserName(Db *xorm.Engine, name string) (*model.User, error) {
var m model.User
if has, err := Db.Where("username = ?", name).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserFindByID is find user byid
func UserFindByID(Db *xorm.Engine, id interface{}) (*model.User, error) {
var m model.User
if has, err := Db.Where("uid = ?", id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserFindByIDWithSession(sess *xorm.Session, id interface{}) (*model.User, error) {
var m model.User
if has, err := sess.Where("uid = ?", id).
Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

func UserFindByIDs(Db *xorm.Engine, uids []int) (*[]model.User, error) {
var m []model.User
if err := Db.In("uid", uids).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

func UserFindByall(Db *xorm.Engine) (*[]model.User, error) {
var m []model.User
if err := Db.Where("uid>0").Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserFindByIDsToStr(Db *xorm.Engine, uids []string) (*[]model.User, error) {
var m []model.User
if err := Db.In("uid", uids).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserFindByIsSet(Db *xorm.Engine, limit, start int) ([]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.Where("is_set=? and parent_uid=0 and uid>0", 0).Limit(limit, start).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return m, nil
}
func UserFindByParentUid(Db *xorm.Engine, parentUid int) ([]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.Where("parent_uid=?", parentUid).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return m, nil
}

// UsersInByIdsByDesc is 根据某列 降序
func UsersInByIdsByDesc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.User, error) {
var m []model.User
if limit == 0 && start == 0 {
if err := Db.In("uid", ids).Desc(c).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.In("uid", ids).Desc(c).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersInByIdsByAsc is 根据某列 升序
func UsersInByIdsByAsc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.User, error) {
var m []model.User
if limit == 0 && start == 0 {
if err := Db.In("uid", ids).Asc(c).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.In("uid", ids).Asc(c).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserInsert is insert user
func UserInsert(Db *xorm.Engine, user *model.User) (int64, error) {
affected, err := Db.Insert(user)
if err != nil {
return 0, err
}
return affected, nil
}

// UserIsExistByMobile is mobile exist
func UserIsExistByMobile(Db *xorm.Engine, mobile string) (bool, error) {
//fmt.Println(mobile)
has, err := Db.Where("phone = ? OR uid = ?", mobile, mobile).Exist(&model.User{})
fmt.Println(has, mobile)
if err != nil {
return false, err
}
return has, nil
}

// UserIsExistByID is mobile exist by id
func UserIsExistByID(Db *xorm.Engine, id string) (bool, error) {
has, err := Db.Where("uid = ?", id).Exist(&model.User{})
if err != nil {
return false, err
}
return has, nil
}

// UserUpdate is update user
func UserUpdate(Db *xorm.Engine, uid interface{}, user *model.User, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = Db.Where("uid=?", uid).Cols(forceColums...).Update(user)
} else {
affected, err = Db.Where("uid=?", uid).Update(user)
}
if err != nil {
return 0, err
}
return affected, nil
}

func UserUpdateWithSession(Db *xorm.Session, uid interface{}, user *model.User, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = Db.Where("uid=?", uid).Cols(forceColums...).Update(user)
} else {
affected, err = Db.Where("uid=?", uid).Update(user)
}
if err != nil {
return 0, err
}
return affected, nil
}

func UpdateUserFinValid() {

}

// UserDelete is delete user
func UserDelete(Db *xorm.Engine, uid interface{}) (int64, error) {
return Db.Where("uid = ?", uid).Delete(model.User{})
}

func UserDeleteWithSess(sess *xorm.Session, uid interface{}) (int64, error) {
return sess.Where("uid = ?", uid).Delete(model.User{})
}

func UserProfileCheckInviteCode(eg *xorm.Engine, uid int, inviteCode string) bool {
var data model.UserProfile
get, err := eg.Where("invite_code=? or custom_invite_code=?", inviteCode, inviteCode).Get(&data)
if get == false || err != nil {
return false
}
if uid == data.Uid {
return false
}
return true
}

+ 103
- 0
app/db/db_user_fin_flow.go Visa fil

@@ -0,0 +1,103 @@
package db

import (
"applet/app/db/model"
"applet/app/utils/logx"

"xorm.io/xorm"
)

// GetFinUserFlowByID is 用户流水记录
func GetFinUserFlowByID(Db *xorm.Engine, id interface{}) (*model.FinUserFlow, error) {
var m model.FinUserFlow
if has, err := Db.Where("id = ?", id).Get(&m); err != nil || !has {
return nil, logx.Warn(err)
}
return &m, nil
}

// GetFinUserFlowByID is 用户流水记录
func GetFinUserFlowByUIDANDOID(Db *xorm.Engine, types, uid, ordId string) (*model.FinUserFlow, error) {
var m model.FinUserFlow
if has, err := Db.Where("uid = ? and ord_id = ? and type = ?", uid, ordId, types).Get(&m); err != nil || !has {
return nil, logx.Warn(err)
}
return &m, nil
}
func GetFinUserFlowByUIDANDOIDTOORDTYPE(Db *xorm.Engine, types, uid, ordId string) (*model.FinUserFlow, error) {
var m model.FinUserFlow
if has, err := Db.Where("uid = ? and ord_id = ? and ord_type = ?", uid, ordId, types).Get(&m); err != nil || !has {
return nil, logx.Warn(err)
}
return &m, nil
}

// GetFinUserFlowByID is 用户流水记录
func GetFinUserFlowByOIDANDORDTYPE(Db *xorm.Engine, types, ordId, ordType string) (*model.FinUserFlow, error) {
var m model.FinUserFlow
if has, err := Db.Where("ord_id = ? and ord_action = ? and ord_type= ?", ordId, types, ordType).Get(&m); err != nil || !has {
return nil, logx.Warn(err)
}
return &m, nil
}

//FinUserFlowInsertOne is 插入一条流水记录
func FinUserFlowInsertOne(Db *xorm.Engine, m *model.FinUserFlow) error {
_, err := Db.InsertOne(m)
if err != nil {
return err
}
return nil
}

//FinUserFlowInsertOne is 插入一条流水记录
func FinUserFlowWithSessionInsertOne(session *xorm.Session, m *model.FinUserFlow) error {
_, err := session.InsertOne(m)
if err != nil {
return err
}
return nil
}

// FinUserFlowByUID is 用户流水
func FinUserFlowInputByUID(Db *xorm.Engine, uid interface{}, time string, limit, start int) ([]*model.FinUserFlow, error) {
var m []*model.FinUserFlow
if err := Db.Where("uid = ? AND create_at like ? and (amount> ? or ord_type=?)", uid, time+"%", "0", "fast_return").In("type", "0").Desc("create_at").Limit(limit, start).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return m, nil
}
func FinUserFlowInputByUIDWithAmount(Db *xorm.Engine, uid interface{}, types, before_amount, after_amount string) (*model.FinUserFlow, error) {
var m model.FinUserFlow
if has, err := Db.Where("uid = ? and ord_type='withdraw' and ord_action = ? and before_amount= ? and after_amount = ?", uid, types, before_amount, after_amount).Get(&m); err != nil || !has {
return nil, logx.Warn(err)
}
return &m, nil
}

// FinUserFlowByUIDByOrderAction is 用户流水 by OrderAction
func FinUserFlowInputByUIDByOrderActionByTime(Db *xorm.Engine, uid, oa interface{}, time string, limit, start int) ([]*model.FinUserFlow, error) {
var m []*model.FinUserFlow
if err := Db.Where("uid = ? AND create_at like ? and amount>0", uid, time+"%").In("ord_action", oa).Desc("create_at").Limit(limit, start).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return m, nil
}

// FinUserFlowByUIDByOrderAction is 用户流水 by OrderAction
func FinUserFlowInputByUIDByTypeByTime(Db *xorm.Engine, uid int, time string, limit, start int) ([]*model.FinUserFlow, error) {
var m []*model.FinUserFlow
if err := Db.Where("uid = ? AND type = 1 AND create_at like ? and (amount>0 or ord_type=? or ord_action=?)", uid, time+"%", "fast_return", 101).Desc("create_at").Limit(limit, start).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return m, nil
}

// 在事务中使用,插入一条流水记录
func FinUserFlowInsertOneWithSession(session *xorm.Session, m *model.FinUserFlow) error {
_, err := session.InsertOne(m)
if err != nil {
return err
}
return nil
}

+ 226
- 0
app/db/db_user_level.go Visa fil

@@ -0,0 +1,226 @@
package db

import (
"applet/app/db/model"
"applet/app/e"
"applet/app/utils/logx"
"github.com/gin-gonic/gin"
"xorm.io/xorm"
)

//UserLevelByID is 根据用户id 获取对应的等级信息
func UserLevelByID(Db *xorm.Engine, id interface{}) (*model.UserLevel, error) {
m := new(model.UserLevel)
has, err := Db.Where("id = ?", id).Get(m)
if err != nil {
return nil, logx.Warn(err)
}
if !has {
return nil, logx.Error("Not found")
}

return m, nil
}
func UserLevelByIDWithSession(sess *xorm.Session, id interface{}) (*model.UserLevel, error) {
m := new(model.UserLevel)
has, err := sess.Where("id = ?", id).Get(m)
if err != nil {
return nil, logx.Warn(err)
}
if !has {
return nil, logx.Error("Not found")
}

return m, nil
}

//UserLevelTop is 查询最高的等级
func UserLevelTop(Db *xorm.Engine) (*model.UserLevel, error) {
m := new(model.UserLevel)
has, err := Db.OrderBy("level_weight DESC").Get(m)
if err != nil {
return nil, logx.Warn(err)
}
if !has {
return nil, logx.Error("Not found")
}

return m, nil
}

//UserLevelNext is 查询下一等级
func UserLevelNext(Db *xorm.Engine, curLevelWeight int) (*model.UserLevel, error) {
m := new(model.UserLevel)
has, err := Db.Where("level_weight > ? and before_hide=?", curLevelWeight, 0).OrderBy("level_weight ASC").Get(m)
if err != nil {
return nil, logx.Warn(err)
}
if !has {
return nil, logx.Error("Not found")
}

return m, nil
}

// UserLevelByWeight is 根据权重获取对应的等级
func UserLevelByWeight(Db *xorm.Engine, w interface{}) (*model.UserLevel, error) {
m := new(model.UserLevel)
has, err := Db.Where("level_weight = ?", w).Get(m)
if err != nil {
return nil, logx.Warn(err)
}
if !has {
return nil, logx.Warn("Not found")
}
return m, nil
}

//UserLevelInIDescByWeight is In 查询获取 权重最低 对应等级
func UserLevelInIDescByWeightLow(Db *xorm.Engine) ([]*model.UserLevel, error) {
var ms []*model.UserLevel
if err := Db.Asc("level_weight").Limit(1).Find(&ms); err != nil {
return nil, err
}
return ms, nil

}
func UserLevelInIDescByWeightLowWithOne(Db *xorm.Engine) (*model.UserLevel, error) {
var ms model.UserLevel
has, err := Db.Asc("level_weight").Get(&ms)
if err != nil {
return nil, err
}
if has == false {
return nil, e.NewErr(400, "等级不存在")
}
return &ms, nil

}
func UserLevelInIDescByWeightDescWithOne(Db *xorm.Engine) (*model.UserLevel, error) {
var ms model.UserLevel
has, err := Db.Desc("level_weight").Get(&ms)
if err != nil {
return nil, err
}
if has == false {
return nil, e.NewErr(400, "等级不存在")
}
return &ms, nil

}
func UserLevelByWeightNext(Db *xorm.Engine, levelWeight int) (*model.UserLevel, error) {
var ms model.UserLevel
if has, err := Db.Where("level_weight>? and is_use=? and before_hide=?", levelWeight, 1, 0).Asc("level_weight").Get(&ms); err != nil || has == false {
return nil, err
}
return &ms, nil

}
func UserLevelByWeightMax(Db *xorm.Engine) (*model.UserLevel, error) {
var ms model.UserLevel
if has, err := Db.Where("is_use=? and before_hide=?", 1, 0).Desc("level_weight").Get(&ms); err != nil || has == false {
return nil, err
}
return &ms, nil

}

//UserLevelInIDescByWeight is In 查询获取对应等级 根据权重排序
func UserLevelInIDescByWeight(Db *xorm.Engine, ids []int) ([]*model.UserLevel, error) {
var ms []*model.UserLevel
if err := Db.In("id", ids).Desc("level_weight").Find(&ms); err != nil {
return nil, err
}
return ms, nil

}
func UserLevelIDescByWeight(Db *xorm.Engine, id int) (*model.UserLevel, error) {
var ms model.UserLevel
if has, err := Db.Where("id=?", id).Get(&ms); err != nil || has == false {
return nil, err
}
return &ms, nil

}

// UserLevlAll is 获取所有开启等级并且升序返回
func UserLevlAll(c *gin.Context, Db *xorm.Engine) ([]*model.UserLevel, error) {
var m []*model.UserLevel
err := Db.Where("is_use = ?", 1).Asc("level_weight").Find(&m)
if err != nil {
return nil, logx.Warn(err)
}

mm, err := sysModFormat(c, m)
if err != nil {
return nil, err
}
return mm.([]*model.UserLevel), nil
}
func UserLevlAllNew(c *gin.Context, Db *xorm.Engine) ([]*model.UserLevel, error) {
var m []*model.UserLevel
err := Db.Where("is_use = ? and before_hide=?", 1, 0).Asc("level_weight").Find(&m)
if err != nil {
return nil, logx.Warn(err)
}

mm, err := sysModFormat(c, m)
if err != nil {
return nil, err
}
return mm.([]*model.UserLevel), nil
}

// UserLevlEgAll is 获取所有开启等级并且升序返回
func UserLevlEgAll(Db *xorm.Engine) ([]*model.UserLevel, error) {
var m []*model.UserLevel
err := Db.Where("is_use = ?", 1).Asc("level_weight").Find(&m)
if err != nil {
return nil, logx.Warn(err)
}
return m, nil
}
func UserFindByLevel(eg *xorm.Engine, level int) []model.User {
var data []model.User
eg.Where("level=?", level).Find(&data)
return data
}

// UserLevlAllByWeight is 获取所有等级并且权重升序返回
func UserLevlAllByWeight(c *gin.Context, Db *xorm.Engine) ([]*model.UserLevel, error) {
var m []*model.UserLevel
err := Db.Asc("level_weight").Find(&m)
if err != nil {
return nil, logx.Warn(err)
}

mm, err := sysModFormat(c, m)
if err != nil {
return nil, err
}
return mm.([]*model.UserLevel), nil
}
func UserLevelByAllMap(Db *xorm.Engine) map[int]*model.UserLevel {
var maps = make(map[int]*model.UserLevel, 0)
var m []*model.UserLevel
err := Db.Where("is_use = ?", 1).Asc("level_weight").Find(&m)
if err != nil {
return maps
}
for _, v := range m {
maps[v.Id] = v
}
return maps
}
func UserLevelByNotHideAllMap(Db *xorm.Engine) map[int]*model.UserLevel {
var maps = make(map[int]*model.UserLevel, 0)
var m []*model.UserLevel
err := Db.Where("is_use = ? and before_hide=?", 1, 0).Asc("level_weight").Find(&m)
if err != nil {
return maps
}
for _, v := range m {
maps[v.Id] = v
}
return maps
}

+ 578
- 0
app/db/db_user_profile.go Visa fil

@@ -0,0 +1,578 @@
package db

import (
"applet/app/db/model"
"applet/app/md"
"applet/app/utils"
"applet/app/utils/logx"
"errors"
"xorm.io/xorm"
)

// UserProfileFindByArkID is get userprofile by arkid
func UserProfileFindByArkID(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("arkid_uid = ?", id).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileFindByArkToken(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("arkid_token<>'' and arkid_token = ?", id).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByInviteCode is get userprofile by InviteCode
func UserProfileFindByInviteCode(Db *xorm.Engine, code string) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("invite_code = ?", code).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByInviteCode is get userprofile by InviteCode
func UserProfileFindByCustomInviteCode(Db *xorm.Engine, code string) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("custom_invite_code = ?", code).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByInviteCodes is get userprofile by InviteCode
func UserProfileFindByInviteCodes(Db *xorm.Engine, codes ...string) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.In("invite_code", codes).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileFindByAll(Db *xorm.Engine) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByCustomInviteCodes is get userprofile by CustomInviteCode
func UserProfileFindByCustomInviteCodes(Db *xorm.Engine, codes ...string) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.In("custom_invite_code", codes).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByID search user_profile by userid
func UserProfileFindByID(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("uid = ?", id).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileFindAll(Db *xorm.Engine) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.Where("invite_code='' and uid>=0").Asc("uid").Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileFindByIDsToStr(Db *xorm.Engine, uids []string) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.In("uid", uids).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileFindByIDSess(sess *xorm.Session, id interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := sess.Where("uid = ?", id).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileFindByPID(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("parent_uid = ?", id).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileOrderByNew 找最新的记录
func UserProfileOrderByNew(Db *xorm.Engine) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("invite_code != ''").OrderBy("uid desc").Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByTaobaoOpenID search user_profile ByTaobaoOpenID
func UserProfileFindByTaobaoOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("third_party_taobao_oid = ?", openid).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByQQOpenID search user_profile ByTaobaoOpenID
func UserProfileFindByQQOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("third_party_qq_openid = ?", openid).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByAppleToken search user_profile AppleToken
func UserProfileFindByAppleToken(Db *xorm.Engine, token interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("third_party_apple_token = ?", token).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByWeChatOpenID search user_profile By 微信openid
func UserProfileFindByWeChatOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("third_party_wechat_openid = ?", openid).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByWeChatMiniOpenID search user_profile By 小程序openid
func UserProfileFindByWeChatMiniOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := Db.Where("third_party_wechat_mini_openid = ?", openid).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileFindByWeChatUnionID search user_profile By 微信唯一id
func UserProfileFindByWeChatUnionID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) {
if openid == "" {
return nil, errors.New("不存在")
}
var m model.UserProfile
if has, err := Db.Where("third_party_wechat_unionid = ? ", openid).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileFindByAccAlipay(Db *xorm.Engine, accAlipay string, uid int) (bool, error) {
if has, err := Db.Where("acc_alipay = ? and uid <>?", accAlipay, uid).Exist(&model.UserProfile{}); err != nil || has == false {
return false, logx.Warn(err)
}
return true, nil
}

// UserProfileisExistByTaobaoOpenID is exist by Taobao
func UserProfileisExistByTaobaoOpenID(Db *xorm.Engine, openid string) (bool, error) {
has, err := Db.Where("third_party_taobao_oid = ?", openid).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}
func UserProfileisThirdPartyWechatH5Openid(Db *xorm.Engine, openid string) (*model.UserProfile, error) {
var user model.UserProfile
has, err := Db.Where("third_party_wechat_h5_openid = ? and third_party_wechat_h5_openid<>''", openid).Get(&user)

if err != nil || has == false {
return nil, err
}
return &user, nil
}

// UserProfileisExistByQQOpenID is exist by QQ openid
func UserProfileisExistByQQOpenID(Db *xorm.Engine, openid string) (bool, error) {
has, err := Db.Where("third_party_qq_openid = ?", openid).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}

// UserProfileisExistByAppleToken is exist by apple token
func UserProfileisExistByAppleToken(Db *xorm.Engine, token string) (bool, error) {
has, err := Db.Where("third_party_apple_token = ?", token).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}

// UserProfileisExistByWeChatOpenID is exist by Wecaht openid
func UserProfileisExistByWeChatOpenID(Db *xorm.Engine, openid string) (bool, error) {
has, err := Db.Where("third_party_wechat_openid = ?", openid).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}

// UserProfileisExistByWeChatMiniOpenID is exist by Wecaht openid
func UserProfileisExistByWeChatMiniOpenID(Db *xorm.Engine, openid string) (bool, error) {
has, err := Db.Where("third_party_wechat_mini_openid = ?", openid).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}

// UserProfileisExistByWeChatUnionID is exist by Wecaht openid
func UserProfileisExistByWeChatUnionID(Db *xorm.Engine, openid string) (bool, error) {
if openid == "" {
return false, errors.New("不存在")
}
has, err := Db.Where("third_party_wechat_unionid = ? ", openid).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}

// UserProfileisExistByRelationIDAndSpecialID is exist by RelationIdAndSpecialId
func UserProfileisExistByRelationIDAndSpecialID(Db *xorm.Engine, SpecialID, RelationID int64) (bool, error) {
has, err := Db.Where("acc_taobao_self_id = ? AND acc_taobao_share_id = ?", SpecialID, RelationID).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}

// UserProfileisExistBySpecialID is exist by SpecialId
func UserProfileisExistBySpecialID(Db *xorm.Engine, SpecialID string) (bool, error) {
has, err := Db.Where("acc_taobao_self_id = ? ", SpecialID).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}

// UserProfileCountByRelationID 统计relationID数量
func UserProfileCountByRelationID(Db *xorm.Engine) (total int64, err error) {
relate := new(model.UserProfile)
total, err = Db.Where("acc_taobao_share_id > 0").Count(relate)
return
}

// UserProfileCountByPUID 统计直推下级数量
func UserProfileCountByPUID(Db *xorm.Engine, puid int) (total int64, err error) {
relate := new(model.UserProfile)
total, err = Db.Where("parent_uid = ?", puid).Count(relate)
return
}

// UserProfileisExistByRelationID is exist by RelationID
func UserProfileisExistByRelationID(Db *xorm.Engine, RelationID string) (bool, error) {
has, err := Db.Where("acc_taobao_share_id = ? ", RelationID).Exist(&model.UserProfile{})

if err != nil {
return false, err
}
return has, nil
}

// UserProfileFindByIDs is in sql by ids
func UserProfileFindByIDs(Db *xorm.Engine, uids ...int) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.In("uid", uids).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileFindByIDsStr(Db *xorm.Engine, uids []string) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.In("uid", uids).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileByPuid search user_profile by parent_uid
func UserProfileByPuid(Db *xorm.Engine, puid interface{}) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.Where("parent_uid = ?", puid).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserProfileByPuidWithSess(sess *xorm.Session, puid interface{}) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := sess.Where("parent_uid = ?", puid).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersProfileInByIds is profiles by ids
func UsersProfileInByIds(Db *xorm.Engine, ids []int, limit, start int) (*[]model.UserProfile, error) {
var m []model.UserProfile
if limit == 0 && start == 0 {
if err := Db.In("uid", ids).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.In("uid", ids).Limit(limit, start).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersProfileInByUIDByisVerify is In查询 以及是否是有效用户
func UsersProfileInByUIDByisVerify(Db *xorm.Engine, ids []int, isVerify interface{}) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.In("uid", ids).Where("is_verify = ?", isVerify).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersProfileInByIdsByDesc is 根据某列 降序
func UsersProfileInByIdsByDesc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.UserProfile, error) {
var m []model.UserProfile
if limit == 0 && start == 0 {
if err := Db.In("uid", ids).Desc(c).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.In("uid", ids).Desc(c).Limit(limit, start).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersProfileInByIdsByAsc is 根据某列 升序
func UsersProfileInByIdsByAsc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.UserProfile, error) {
var m []model.UserProfile
if limit == 0 && start == 0 {
if err := Db.In("uid", ids).Asc(c).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.In("uid", ids).Asc(c).Limit(limit, start).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UsersProfileByAll is 查询所有分享id大于0的数据
func UsersProfileByTaobaoShateIdNotNull(Db *xorm.Engine, limit, start int) (*[]model.UserProfile, error) {
var m []model.UserProfile
if err := Db.Where("acc_taobao_share_id > 0").Limit(limit, start).Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserProfileIsExistByUserID is mobile exist
func UserProfileIsExistByUserID(Db *xorm.Engine, id int) (bool, error) {
has, err := Db.Where("uid = ?", id).Exist(&model.UserProfile{})
if err != nil {
return false, err
}
return has, nil
}

// UserProfileIsExistByInviteCode is exist ?
func UserProfileIsExistByInviteCode(Db *xorm.Engine, code string) (bool, error) {
has, err := Db.Where("invite_code = ?", code).Exist(&model.UserProfile{})
if err != nil {
return false, err
}
return has, nil
}

// UserProfileIsExistByCustomInviteCode is exist ?
func UserProfileIsExistByCustomInviteCode(Db *xorm.Engine, code string) (bool, error) {
has, err := Db.Where("custom_invite_code = ?", code).Exist(&model.UserProfile{})
if err != nil {
return false, err
}
return has, nil
}

// UserProfileInsert is insert user
func UserProfileInsert(Db *xorm.Engine, userProfile *model.UserProfile) (int64, error) {
affected, err := Db.Insert(userProfile)
if err != nil {
return 0, err
}
return affected, nil
}

// UserProfileUpdate is update userprofile
func UserProfileUpdate(Db *xorm.Engine, uid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) {
var (
affected int64
err error
)
if forceCols != nil {
affected, err = Db.Where("uid=?", uid).Cols(forceCols...).Update(userProfile)
} else {
affected, err = Db.Where("uid=?", uid).AllCols().Omit("fin_valid,parent_uid").Update(userProfile)
}

if err != nil {
return 0, logx.Warn(err)
}
return affected, nil
}
func UserProfileUpdateWithSess(sess *xorm.Session, uid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) {
var (
affected int64
err error
)
if forceCols != nil {
affected, err = sess.Where("uid=?", uid).Cols(forceCols...).Update(userProfile)
} else {
affected, err = sess.Where("uid=?", uid).AllCols().Omit("fin_valid").Update(userProfile)
}

if err != nil {
return 0, logx.Warn(err)
}
return affected, nil
}

// UserProfileUpdateByArkID is update userprofile
func UserProfileUpdateByArkID(Db *xorm.Engine, arkid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) {
var (
affected int64
err error
)
if forceCols != nil {
affected, err = Db.Where("arkid_uid=?", arkid).Cols(forceCols...).Update(userProfile)
} else {
affected, err = Db.Where("arkid_uid=?", arkid).Update(userProfile)
}
if err != nil {
return 0, logx.Warn(err)
}
return affected, nil
}

// UserProfileDelete is delete user profile
func UserProfileDelete(Db *xorm.Engine, uid interface{}) (int64, error) {
return Db.Where("uid = ?", uid).Delete(model.UserProfile{})
}
func UserProfileDeleteWithSess(sess *xorm.Session, uid interface{}) (int64, error) {
return sess.Where("uid = ?", uid).Delete(model.UserProfile{})
}
func UserProfileFindByIdWithSession(session *xorm.Session, uid int) (*model.UserProfile, error) {
var m model.UserProfile
if has, err := session.Where("uid = ?", uid).Get(&m); err != nil || has == false {
return nil, logx.Warn(err)
}
return &m, nil
}

// 在事务中更新用户信息
func UserProfileUpdateWithSession(session *xorm.Session, uid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) {
var (
affected int64
err error
)
if forceCols != nil {
affected, err = session.Where("uid=?", uid).Cols(forceCols...).Update(userProfile)
} else {
affected, err = session.Where("uid=?", uid).Omit("fin_valid").Update(userProfile)
}
if err != nil {
return 0, logx.Warn(err)
}
return affected, nil
}

// 根据uid获取md.user
func UserAllInfoByUid(Db *xorm.Engine, uid interface{}) (*md.User, error) {
u, err := UserFindByID(Db, uid)
if err != nil {
return nil, err
}
if u == nil {
return nil, errors.New("user is nil")
}
up, err := UserProfileFindByID(Db, uid)
if err != nil {
return nil, err
}
if utils.AnyToInt64(uid) == 0 {
userLevel, err := UserLevelInIDescByWeightLowWithOne(Db)
if err != nil {
return nil, err
}
if userLevel != nil {
u.Level = userLevel.Id
}
}
// 获取user 等级
ul, err := UserLevelByID(Db, u.Level)
if u.Uid == 0 {
one, err := UserLevelInIDescByWeightLowWithOne(Db)
if err != nil {
return nil, err
}
ul = one
}
if err != nil {
return nil, err
}

user := &md.User{
Info: u,
Profile: up,
Level: ul,
}
return user, nil
}

// UpdateUserProfileFinValid 更新用户余额
func UpdateUserProfileFinValid(Db *xorm.Engine, uid interface{}, newAmount string) error {
update, err := Db.Where("uid=?", uid).Update(&model.UserProfile{FinValid: newAmount})
if err != nil {
return err
}
if update != 1 {
return errors.New("更新失败")
}

return nil
}

// UpdateUserProfileFinValidWithSess 事务更新用户余额
func UpdateUserProfileFinValidWithSess(sess *xorm.Session, uid interface{}, newAmount string) error {
update, err := sess.Where("uid=?", uid).Update(&model.UserProfile{FinValid: newAmount})
if err != nil {
return err
}
if update != 1 {
return errors.New("更新失败")
}

return nil
}

+ 249
- 0
app/db/db_user_relate.go Visa fil

@@ -0,0 +1,249 @@
package db

import (
"applet/app/db/model"
"applet/app/utils/logx"

"xorm.io/xorm"
)

// UserRelateInsert is 插入一条数据到用户关系表
func UserRelateInsert(Db *xorm.Engine, userRelate *model.UserRelate) (int64, error) {
affected, err := Db.Insert(userRelate)
if err != nil {
return 0, err
}
return affected, nil
}
func UserRelateInsertWithSess(sess *xorm.Session, userRelate *model.UserRelate) (int64, error) {
affected, err := sess.Insert(userRelate)
if err != nil {
return 0, err
}
return affected, nil
}
func UserRelateUpdate(Db *xorm.Engine, userRelate *model.UserRelate) (int64, error) {
affected, err := Db.Where("parent_uid=? and uid=?", userRelate.ParentUid, userRelate.Uid).Cols("level,invite_time").Update(userRelate)
if err != nil {
return 0, err
}
return affected, nil
}

//UserRelateByPuid is 获取用户关系列表 by puid
func UserRelatesByPuid(Db *xorm.Engine, puid interface{}, limit, start int) (*[]model.UserRelate, error) {
var m []model.UserRelate
if limit == 0 && start == 0 {
if err := Db.Where("parent_uid = ?", puid).
Cols(`id,parent_uid,uid,level,invite_time`).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.Where("parent_uid = ?", puid).
Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}

return &m, nil
}

//UserRelatesByPuidByLv is 获取用户关系列表 by puid 和lv
func UserRelatesByPuidByLv(Db *xorm.Engine, puid, lv interface{}, limit, start int) (*[]model.UserRelate, error) {
var m []model.UserRelate
if limit == 0 && start == 0 {
if err := Db.Where("parent_uid = ? AND level = ?", puid, lv).
Cols(`id,parent_uid,uid,level,invite_time`).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.Where("parent_uid = ? AND level = ?", puid, lv).
Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}

return &m, nil
}

//UserRelatesByPuidByLvByTime is 获取直属 level =1用户关系列表 by puid 和lv by time
func UserRelatesByPuidByLvByTime(Db *xorm.Engine, puid, lv, stime, etime interface{}, limit, start int) (*[]model.UserRelate, error) {
var m []model.UserRelate
if limit == 0 && start == 0 {
if err := Db.Where("parent_uid = ? AND level = ? AND invite_time > ? AND invite_time < ?", puid, lv, stime, etime).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.Where("parent_uid = ? AND level = ? AND invite_time > ? AND invite_time < ?", puid, lv, stime, etime).
Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}

return &m, nil
}

//UserRelatesByPuidByTime is 获取户关系列表 by puid 和lv by time
func UserRelatesByPuidByTime(Db *xorm.Engine, puid, stime, etime interface{}, limit, start int) (*[]model.UserRelate, error) {
var m []model.UserRelate
if limit == 0 && start == 0 {
if err := Db.Where("parent_uid = ? AND invite_time > ? AND invite_time < ?", puid, stime, etime).
Cols(`id,parent_uid,uid,level,invite_time`).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.Where("parent_uid = ? AND invite_time > ? AND invite_time < ?", puid, stime, etime).
Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}

return &m, nil
}

//UserRelatesByPuidExceptLv is 获取用户关系列表 by puid 和非 lv
func UserRelatesByPuidExceptLv(Db *xorm.Engine, puid, lv interface{}, limit, start int) (*[]model.UserRelate, error) {
var m []model.UserRelate
if limit == 0 && start == 0 {
if err := Db.Where("parent_uid = ? AND level != ?", puid, lv).
Cols(`id,parent_uid,uid,level,invite_time`).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
if err := Db.Where("parent_uid = ? AND level != ?", puid, lv).
Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start).
Find(&m); err != nil {
return nil, logx.Warn(err)
}

return &m, nil
}

//UserRelateByUID is 获取用户关系表 by uid
func UserRelateByUID(Db *xorm.Engine, uid interface{}) (*model.UserRelate, bool, error) {
r := new(model.UserRelate)
has, err := Db.Where("uid=?", uid).Get(r)
if err != nil {
return nil, false, err
}
return r, has, nil
}

//UserRelateByUIDByLv is 获取用户关系表 by uid
func UserRelateByUIDByLv(Db *xorm.Engine, uid, lv interface{}) (*model.UserRelate, bool, error) {
r := new(model.UserRelate)
has, err := Db.Where("uid=? AND level=?", uid, lv).Get(r)
if err != nil {
return nil, false, err
}
return r, has, nil
}

//UserRelateByUIDAndPUID 根据 Puid 和uid 查找 ,用于确认关联
func UserRelateByUIDAndPUID(Db *xorm.Engine, uid, puid interface{}) (*model.UserRelate, bool, error) {
r := new(model.UserRelate)
has, err := Db.Where("uid=? AND parent_uid=?", uid, puid).Get(r)
if err != nil {
return nil, false, err
}
return r, has, nil
}

//UserRelatesByPuIDAndLv is 查询用户关系表 获取指定等级和puid的关系
func UserRelatesByPuIDAndLv(Db *xorm.Engine, puid, lv interface{}) (*[]model.UserRelate, error) {
var m []model.UserRelate
if err := Db.Where("parent_uid = ? AND level = ?", puid, lv).
Cols(`id,parent_uid,uid,level,invite_time`).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserRelateInByUID is In查询
func UserRelateInByUID(Db *xorm.Engine, ids []int) (*[]model.UserRelate, error) {
var m []model.UserRelate
if err := Db.In("uid", ids).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

// UserRelatesByUIDDescLv is Where 查询 根据level 降序
func UserRelatesByUIDDescLv(Db *xorm.Engine, id interface{}) (*[]model.UserRelate, error) {
var m []model.UserRelate
if err := Db.Where("uid = ?", id).Desc("level").
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}
func UserRelatesByInvite(Db *xorm.Engine, times interface{}) (*[]model.UserRelate, error) {
var m []model.UserRelate
if err := Db.Where("invite_time >= ?", times).
Find(&m); err != nil {
return nil, logx.Warn(err)
}
return &m, nil
}

//UserRelateCountByPUID is 根据puid 计数
func UserRelateCountByPUID(Db *xorm.Engine, pid interface{}) (int64, error) {

count, err := Db.Where("parent_uid = ?", pid).Count(model.UserRelate{})
if err != nil {
return 0, nil
}
return count, nil
}

//UserRelateDelete is 删除关联他上级的关系记录,以及删除他下级的关联记录
func UserRelateDelete(Db *xorm.Engine, uid interface{}) (int64, error) {
// 删除与之上级的记录
_, err := Db.Where("uid = ?", uid).Delete(model.UserRelate{})
if err != nil {
return 0, err
}
// 删除与之下级的记录
_, err = Db.Where("parent_uid = ?", uid).Delete(model.UserRelate{})
if err != nil {
return 0, err
}

return 1, nil
}
func UserRelateDeleteWithSession(sess *xorm.Session, uid interface{}) (int64, error) {
// 删除与之上级的记录
_, err := sess.Where("uid = ?", uid).Delete(model.UserRelate{})
if err != nil {
return 0, err
}
// 删除与之下级的记录
_, err = sess.Where("parent_uid = ?", uid).Delete(model.UserRelate{})
if err != nil {
return 0, err
}

return 1, nil
}

//UserRelateDelete is 删除关联他上级的关系记录
func UserRelateExtendDelete(Db *xorm.Engine, uid interface{}) (int64, error) {
// 删除与之上级的记录
_, err := Db.Where("uid = ?", uid).Delete(model.UserRelate{})
if err != nil {
return 0, err
}
return 1, nil
}

+ 104
- 0
app/db/dbs.go Visa fil

@@ -0,0 +1,104 @@
package db

import (
"fmt"
"os"
"time"

"xorm.io/xorm"
"xorm.io/xorm/log"

"applet/app/cfg"
"applet/app/db/model"
"applet/app/utils/logx"
)

var DBs map[string]*xorm.Engine

// 每个站长都要有自己的syscfg 缓存, 键是站长id,值是缓存名
// var SysCfgMapKey map[string]string

func NewDB(c *cfg.DBCfg) (*xorm.Engine, error) {
db, err := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name))
if err != nil {
return nil, err
}
db.SetConnMaxLifetime(c.MaxLifetime * time.Second)
db.SetMaxOpenConns(c.MaxOpenConns)
db.SetMaxIdleConns(c.MaxIdleConns)
err = db.Ping()
if err != nil {
return nil, err
}
if c.ShowLog {
db.ShowSQL(true)
db.Logger().SetLevel(log.LOG_DEBUG)
f, err := os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
os.RemoveAll(c.Path)
if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil {
return nil, err
}
}
logger := log.NewSimpleLogger(f)
logger.ShowSQL(true)
db.SetLogger(logger)
}
return db, nil
}

// InitDBs is 初始化多数据库
func InitDBs(ch chan int) {
// 初始化多数据库
var tables *[]model.DbMapping
InitMapDbs(cfg.DB, cfg.Prd)
ch <- 1
// 每10s 查询一次模板数据库的db mapping 表,如果有新增数据库记录,则添加到 DBs中
ticker := time.NewTicker(time.Duration(time.Second * 120))
for range ticker.C {
if cfg.Prd {
tables = GetAllDatabasePrd() //默认获取全部
} else {
tables = GetAllDatabaseDev() //默认获取全部
}
if tables == nil {
logx.Warn("no database tables data")
continue
}
for _, item := range *tables {
_, ok := DBs[item.DbMasterId]
if !ok {
// 不在db.DBs 则添加进去
dbCfg := cfg.DBCfg{
Name: item.DbName,
ShowLog: cfg.DB.ShowLog,
MaxLifetime: cfg.DB.MaxLifetime,
MaxOpenConns: cfg.DB.MaxOpenConns,
MaxIdleConns: cfg.DB.MaxIdleConns,
Path: fmt.Sprintf(cfg.DB.Path, item.DbName),
}
if item.DbHost != "" && item.DbUsername != "" && item.DbPassword != "" {
dbCfg.Host = item.DbHost
dbCfg.User = item.DbUsername
dbCfg.Psw = item.DbPassword
} else {
dbCfg.Host = cfg.DB.Host
dbCfg.User = cfg.DB.User
dbCfg.Psw = cfg.DB.Psw
}
e, err := NewDB(&dbCfg)
if err != nil || e == nil {
logx.Warnf("db engine can't create, please check config, params[host:%s, user:%s, psw: %s, name: %s], err: %v", dbCfg.Host, dbCfg.User, dbCfg.Psw, dbCfg.Name, err)
} else {
DBs[item.DbMasterId] = e
}
}
// 如果 被禁用则删除
if item.DeletedAt == 1 {
logx.Infof("%s have been removed", item.DbMasterId)
delete(DBs, item.DbMasterId)
}
}
}

}

+ 232
- 0
app/db/dbs_map.go Visa fil

@@ -0,0 +1,232 @@
package db

import (
model2 "applet/app/db/offical/model"
"errors"
"fmt"

"xorm.io/xorm"

"applet/app/cfg"
"applet/app/db/model"
"applet/app/utils/logx"
)

func MapBaseExists() (bool, error) {
return Db.IsTableExist("db_mapping")
}

func InitMapDbs(c *cfg.DBCfg, prd bool) {
var tables *[]model.DbMapping
exists, err := MapBaseExists()
if !exists || err != nil {
logx.Fatalf("db_mapping not exists : %v", err)
}
// tables := MapAllDatabases(debug)
if prd {
tables = GetAllDatabasePrd() //debug 获取生产
} else {
tables = GetAllDatabaseDev() //debug 获取开发
}

if tables == nil {
logx.Fatal("no database tables data")
}
var e *xorm.Engine
DBs = map[string]*xorm.Engine{}
for _, v := range *tables {
if v.DbName != "" && v.DeletedAt == 0 && v.DbName != c.Name {
dbCfg := cfg.DBCfg{
Name: v.DbName,
ShowLog: c.ShowLog,
MaxLifetime: c.MaxLifetime,
MaxOpenConns: c.MaxOpenConns,
MaxIdleConns: c.MaxIdleConns,
Path: fmt.Sprintf(c.Path, v.DbName),
}
if v.DbHost != "" && v.DbUsername != "" && v.DbPassword != "" {
dbCfg.Host = v.DbHost
dbCfg.User = v.DbUsername
dbCfg.Psw = v.DbPassword
} else {
dbCfg.Host = c.Host
dbCfg.User = c.User
dbCfg.Psw = c.Psw
}
e, err = NewDB(&dbCfg)
if err != nil || e == nil {
logx.Warnf("db engine can't create, please check config, params[host:%s, user:%s, psw: %s, name: %s], err: %v", dbCfg.Host, dbCfg.User, dbCfg.Psw, dbCfg.Name, err)
} else {
DBs[v.DbMasterId] = e
}
}
}
}

func MapAllDatabases(debug bool) *[]model.DbMapping {
sql := "`db_name` != ?"
if debug {
sql = "`db_name` = ?"
}
var m []model.DbMapping
if err := Db.Where(sql, cfg.DB.Name).Find(&m); err != nil || len(m) == 0 {
logx.Warn(err)
return nil
}
return &m
}

// GetAllDatabasePrd is 获取生成库 所有db 除了 deleted_at = 1 的
func GetAllDatabasePrd() *[]model.DbMapping {
var m []model.DbMapping
if err := Db.Where("deleted_at != ? AND is_dev = '0' ", 1).Find(&m); err != nil || len(m) == 0 {
logx.Warn(err)
return nil
}
return &m
}

// GetAllDatabaseDev is 获取开发库 所有db 除了 deleted_at = 1 的
func GetAllDatabaseDev() *[]model.DbMapping {
var m []model.DbMapping
var err error
if cfg.Local { // 本地调试 加快速度
//fmt.Println("notice:LOCAL TEST, only masterId:** 123456 ** available!")
err = Db.Where("deleted_at != ? AND is_dev = '1' AND db_master_id=?", 1, 123456).Find(&m)
//err = Db.Where(" db_master_id=?", 36274003).Find(&m)
} else {
err = Db.Where("deleted_at != ? AND is_dev = '1' ", 1).Find(&m)
}

//err := Db.Where("deleted_at != ? AND is_dev = '1' and db_master_id='123456'", 1).Find(&m)
if err != nil || len(m) == 0 {
logx.Warn(err)
return nil
}
return &m
}

// GetDatabaseByMasterID is 根据站长id 获取对应的的数据库信息
func GetDatabaseByMasterID(Db *xorm.Engine, id string) (*model.DbMapping, error) {
var m model.DbMapping
has, err := Db.Where("db_master_id=?", id).Get(&m)
if !has {
return nil, errors.New("Not Found DB data by " + id)
}
if err != nil {
return nil, err
}
if m.DbHost == "" {
m.DbHost = cfg.DB.Host
m.DbUsername = cfg.DB.User
m.DbPassword = cfg.DB.Psw
}
return &m, nil
}

// SessionGetDatabaseByMasterID is 根据站长id 获取对应的的数据库信息
func SessionGetDatabaseByMasterID(Db *xorm.Session, id string) (*model.DbMapping, error) {
var m model.DbMapping
has, err := Db.Where("db_master_id=?", id).Get(&m)
if !has {
return nil, errors.New("Not Found DB data by " + id)
}
if err != nil {
return nil, err
}
if m.DbHost == "" {
m.DbHost = cfg.DB.Host
m.DbName = cfg.DB.Name
m.DbUsername = cfg.DB.User
m.DbPassword = cfg.DB.Psw
}
return &m, nil
}

// 获取自动任务队列
func MapCrontabCfg(eg *xorm.Engine) *[]model.SysCfg {
var c []model.SysCfg
// 数据库查询如果有下划线会认为是一个任意字符
if err := eg.Where("`key` LIKE 'cron\\_%' AND val != ''").Cols("`key`,`val`").Find(&c); err != nil || len(c) == 0 {
logx.Warn(err)
return nil
}
return &c
}

// 获取官方域名
func GetOfficialDomainInfoByType(Db *xorm.Engine, masterId, key string) (string, error) {
type SysCfg struct {
K string
V string
Memo string
}
var domainBase SysCfg

has, err := Db.Where("k=?", "domain_wap_base").Get(&domainBase)
if err != nil {
return "", err
}
if has == false {
return "", errors.New("can not find key by : domain_base")
}

if key == "wap" {
return masterId + "." + domainBase.V, nil
}

if key == "api" {
var apiDomain SysCfg
has, err = Db.Where("k=?", "domain_api_base").Get(&apiDomain)
if err != nil {
return "", err
}
if has == false {
return "", errors.New("can not find key by : domain_api_base")
}
return apiDomain.V, nil
}

if key == "admin" {
return "admin." + masterId + "." + domainBase.V, nil
}
// 默认返回H5的
return masterId + "." + domainBase.V, nil
}
func GetOfficialDomainInfoByTypeToAgent(Db *xorm.Engine, masterId, uuid, key string) (string, error) {
type SysCfg struct {
K string
V string
Memo string
}
var domainBase model2.MasterListCfg
has, err := Db.Where("uid=? and k=?", uuid, "domain_base").Get(&domainBase)
if err != nil {
return "", err
}
if has == false {
return "", errors.New("can not find key by : domain_base")
}

if key == "wap" {
return masterId + ".h5." + domainBase.V, nil
}

if key == "api" {
var apiDomain SysCfg
has, err = Db.Where("k=?", "domain_api_base").Get(&apiDomain)
if err != nil {
return "", err
}
if has == false {
return "", errors.New("can not find key by : domain_api_base")
}
return apiDomain.V, nil
}

if key == "admin" {
return "admin." + masterId + "." + domainBase.V, nil
}
// 默认返回H5的
return masterId + "." + domainBase.V, nil
}

+ 55
- 0
app/db/dbs_sys_cfg.go Visa fil

@@ -0,0 +1,55 @@
package db

import (
"xorm.io/xorm"

"applet/app/db/model"
"applet/app/utils/logx"
)

// 系统配置get
func DbsSysCfgGetAll(eg *xorm.Engine) (*[]model.SysCfg, error) {
var cfgList []model.SysCfg
if err := eg.Cols("`key`,`val`").Find(&cfgList); cfgList == nil || err != nil {
return nil, logx.Error(err)
}
return &cfgList, nil
}

// 获取一条记录
func DbsSysCfgGet(eg *xorm.Engine, key string) (*model.SysCfg, error) {
var cfgList model.SysCfg
if has, err := eg.Where("`key`=?", key).Get(&cfgList); err != nil || has == false {
return nil, logx.Error(err)
}
return &cfgList, nil
}

func DbsSysCfgInsert(eg *xorm.Engine, key, val string) bool {
cfg := model.SysCfg{Key: key, Val: val}
_, err := eg.Where("`key`=?", key).Cols("val,memo").Update(&cfg)
if err != nil {
logx.Error(err)
return false
}
return true
}
func DbsSysCfgInserts(eg *xorm.Engine, key, val string) bool {
cfg := model.SysCfg{Key: key, Val: val}
_, err := eg.InsertOne(&cfg)
if err != nil {
logx.Error(err)
return false
}
return true
}

func DbsSysCfgUpdate(eg *xorm.Engine, key, val string) bool {
cfg := model.SysCfg{Key: key, Val: val}
_, err := eg.Where("`key`=?", key).Cols("val").Update(&cfg)
if err != nil {
logx.Error(err)
return false
}
return true
}

+ 19
- 0
app/db/model/cloud_bundle.go Visa fil

@@ -0,0 +1,19 @@
package model

type CloudBundle struct {
Id int `json:"id" xorm:"not null pk autoincr INT(10)"`
Os int `json:"os" xorm:"not null default 1 comment('系统类型:1.Android; 2.IOS') TINYINT(1)"`
Ep int `json:"ep" xorm:" default 0 comment('') TINYINT(1)"`
Version string `json:"version" xorm:"not null default '' comment('版本号') VARCHAR(255)"`
Modules string `json:"modules" xorm:"not null default '' comment('包含的模块') VARCHAR(255)"`
ApplyAt int `json:"apply_at" xorm:"comment('申请时间') INT(11)"`
FinishAt int `json:"finish_at" xorm:"comment('完成时间') INT(11)"`
IsAuditing int `json:"is_auditing" xorm:"comment('完成时间') INT(11)"`
State int `json:"state" xorm:"not null default 1 comment('状态:正在排队0,正在同步代码1,正在更新配置2,正在混淆3,正在打包4,正在上传5,打包成功999,异常-1') SMALLINT(5)"`
Memo string `json:"memo" xorm:"comment('备注') TEXT"`
ErrorMsg string `json:"error_msg" xorm:"comment('错误信息') TEXT"`
Src string `json:"src" xorm:"comment('包源地址') VARCHAR(255)"`
BuildId string `json:"build_id" xorm:"comment('build版本ID') VARCHAR(255)"`
BuildNumber string `json:"build_number" xorm:"default '' VARCHAR(255)"`
TemplateDuringAudit string `json:"template_during_audit" xorm:"not null default '' VARCHAR(255)"`
}

+ 10
- 0
app/db/model/community_team_cate.go Visa fil

@@ -0,0 +1,10 @@
package model

type CommunityTeamCate struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"default 0 comment('0是官方') INT(11)"`
StoreType int `json:"store_type" xorm:"default 0 comment('0官方自营店 1加盟店 2连锁店') INT(11)"`
Title string `json:"title" xorm:"VARCHAR(255)"`
Sort int `json:"sort" xorm:"default 0 INT(11)"`
IsShow int `json:"is_show" xorm:"default 0 INT(1)"`
}

+ 27
- 0
app/db/model/community_team_coupon.go Visa fil

@@ -0,0 +1,27 @@
package model

import (
"time"
)

type CommunityTeamCoupon struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Name string `json:"name" xorm:"comment('方案名称') VARCHAR(255)"`
Comment string `json:"comment" xorm:"comment('备注') VARCHAR(2048)"`
PublishTime time.Time `json:"publish_time" xorm:"comment('立即发布时间') DATETIME"`
Kind int `json:"kind" xorm:"not null comment('优惠券类型,1:立减,2:满减,3折扣') TINYINT(1)"`
IsReach int `json:"is_reach" xorm:"comment('是否有门槛,1:有,2:否;优惠券类型为3折扣时') TINYINT(1)"`
Cal string `json:"cal" xorm:"comment('满减及折扣有门槛时算法,{"reach": "20.12", "reduce": "2.2"}, reach:满X元,减/折reduce') VARCHAR(255)"`
State int `json:"state" xorm:"not null default 1 comment('状态,是否使用(1:使用;2:不使用)') TINYINT(1)"`
ActivityTimeStart time.Time `json:"activity_time_start" xorm:"not null comment('活动起止时间,开始时间') DATETIME"`
ActivityTimeEnd time.Time `json:"activity_time_end" xorm:"not null comment('活动起止时间,结束时间') DATETIME"`
ActivityStatement string `json:"activity_statement" xorm:"not null default '0' comment('活动规则说明') VARCHAR(5000)"`
Sort int `json:"sort" xorm:"comment('排序') INT(11)"`
Ext string `json:"ext" xorm:"comment('拓展字段') TEXT"`
IsPublishNow int `json:"is_publish_now" xorm:"not null default 0 comment('是否立即发布,0:否,1:是') TINYINT(1)"`
CreatedTime time.Time `json:"created_time" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') DATETIME"`
UpdatedTime time.Time `json:"updated_time" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') DATETIME"`
DeletedTime time.Time `json:"deleted_time" xorm:"comment('删除时间') DATETIME"`
StoreId int `json:"store_id" xorm:"default 0 INT(11)"`
StoreType int `json:"store_type" xorm:"default 0 comment('0官方自营店 1加盟店 2连锁店') INT(11)"`
}

+ 25
- 0
app/db/model/community_team_coupon_user.go Visa fil

@@ -0,0 +1,25 @@
package model

import (
"time"
)

type CommunityTeamCouponUser struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Uid int `json:"uid" xorm:"comment('用户id') index INT(11)"`
MerchantSchemeId int `json:"merchant_scheme_id" xorm:"comment('优惠券方案的id') INT(11)"`
IsUse int `json:"is_use" xorm:"comment('是否已使用:0否1是2失效') TINYINT(1)"`
Kind int `json:"kind" xorm:"comment('优惠券类型:1立减2满减3折扣') TINYINT(1)"`
Cal string `json:"cal" xorm:"not null default '0.00' comment('折扣算法json:形式:{"reach":"10.00", "reduce":"1.00"},无门槛reach为0') VARCHAR(255)"`
ValidTimeStart time.Time `json:"valid_time_start" xorm:"comment('有效日期开始') DATETIME"`
ValidTimeEnd time.Time `json:"valid_time_end" xorm:"comment('有效日期结束') DATETIME"`
UseRule int `json:"use_rule" xorm:"comment('1全部商品可用2指定商品3指定活动类型') TINYINT(1)"`
UseActivityType int `json:"use_activity_type" xorm:"comment('可用的活动类型: 1拼团活动 2秒杀活动 3砍价活动') TINYINT(1)"`
CreateTime time.Time `json:"create_time" xorm:"default CURRENT_TIMESTAMP comment('创建时间') DATETIME"`
UpdateTime time.Time `json:"update_time" xorm:"default CURRENT_TIMESTAMP comment('更新时间') DATETIME"`
StoreId int `json:"store_id" xorm:"default 0 comment('0是官方') INT(11)"`
StoreType int `json:"store_type" xorm:"default 0 comment('0官方自营店 1加盟店 2连锁店') INT(11)"`
Name string `json:"name" xorm:"comment('方案名称') VARCHAR(255)"`
ActivityStatement string `json:"activity_statement" xorm:"not null default '0' comment('活动规则说明') VARCHAR(5000)"`
Img string `json:"img" xorm:"VARCHAR(255)"`
}

+ 29
- 0
app/db/model/community_team_goods.go Visa fil

@@ -0,0 +1,29 @@
package model

import (
"time"
)

type CommunityTeamGoods struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"default 0 comment('0是官方') INT(11)"`
StoreType int `json:"store_type" xorm:"default 0 comment('0官方自营店 1加盟店 2连锁店') INT(11)"`
Title string `json:"title" xorm:"VARCHAR(255)"`
Img string `json:"img" xorm:"VARCHAR(255)"`
Info string `json:"info" xorm:"comment('描述') VARCHAR(255)"`
Cid int `json:"cid" xorm:"default 0 INT(11)"`
State int `json:"state" xorm:"default 0 comment('0上架 1下架') INT(11)"`
CreateAt time.Time `json:"create_at" xorm:"DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"DATETIME"`
Price string `json:"price" xorm:"DECIMAL(10,2)"`
Stock int `json:"stock" xorm:"default 0 INT(11)"`
Spe string `json:"spe" xorm:"not null default '' comment('所有规格属性json') VARCHAR(5012)"`
LinePrice string `json:"line_price" xorm:"not null default 0.00 comment('划线价') DECIMAL(12,2)"`
SpeImages string `json:"spe_images" xorm:"not null comment('第一组规格值对应的图片json') TEXT"`
IsSingleSku int `json:"is_single_sku" xorm:"not null default 1 comment('是否单规格,0:否,1是') TINYINT(1)"`
Sort int `json:"sort" xorm:"default 0 INT(11)"`
IsSpeImageOn int `json:"is_spe_image_on" xorm:"not null default 0 comment('是否开启规格图片:0否 1是') TINYINT(1)"`
Commission string `json:"commission" xorm:"default 0.00 DECIMAL(20,2)"`
ImageList string `json:"image_list" xorm:"comment('商品图json') TEXT"`
SaleCount int `json:"sale_count" xorm:"default 0 INT(11)"`
}

+ 37
- 0
app/db/model/community_team_order.go Visa fil

@@ -0,0 +1,37 @@
package model

import (
"time"
)

type CommunityTeamOrder struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"default 0 INT(11)"`
StoreType int `json:"store_type" xorm:"default 0 comment('0官方自营店 1加盟店 2连锁店') INT(11)"`
StoreUid int `json:"store_uid" xorm:"default 0 comment('门店用户id') INT(11)"`
ParentUid int `json:"parent_uid" xorm:"default 0 comment('上级代理') INT(11)"`
Num int `json:"num" xorm:"default 0 comment('') INT(11)"`
CouponId int `json:"coupon_id" xorm:"default 0 comment('') INT(11)"`
Address string `json:"address" xorm:"comment('详细地址') VARCHAR(255)"`
Commission string `json:"commission" xorm:"default 0.00 comment('分佣(元)') DECIMAL(20,2)"`
CreateAt time.Time `json:"create_at" xorm:"DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"DATETIME"`
BuyPhone string `json:"buy_phone" xorm:"VARCHAR(255)"`
Phone string `json:"phone" xorm:"VARCHAR(255)"`
BuyName string `json:"buy_name" xorm:"VARCHAR(255)"`
State int `json:"state" xorm:"default 0 comment('0待付款 1已支付 2已提货') INT(11)"`
PayAt time.Time `json:"pay_at" xorm:"comment('付款时间') DATETIME"`
ConfirmAt time.Time `json:"confirm_at" xorm:"comment('提货时间') DATETIME"`
Oid int64 `json:"oid" xorm:"default 0 comment('主单号') BIGINT(20)"`
Code string `json:"code" xorm:"comment('提货码') VARCHAR(255)"`
Type int `json:"type" xorm:"default 0 comment('0自提 1外卖') INT(1)"`
PayMethod int `json:"pay_method" xorm:"default 0 comment('1余额 2支付宝 3微信') INT(11)"`
PayId string `json:"pay_id" xorm:"comment('第三方的支付id') VARCHAR(255)"`
Amount string `json:"amount" xorm:"default 0.00 comment('总金额') DECIMAL(20,2)"`
Memo string `json:"memo" xorm:"comment('备注') VARCHAR(255)"`
TakeTime time.Time `json:"take_time" xorm:"comment('预计提货时间') DATETIME"`
MealNum int `json:"meal_num" xorm:"default 0 comment('餐具数量') INT(11)"`
Coupon string `json:"coupon" xorm:"default 0.00 DECIMAL(10,2)"`
Timer string `json:"timer" xorm:"comment('预计提货时间') VARCHAR(255)"`
IsNow int `json:"is_now" xorm:"default 0 comment('是否立即提货') INT(1)"`
}

+ 13
- 0
app/db/model/community_team_order_info.go Visa fil

@@ -0,0 +1,13 @@
package model

type CommunityTeamOrderInfo struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Oid int64 `json:"oid" xorm:"BIGINT(20)"`
Title string `json:"title" xorm:"comment('标题') VARCHAR(255)"`
Img string `json:"img" xorm:"comment('图片') VARCHAR(255)"`
Price string `json:"price" xorm:"default 0.00 comment('单价') DECIMAL(10,2)"`
Num int `json:"num" xorm:"default 0 comment('数量') INT(11)"`
SkuInfo string `json:"sku_info" xorm:"comment('sku信息') VARCHAR(255)"`
GoodsId int `json:"goods_id" xorm:"default 0 INT(11)"`
SkuId int `json:"sku_id" xorm:"default 0 INT(11)"`
}

+ 20
- 0
app/db/model/community_team_sku.go Visa fil

@@ -0,0 +1,20 @@
package model

import (
"time"
)

type CommunityTeamSku struct {
SkuId int64 `json:"sku_id" xorm:"not null pk autoincr BIGINT(20)"`
GoodsId int `json:"goods_id" xorm:"not null comment('商品id') INT(11)"`
Price string `json:"price" xorm:"not null default 0.00 comment('价格') DECIMAL(12,2)"`
CreateTime time.Time `json:"create_time" xorm:"default CURRENT_TIMESTAMP comment('创建时间') DATETIME"`
UpdateTime time.Time `json:"update_time" xorm:"default CURRENT_TIMESTAMP comment('更新时间') DATETIME"`
Stock int `json:"stock" xorm:"not null default 0 comment('库存') INT(11)"`
Indexes string `json:"indexes" xorm:"not null default '' comment('规格值组合的下标') VARCHAR(100)"`
Sku string `json:"sku" xorm:"not null comment('规格组合json') VARCHAR(2048)"`
SaleCount int `json:"sale_count" xorm:"not null default 0 comment('销量') INT(11)"`
Sort int `json:"sort" xorm:"not null default 0 comment('排序') INT(11)"`
Discount string `json:"discount" xorm:"default 10.00 comment('折扣,为10无折扣') DECIMAL(6,2)"`
SkuCode string `json:"sku_code" xorm:"default '' comment('sku编码') VARCHAR(255)"`
}

+ 24
- 0
app/db/model/community_team_store.go Visa fil

@@ -0,0 +1,24 @@
package model

import (
"time"
)

type CommunityTeamStore struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"default 0 INT(11)"`
StoreType int `json:"store_type" xorm:"default 0 comment('0官方自营店 1加盟店 2连锁店') INT(11)"`
ParentUid int `json:"parent_uid" xorm:"default 0 comment('上级代理') INT(11)"`
Lat string `json:"lat" xorm:"default 0.000000 comment('纬度') DECIMAL(30,6)"`
Lng string `json:"lng" xorm:"default 0.000000 comment('经度') DECIMAL(30,6)"`
Address string `json:"address" xorm:"comment('详细地址') VARCHAR(255)"`
Commission string `json:"commission" xorm:"default 0.00 comment('分佣比例%') DECIMAL(20,2)"`
CreateAt time.Time `json:"create_at" xorm:"DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"DATETIME"`
State int `json:"state" xorm:"default 0 comment('0非店长 1店长') INT(1)"`
WorkState int `json:"work_state" xorm:"default 0 comment('0营业中 1休息中') INT(1)"`
Name string `json:"name" xorm:"VARCHAR(255)"`
Province string `json:"province" xorm:"comment('省级的名称') VARCHAR(255)"`
City string `json:"city" xorm:"comment('市级的名称') VARCHAR(255)"`
District string `json:"district" xorm:"comment('县,区名称') VARCHAR(255)"`
}

+ 12
- 0
app/db/model/community_team_store_like.go Visa fil

@@ -0,0 +1,12 @@
package model

import (
"time"
)

type CommunityTeamStoreLike struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"default 0 INT(11)"`
StoreId int `json:"store_id" xorm:"default 0 INT(11)"`
Time time.Time `json:"time" xorm:"DATETIME"`
}

+ 18
- 0
app/db/model/db_mapping.go Visa fil

@@ -0,0 +1,18 @@
package model

import (
"time"
)

type DbMapping struct {
DbMasterId string `json:"db_master_id" xorm:"not pk null comment('站长id') VARCHAR(32)"`
DbHost string `json:"db_host" xorm:"not null default '' comment('数据库连接(带port)') VARCHAR(255)"`
DbUsername string `json:"db_username" xorm:"not null default '' comment('数据库用户名') VARCHAR(255)"`
DbPassword string `json:"db_password" xorm:"not null default '' comment('数据库用户名密码') VARCHAR(255)"`
DbName string `json:"db_name" xorm:"not null comment('数据库名') VARCHAR(255)"`
ExternalMysql string `json:"external_mysql" xorm:"not null default '0' comment('是否外部mysql(0是内部,1是外部)') VARCHAR(255)"`
IsDev int `json:"is_dev" xorm:"not null default 0 comment('开发库是1,0是生产库') TINYINT(1)"`
CreatedAt time.Time `json:"created_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"`
UpdatedAt time.Time `json:"updated_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"`
DeletedAt int `json:"deleted_at" xorm:"not null default 0 comment('是否已删除') TINYINT(1)"`
}

+ 30
- 0
app/db/model/fin_user_flow.go Visa fil

@@ -0,0 +1,30 @@
package model

import (
"time"
)

type FinUserFlow struct {
Id int64 `json:"id" xorm:"pk autoincr comment('流水编号') BIGINT(20)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"`
Type int `json:"type" xorm:"not null default 0 comment('0收入,1支出') TINYINT(1)"`
Amount string `json:"amount" xorm:"not null default 0.0000 comment('变动金额') DECIMAL(11,4)"`
BeforeAmount string `json:"before_amount" xorm:"not null default 0.0000 comment('变动前金额') DECIMAL(11,4)"`
AfterAmount string `json:"after_amount" xorm:"not null default 0.0000 comment('变动后金额') DECIMAL(11,4)"`
SysFee string `json:"sys_fee" xorm:"not null default 0.0000 comment('手续费') DECIMAL(11,4)"`
PaymentType int `json:"payment_type" xorm:"not null default 1 comment('1支付宝,2微信.3手动转账') TINYINT(1)"`
OrdType string `json:"ord_type" xorm:"not null default '' comment('订单类型taobao,jd,pdd,vip,suning,kaola,own自营,withdraw提现') VARCHAR(20)"`
OrdId string `json:"ord_id" xorm:"not null default '' comment('对应订单编号') VARCHAR(50)"`
OrdTitle string `json:"ord_title" xorm:"not null default '' comment('订单标题') VARCHAR(50)"`
OrdAction int `json:"ord_action" xorm:"not null default 0 comment('10自购,11推广,12团队,20提现,21消费') TINYINT(2)"`
OrdTime int `json:"ord_time" xorm:"not null default 0 comment('下单时间or提现时间') INT(11)"`
OrdDetail string `json:"ord_detail" xorm:"not null default '' comment('记录商品ID或提现账号') VARCHAR(50)"`
ExpectedTime string `json:"expected_time" xorm:"not null default '0' comment('预期到账时间,字符串用于直接显示,结算后清除内容') VARCHAR(30)"`
State int `json:"state" xorm:"not null default 1 comment('1未到账,2已到账') TINYINT(1)"`
Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(2000)"`
OtherId int64 `json:"other_id" xorm:"not null default 0 comment('其他关联订单,具体根据订单类型判断') BIGINT(20)"`
AliOrdId string `json:"ali_ord_id" xorm:"default '' comment('支付宝订单号') VARCHAR(128)"`
ExtendType int `json:"extend_type" xorm:"not null default 1 comment('') TINYINT(1)"`
CreateAt time.Time `json:"create_at" xorm:"created not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"updated not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"`
}

+ 7
- 0
app/db/model/sys_cfg.go Visa fil

@@ -0,0 +1,7 @@
package model

type SysCfg struct {
Key string `json:"key" xorm:"not null pk comment('键') VARCHAR(127)"`
Val string `json:"val" xorm:"comment('值') TEXT"`
Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"`
}

+ 35
- 0
app/db/model/sys_module.go Visa fil

@@ -0,0 +1,35 @@
package model

import (
"time"
)

type SysModule struct {
ModId int `json:"mod_id" xorm:"not null pk autoincr INT(10)"`
ModPid int `json:"mod_pid" xorm:"not null default 0 comment('父级模块ID') INT(10)"`
TemplateId int `json:"template_id" xorm:"not null default 0 comment('模板ID') INT(11)"`
ModName string `json:"mod_name" xorm:"not null default '' comment('模块名称') VARCHAR(250)"`
Position string `json:"position" xorm:"not null default '' comment('位置') VARCHAR(250)"`
SkipIdentifier string `json:"skip_identifier" xorm:"not null default '' comment('跳转标识') VARCHAR(250)"`
Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(128)"`
Subtitle string `json:"subtitle" xorm:"not null default '' comment('副标题') VARCHAR(255)"`
Url string `json:"url" xorm:"not null default '' comment('跳转链接') VARCHAR(512)"`
Margin string `json:"margin" xorm:"not null default '0,0,0,0' comment('边距,上右下左') VARCHAR(64)"`
AspectRatio string `json:"aspect_ratio" xorm:"not null default 0.00 comment('宽高比,宽/高保留两位小数') DECIMAL(4,2)"`
Icon string `json:"icon" xorm:"not null default '' comment('图标') VARCHAR(512)"`
Img string `json:"img" xorm:"not null default '' comment('图片') VARCHAR(512)"`
FontColor string `json:"font_color" xorm:"not null default '' comment('文字颜色') VARCHAR(128)"`
BgImg string `json:"bg_img" xorm:"not null default '' comment('背景图片') VARCHAR(512)"`
BgColor string `json:"bg_color" xorm:"not null default '' comment('背景颜色') VARCHAR(512)"`
BgColorT string `json:"bg_color_t" xorm:"not null default '' comment('背景颜色过度') VARCHAR(255)"`
Badge string `json:"badge" xorm:"not null default '' comment('badge图片') VARCHAR(512)"`
Path string `json:"path" xorm:"not null default '' comment('跳转路径') VARCHAR(255)"`
Data string `json:"data" xorm:"comment('内容') TEXT"`
Sort int `json:"sort" xorm:"not null default 0 comment('排序') INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 comment('排序') INT(11)"`
State int `json:"state" xorm:"not null default 1 comment('0不显示,1显示') TINYINT(1)"`
IsGlobal int `json:"is_global" xorm:"not null default 0 comment('是否全局显示') TINYINT(1)"`
Platform int `json:"platform" xorm:"not null default 1 comment('平台;1:全平台;2:App应用(ios和android);3:H5(wap);4:微信小程序;5:抖音小程序;6:百度小程序') TINYINT(1)"`
CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"`
}

+ 28
- 0
app/db/model/sys_popup.go Visa fil

@@ -0,0 +1,28 @@
package model

import (
"time"
)

type SysPopup struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 INT(11)"`
Name string `json:"name" xorm:"not null default '' VARCHAR(32)"`
ConditionType string `json:"condition_type" xorm:"not null default 'all' comment('展示人群类型;all:所有人;new_user:新用户;level:指定等级;tag:指定标签;no_order_user:未出单用户') VARCHAR(32)"`
Condition string `json:"condition" xorm:"not null comment('弹窗条件,json') TEXT"`
Position string `json:"position" xorm:"not null default 'index' comment('展示位置;index:首页') VARCHAR(64)"`
Image string `json:"image" xorm:"not null default '' comment('弹窗图片') VARCHAR(128)"`
Platform string `json:"platform" xorm:"not null default '' comment('弹窗图片') VARCHAR(255)"`
Interval int `json:"interval" xorm:"not null default 0 comment('弹窗时间间隔;单位:分钟') INT(11)"`
Skip string `json:"skip" xorm:"not null default '' comment('跳转标识') VARCHAR(255)"`
Type int `json:"type" xorm:"not null default 1 comment('弹窗时间类型;1:固定时间;2:每天定时') TINYINT(1)"`
PopupTime string `json:"popup_time" xorm:"comment('弹窗时间,json') TEXT"`
State int `json:"state" xorm:"not null default 0 comment('状态;0:不启用;1:启用') TINYINT(1)"`
Sort int `json:"sort" xorm:"not null default 0 comment('排序') INT(11)"`
PopupType int `json:"popup_type" xorm:"not null default 0 comment('弹窗类型 0活动弹窗 1任务弹窗') INT(11)"`
TaskType int `json:"task_type" xorm:"not null default 0 comment('任务类型') INT(11)"`
TaskFinishType int `json:"task_finish_type" xorm:"not null default 0 comment('任务完成状态') INT(11)"`
CreateAt time.Time `json:"create_at" xorm:"default 'CURRENT_TIMESTAMP' TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"default 'CURRENT_TIMESTAMP' TIMESTAMP"`
IsNotClose int `json:"is_not_close" xorm:"not null default 0 comment('不能关闭 0能关 1不能关') INT(1)"`
}

+ 22
- 0
app/db/model/sys_push_app.go Visa fil

@@ -0,0 +1,22 @@
package model

import (
"time"
)

type SysPushApp struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(32)"`
Content string `json:"content" xorm:"not null comment('内容') TEXT"`
Image string `json:"image" xorm:"not null default '' comment('图片(只有官方才有图片)') VARCHAR(255)"`
Provider string `json:"provider" xorm:"not null default 'mob' comment('平台供应商,如:mob,official:官方推送') VARCHAR(16)"`
Type string `json:"type" xorm:"not null default '' comment('模板类型 | 推送类型;public;:普通推送;activity:活动通知;order_self:新订单提醒(导购自购新订单),order_team:新订单提醒(团队新订单),order_share:新订单提醒(导购分享新订单),member_register:团队成员注册成功,level_upgrade:团队成员等级升级成功,withdraw_fail:提现失败提醒,withdraw_success:提现成功提醒,comission_settle_success:佣金结算提醒(平台结算)') VARCHAR(50)"`
SendAt int `json:"send_at" xorm:"not null default 0 comment('指定发送时间0为马上执行') INT(11)"`
State int `json:"state" xorm:"not null default 1 comment('1发送中,2成功,3失败,4部分成功') TINYINT(1)"`
DeviceProvider int `json:"device_provider" xorm:"default 1 comment('推送设备平台。1:全平台;2:安卓;3:ios') TINYINT(1)"`
Target int `json:"target" xorm:"not null default 1 comment('推送目标;1:全部会员;2:指定会员;3:指定等级;4:指定标签') TINYINT(1)"`
TargetCondition string `json:"target_condition" xorm:"comment('推送目标条件。json格式;') TEXT"`
Skip string `json:"skip" xorm:"not null default '' comment('跳转功能') VARCHAR(255)"`
CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"`
}

+ 19
- 0
app/db/model/sys_push_sms.go Visa fil

@@ -0,0 +1,19 @@
package model

import (
"time"
)

type SysPushSms struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Content string `json:"content" xorm:"not null comment('内容') TEXT"`
Provider string `json:"provider" xorm:"not null default '' comment('短信供应平台,暂时没有') VARCHAR(20)"`
SendAt int `json:"send_at" xorm:"not null default 0 comment('指定发送时间0为马上执行') INT(10)"`
State int `json:"state" xorm:"not null default 0 comment('0发送中,1成功,2失败,3部分成功') TINYINT(1)"`
Target int `json:"target" xorm:"not null default 1 comment('推送目标;1:全部会员;2:指定会员;3:指定等级;4:指定标签') TINYINT(1)"`
TargetCondition string `json:"target_condition" xorm:"comment('推送目标条件。json格式;') TEXT"`
Skip string `json:"skip" xorm:"not null default '' comment('跳转功能') VARCHAR(255)"`
CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"`
Type string `json:"type" xorm:"not null default '' comment('模板类型 | 推送类型;public;:普通推送;activity:活动通知;order_self:新订单提醒(导购自购新订单),order_team:新订单提醒(团队新订单),order_share:新订单提醒(导购分享新订单),member_register:团队成员注册成功,level_upgrade:团队成员等级升级成功,withdraw_fail:提现失败提醒,withdraw_success:提现成功提醒,comission_settle_success:佣金结算提醒(平台结算)') VARCHAR(50)"`
}

+ 17
- 0
app/db/model/sys_push_template.go Visa fil

@@ -0,0 +1,17 @@
package model

import (
"time"
)

type SysPushTemplate struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
IsAppPush int `json:"is_app_push" xorm:"not null default 1 comment('是否app推送') TINYINT(1)"`
IsSmsPush int `json:"is_sms_push" xorm:"not null default 0 comment('是否短信推送') TINYINT(1)"`
Type string `json:"type" xorm:"not null default '' comment('模板类型') VARCHAR(50)"`
Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(128)"`
Content string `json:"content" xorm:"not null comment('内容') TEXT"`
Skip string `json:"skip" xorm:"not null default '' comment('跳转功能') VARCHAR(255)"`
CreateAt time.Time `json:"create_at" xorm:"default CURRENT_TIMESTAMP TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"default CURRENT_TIMESTAMP TIMESTAMP"`
}

+ 18
- 0
app/db/model/sys_push_user.go Visa fil

@@ -0,0 +1,18 @@
package model

import (
"time"
)

type SysPushUser struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
PushId int `json:"push_id" xorm:"not null default 0 comment('sys_push_app表ID') index INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 INT(11)"`
State int `json:"state" xorm:"not null default 0 comment('发送状态;0:失败;1:成功') TINYINT(1)"`
Time time.Time `json:"time" xorm:"default CURRENT_TIMESTAMP comment('发送时间') TIMESTAMP"`
SendData string `json:"send_data" xorm:"comment('发送内容,json格式') TEXT"`
Provider string `json:"provider" xorm:"not null default 'mob' comment('平台供应商,如:mob,official:官方推送') VARCHAR(16)"`
Type string `json:"type" xorm:"not null default '' comment('模板类型 | 推送类型;public;:普通推送;activity:活动通知;order_self:新订单提醒(导购自购新订单),order_team:新订单提醒(团队新订单),order_share:新订单提醒(导购分享新订单),member_register:团队成员注册成功,level_upgrade:团队成员等级升级成功,withdraw_fail:提现失败提醒,withdraw_success:提现成功提醒,comission_settle_success:佣金结算提醒(平台结算)') VARCHAR(50)"`
SendAt int `json:"send_at" xorm:"not null default 0 comment('官方活动显示时间(大于当前时间戳才显示);0为即可显示') INT(11)"`
IsRead int `json:"is_read" xorm:"not null default 0 comment('是否已读;0:未读;1:已读') TINYINT(1)"`
}

+ 20
- 0
app/db/model/sys_template.go Visa fil

@@ -0,0 +1,20 @@
package model

import (
"time"
)

type SysTemplate struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 INT(11)"`
Name string `json:"name" xorm:"not null default '' comment('模板名称') VARCHAR(32)"`
Title string `json:"title" xorm:"not null default '' comment('页面title字段') VARCHAR(32)"`
Type string `json:"type" xorm:"not null default 'index' comment('模板类型;index:首页;bottom:底部导航栏;member:会员中心;custom:自定义模板;share_goods_image:商品图文分享;share_goods_link:商品链接分享;share_goods_platform_xx:商品分享平台(xx对应平台类型)') VARCHAR(64)"`
Image string `json:"image" xorm:"not null default '' VARCHAR(128)"`
IsUse int `json:"is_use" xorm:"default 0 comment('是否使用;1:使用;0未使用') TINYINT(1)"`
Remark string `json:"remark" xorm:"not null default '' comment('备注') VARCHAR(128)"`
LimitData string `json:"limit_data" xorm:"not null comment('') TEXT"`
IsSystem int `json:"is_system" xorm:"not null default 0 comment('是否系统模板;0:否;1:是') TINYINT(1)"`
CreateAt time.Time `json:"create_at" xorm:"default CURRENT_TIMESTAMP TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"default CURRENT_TIMESTAMP TIMESTAMP"`
}

+ 37
- 0
app/db/model/user.go Visa fil

@@ -0,0 +1,37 @@
package model

import (
"time"
)

type User struct {
Uid int `json:"uid" xorm:"not null pk autoincr comment('主键ID') INT(10)"`
Username string `json:"username" xorm:"not null default '' comment('用户名') index VARCHAR(50)"`
Password string `json:"password" xorm:"not null default '' comment('密码') CHAR(32)"`
Passcode string `json:"passcode" xorm:"not null default '' comment('支付密码') CHAR(32)"`
Email string `json:"email" xorm:"not null default '' comment('邮箱') VARCHAR(128)"`
Phone string `json:"phone" xorm:"not null default '' comment('联系电话') index VARCHAR(20)"`
Nickname string `json:"nickname" xorm:"not null default '' comment('昵称') VARCHAR(20)"`
Level int `json:"level" xorm:"not null default 0 comment('用户等级id') INT(11)"`
IsStore int `json:"is_store" xorm:"not null default 0 comment('') INT(11)"`
InviteTotal int `json:"invite_total" xorm:"not null default 0 comment('直推邀请总人数') INT(11)"`
LevelArriveAt time.Time `json:"level_arrive_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('到达该等级的时间') TIMESTAMP"`
LevelExpireAt time.Time `json:"level_expire_at" xorm:"not null default '0000-00-00 00:00:00' comment('该等级过期时间') TIMESTAMP"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"default 'CURRENT_TIMESTAMP' comment('最后修改资料时间') TIMESTAMP"`
LastLoginAt time.Time `json:"last_login_at" xorm:"default 'CURRENT_TIMESTAMP' comment('最近登录时间') TIMESTAMP"`
DeleteAt int `json:"delete_at" xorm:"not null default 0 comment('是否删除;0未删除;1已删除') TINYINT(1)"`
State int `json:"state" xorm:"not null default 1 comment('0未激活,1正常,2冻结') TINYINT(1)"`
LastLoginIp string `json:"last_login_ip" xorm:"not null default '' comment('最后登录IP') VARCHAR(64)"`
RegisterIp string `json:"register_ip" xorm:"not null default '' comment('注册IP') VARCHAR(64)"`
IsFake int `json:"is_fake" xorm:"not null default 0 comment('0真实 1虚拟') TINYINT(1)"`
IsMarketer int `json:"is_marketer" xorm:"not null default 0 comment('是否市商 0否 1是') TINYINT(1)"`
CanChangeLv int `json:"can_change_lv" xorm:"not null default 0 comment('是否市商 0否 1是') TINYINT(1)"`
IsPop int `json:"is_pop" xorm:"not null default 0 comment('是否市商 0否 1是') TINYINT(1)"`
IsNotAddMoments int `json:"is_not_add_moments" xorm:"not null default 0 comment('是否市商 0否 1是') TINYINT(1)"`
Zone string `json:"zone" xorm:"not null default '86' comment('区号') VARCHAR(100)"`
SalePhone string `json:"sale_phone" xorm:"not null default '' comment('') VARCHAR(100)"`
Platform string `json:"platform" xorm:"not null default '' comment('') VARCHAR(100)"`
ImportFinTotal string `json:"import_fin_total" xorm:"not null default 0.000000 comment('累计总收益') DECIMAL(30,4)"`
FinTotal string `json:"fin_total" xorm:"not null default 0.000000 comment('累计总收益') DECIMAL(30,4)"`
}

+ 8
- 0
app/db/model/user_app_domain.go Visa fil

@@ -0,0 +1,8 @@
package model

type UserAppDomain struct {
Domain string `json:"domain" xorm:"not null pk comment('绑定域名') VARCHAR(100)"`
Uuid int `json:"uuid" xorm:"not null comment('对应APP ID编号') index unique(IDX_UUID_TYPE) INT(10)"`
Type string `json:"type" xorm:"not null comment('api接口域名,wap.h5域名,admin管理后台') unique(IDX_UUID_TYPE) ENUM('admin','api','wap')"`
IsSsl int `json:"is_ssl" xorm:"not null default 0 comment('是否开启ssl:0否;1是') TINYINT(255)"`
}

+ 8
- 0
app/db/model/user_app_list.go Visa fil

@@ -0,0 +1,8 @@
package model

type UserAppList struct {
Id int `json:"id" xorm:"int(11) NOT NULL "`
Uuid int64 `json:"uuid" xorm:"int(10) NOT NULL "`
AppId int64 `json:"app_id" xorm:"int(10) NOT NULL "`
SmsPlatform string `json:"sms_platform" xorm:"varchar(255) DEFAULT 'mob' "`
}

+ 23
- 0
app/db/model/user_level.go Visa fil

@@ -0,0 +1,23 @@
package model

import (
"time"
)

type UserLevel struct {
Id int `json:"id" xorm:"not null pk autoincr comment('等级id') INT(11)"`
BenefitIds string `json:"benefit_ids" xorm:"comment('该等级拥有的权益id【json】') TEXT"`
LevelName string `json:"level_name" xorm:"not null default '' comment('等级名称') VARCHAR(255)"`
LevelWeight int `json:"level_weight" xorm:"not null default 0 comment('等级权重') INT(11)"`
LevelUpdateCondition int `json:"level_update_condition" xorm:"not null default 2 comment('2是条件升级,1是无条件升级') TINYINT(1)"`
AutoAudit int `json:"auto_audit" xorm:"not null default 0 comment('(自动审核)0关闭,1开启') TINYINT(1)"`
AutoUpdate int `json:"auto_update" xorm:"not null default 0 comment('(自动升级)0关闭,1开启') TINYINT(1)"`
LevelDate int `json:"level_date" xorm:"default 0 comment('会员有效期(0永久有效,单位月)') INT(11)"`
IsUse int `json:"is_use" xorm:"not null default 1 comment('是否开启(0否,1是)') TINYINT(1)"`
ChoosableNum int `json:"choosable_num" xorm:"default 0 comment('可选任务数量(当is_must_task为0时生效)') INT(6)"`
BeforeHide int `json:"before_hide" xorm:"default 0 comment('可选任务数量(当is_must_task为0时生效)') INT(6)"`
Label int `json:"label" xorm:"default 0 comment('') INT(6)"`
Memo string `json:"memo" xorm:"default '' comment('备注') VARCHAR(255)"`
CssSet string `json:"css_set" xorm:"TEXT"`
CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP TIMESTAMP"`
}

+ 102
- 0
app/db/model/user_profile.go Visa fil

@@ -0,0 +1,102 @@
package model

import (
"time"
)

type UserProfile struct {
Uid int `json:"uid" xorm:"not null pk comment('关联userID') INT(20)"`
ArkidUid int `json:"arkid_uid" xorm:"not null default 0 comment('Arkid 用户ID') INT(20)"`
ParentUid int `json:"parent_uid" xorm:"not null default 0 comment('上级ID') INT(20)"`
ArkidToken string `json:"arkid_token" xorm:"not null default '' comment('token') VARCHAR(2000)"`
AvatarUrl string `json:"avatar_url" xorm:"not null default '' comment('头像URL') VARCHAR(2000)"`
CustomInviteCode string `json:"custom_invite_code" xorm:"not null default '' comment('邀请码(自定义)') VARCHAR(16)"`
InviteCode string `json:"invite_code" xorm:"not null default '' comment('邀请码(系统)') VARCHAR(16)"`
Gender int `json:"gender" xorm:"not null default 2 comment('性别0女,1男,2未知') TINYINT(1)"`
Birthday int `json:"birthday" xorm:"not null default 0 comment('出生日期') INT(10)"`
AccWxId string `json:"acc_wx_id" xorm:"not null default '' comment('账户_微信id') VARCHAR(50)"`
AccWxOpenid string `json:"acc_wx_openid" xorm:"not null default '' comment('账户_微信openid') VARCHAR(80)"`
AccTaobaoNickname string `json:"acc_taobao_nickname" xorm:"not null default '' comment('淘宝昵称') VARCHAR(50)"`
AccTaobaoAuthTime int64 `json:"acc_taobao_auth_time" xorm:"not null default 0 comment('淘宝授权备案时间') BIGINT(11)"`
AccTaobaoShareId int64 `json:"acc_taobao_share_id" xorm:"not null default 0 comment('淘宝分享relationId,') index BIGINT(12)"`
AccTaobaoSelfId int64 `json:"acc_taobao_self_id" xorm:"not null default 0 comment('淘宝自购specialId') index BIGINT(12)"`
AccJdSelfId string `json:"acc_jd_self_id" xorm:"not null default '' comment('京东自购ID') index VARCHAR(50)"`
AccJdShareId string `json:"acc_jd_share_id" xorm:"not null default '' comment('京东分享ID') index VARCHAR(50)"`
AccJdFreeId string `json:"acc_jd_free_id" xorm:"not null default '' comment('京东新人免单ID') VARCHAR(50)"`
AccJdCloudId string `json:"acc_jd_cloud_id" xorm:"not null default '' comment('京东新人免单ID') VARCHAR(50)"`
AccSuningSelfId string `json:"acc_suning_self_id" xorm:"not null default '' comment('苏宁自购ID') index VARCHAR(50)"`
AccSuningShareId string `json:"acc_suning_share_id" xorm:"not null default '' comment('苏宁分享ID') index VARCHAR(50)"`
AccSuningFreeId string `json:"acc_suning_free_id" xorm:"not null default '' comment('苏宁新人免单ID') VARCHAR(50)"`
AccPddSelfId string `json:"acc_pdd_self_id" xorm:"not null default '' comment('拼多多自购ID') index VARCHAR(50)"`
AccPddCloudId string `json:"acc_pdd_cloud_id" xorm:"not null default '' comment('拼多多自购ID') index VARCHAR(50)"`
AccPddShareId string `json:"acc_pdd_share_id" xorm:"not null default '' comment('拼多多分享ID') index VARCHAR(50)"`
AccPddFreeId string `json:"acc_pdd_free_id" xorm:"not null default '' comment('拼多多新人免单ID') VARCHAR(50)"`
AccPddBind int `json:"acc_pdd_bind" xorm:"not null default 0 comment('拼多多是否授权绑定') TINYINT(1)"`
AccVipSelfId string `json:"acc_vip_self_id" xorm:"not null default '' comment('唯品会自购ID') index VARCHAR(50)"`
AccVipShareId string `json:"acc_vip_share_id" xorm:"not null default '' comment('唯品会分享ID') index VARCHAR(50)"`
AccVipFreeId string `json:"acc_vip_free_id" xorm:"not null default '' comment('唯品会新人免单ID') VARCHAR(50)"`
AccKaolaSelfId string `json:"acc_kaola_self_id" xorm:"not null default '' comment('考拉自购ID') index VARCHAR(50)"`
AccKaolaShareId string `json:"acc_kaola_share_id" xorm:"not null default '' comment('考拉分享ID') index VARCHAR(50)"`
AccKaolaFreeId string `json:"acc_kaola_free_id" xorm:"not null default '' comment('考拉新人免单ID') VARCHAR(50)"`
AccDuomaiShareId int64 `json:"acc_duomai_share_id" xorm:"not null pk default 0 comment('多麦联盟分享ID') BIGINT(12)"`
AccAlipay string `json:"acc_alipay" xorm:"not null default '' comment('支付宝账号') VARCHAR(50)"`
AccAlipayRealName string `json:"acc_alipay_real_name" xorm:"not null default '' comment('支付宝账号真实姓名') VARCHAR(50)"`
CertTime int `json:"cert_time" xorm:"not null default 0 comment('认证时间') INT(10)"`
CertName string `json:"cert_name" xorm:"not null default '' comment('证件上名字,也是真实姓名') VARCHAR(50)"`
CertNum string `json:"cert_num" xorm:"not null default '' comment('证件号码') VARCHAR(50)"`
CertState int `json:"cert_state" xorm:"not null default 0 comment('认证状态(0为未认证,1为认证中,2为已认证,3为认证失败)') TINYINT(1)"`
FinCommission string `json:"fin_commission" xorm:"not null default 0.0000 comment('累计佣金') DECIMAL(10,4)"`
FinValid string `json:"fin_valid" xorm:"not null default 0.0000 comment('可用余额,fin=>finance财务') DECIMAL(10,4)"`
FinInvalid string `json:"fin_invalid" xorm:"not null default 0.0000 comment('不可用余额,冻结余额') DECIMAL(10,4)"`
FinSelfOrderCount int `json:"fin_self_order_count" xorm:"not null default 0 comment('自购订单数,包括未完成') INT(11)"`
FinSelfOrderCountDone int `json:"fin_self_order_count_done" xorm:"not null default 0 comment('自购已完成订单') INT(11)"`
FinSelfRebate float32 `json:"fin_self_rebate" xorm:"not null default 0.000000 comment('累积自购获得返利金额') FLOAT(14,6)"`
FinTotal float32 `json:"fin_total" xorm:"not null default 0.000000 comment('累计总收益') FLOAT(14,6)"`
Lat float32 `json:"lat" xorm:"not null default 0.000000 comment('纬度') FLOAT(15,6)"`
Lng float32 `json:"lng" xorm:"not null default 0.000000 comment('经度') FLOAT(15,6)"`
Memo string `json:"memo" xorm:"not null default '' comment('用户简述备注') VARCHAR(2048)"`
Qq string `json:"qq" xorm:"not null default '' comment('') VARCHAR(255)"`
IsNew int `json:"is_new" xorm:"not null default 1 comment('是否是新用户') TINYINT(1)"`
IsVerify int `json:"is_verify" xorm:"not null default 0 comment('是否有效会员') TINYINT(1)"`
IsOrdered int `json:"is_ordered" xorm:"not null default 0 comment('是否已完成首单(0否,1是)') TINYINT(1)"`
FromWay string `json:"from_way" xorm:"not null default '' comment('注册来源:
no_captcha_phone:免验证码手机号注册;
manual_phone:手动手机验证码注册;
wx:微信授权;
wx_mp:小程序授权;
wx_pub:公众号授权;
wx_bind_phone:微信注册绑定手机号;
admin:管理员添加;taobao_bind_phone:淘宝注册绑定手机号,apple_bind_phone:苹果注册绑定手机号') VARCHAR(16)"`
HidOrder int `json:"hid_order" xorm:"not null default 0 comment('隐藏订单') TINYINT(3)"`
HidContact int `json:"hid_contact" xorm:"not null default 0 comment('隐藏联系方式') TINYINT(4)"`
NewMsgNotice int `json:"new_msg_notice" xorm:"not null default 1 comment('新消息通知') TINYINT(1)"`
WxAccount string `json:"wx_account" xorm:"not null default '' comment('微信号') VARCHAR(100)"`
WxQrcode string `json:"wx_qrcode" xorm:"not null default '' comment('微信二维码') VARCHAR(100)"`
ThirdPartyTaobaoOid string `json:"third_party_taobao_oid" xorm:"not null default '' comment('淘宝第三方登录openID') VARCHAR(100)"`
ThirdPartyTaobaoSid string `json:"third_party_taobao_sid" xorm:"not null default '' comment('淘宝第三方登录sID') VARCHAR(255)"`
ThirdPartyTaobaoAcctoken string `json:"third_party_taobao_acctoken" xorm:"not null default '' comment('淘宝第三方登录topaccesstoken') VARCHAR(100)"`
ThirdPartyTaobaoAuthcode string `json:"third_party_taobao_authcode" xorm:"not null default '' comment('淘宝第三方登录topAuthCode') VARCHAR(100)"`
ThirdPartyAppleToken string `json:"third_party_apple_token" xorm:"not null default '' comment('苹果第三方登录token') VARCHAR(1024)"`
ThirdPartyQqAccessToken string `json:"third_party_qq_access_token" xorm:"not null default '' comment('QQ第三方登录access_token') VARCHAR(255)"`
ThirdPartyQqExpiresIn string `json:"third_party_qq_expires_in" xorm:"not null default '' comment('QQ第三方登录expires_in(剩余时长)') VARCHAR(255)"`
ThirdPartyQqOpenid string `json:"third_party_qq_openid" xorm:"not null default '' comment('QQ第三方登陆openid(不变,用于认证)') VARCHAR(255)"`
ThirdPartyQqUnionid string `json:"third_party_qq_unionid" xorm:"not null default '' comment('QQ第三方登陆unionid') VARCHAR(255)"`
ThirdPartyWechatExpiresIn string `json:"third_party_wechat_expires_in" xorm:"not null default '' comment('微信第三方登录expires_in(剩余时长)') VARCHAR(255)"`
ThirdPartyWechatOpenid string `json:"third_party_wechat_openid" xorm:"not null default '' comment('微信第三方登陆openid(不变,用于认证)') VARCHAR(255)"`
ThirdPartyWechatUnionid string `json:"third_party_wechat_unionid" xorm:"not null default '' comment('微信第三方登陆unionid') VARCHAR(255)"`
ThirdPartyWechatMiniOpenid string `json:"third_party_wechat_mini_openid" xorm:"not null default '' comment('微信小程序登录open_id') VARCHAR(255)"`
ThirdPartyWechatH5Openid string `json:"third_party_wechat_h5_openid" xorm:"not null default '' comment('微信H5登录open_id') VARCHAR(255)"`
FreeRemainTime int `json:"free_remain_time" xorm:"not null default 0 comment('免单剩余次数') INT(11)"`
FreeCumulativeTime int `json:"free_cumulative_time" xorm:"not null default 0 comment('免单累计次数') INT(11)"`
SecondFreeRemainTime int `json:"second_free_remain_time" xorm:"not null default 0 comment('免单剩余次数') INT(11)"`
SecondFreeCumulativeTime int `json:"second_free_cumulative_time" xorm:"not null default 0 comment('免单累计次数') INT(11)"`
ThirdFreeRemainTime int `json:"third_free_remain_time" xorm:"not null default 0 comment('免单剩余次数') INT(11)"`
ThirdFreeCumulativeTime int `json:"third_free_cumulative_time" xorm:"not null default 0 comment('免单累计次数') INT(11)"`
IsDelete int `json:"is_delete" xorm:"not null default 0 comment('是否已删除') TINYINT(1)"`
UpdateAt time.Time `json:"update_at" xorm:"updated not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"`
IsSet int `json:"is_set" xorm:"not null default 0 comment('用于一个客户生成关系链匹配的') INT(1)"`
IsOld int `json:"is_old" xorm:"not null default 0 comment('') INT(1)"`
RunVerifyTime int `json:"run_verify_time" xorm:"not null default 0 comment('') INT(1)"`
TaskId int `json:"task_id" xorm:"not null default 0 comment('') INT(1)"`
TaskType string `json:"task_type" xorm:"not null default '' comment('') VARCHAR(255)"`
}

+ 13
- 0
app/db/model/user_relate.go Visa fil

@@ -0,0 +1,13 @@
package model

import (
"time"
)

type UserRelate struct {
Id int64 `json:"id" xorm:"pk autoincr comment('主键') BIGINT(10)"`
ParentUid int `json:"parent_uid" xorm:"not null default 0 comment('上级会员ID') unique(idx_union_u_p_id) INT(20)"`
Uid int `json:"uid" xorm:"not null default 0 comment('关联UserID') unique(idx_union_u_p_id) INT(20)"`
Level int `json:"level" xorm:"not null default 1 comment('推广等级(1直属,大于1非直属)') INT(10)"`
InviteTime time.Time `json:"invite_time" xorm:"not null default CURRENT_TIMESTAMP comment('邀请时间') TIMESTAMP"`
}

+ 17
- 0
app/db/model/virtual_coin.go Visa fil

@@ -0,0 +1,17 @@
package model

type VirtualCoin struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"`
ExchangeRatio string `json:"exchange_ratio" xorm:"not null comment('兑换比例(与金额)') DECIMAL(5,2)"`
IsUse int `json:"is_use" xorm:"comment('是否开启:0否 1是') TINYINT(1)"`
CanExchange string `json:"can_exchange" xorm:"comment('能兑换的虚拟币id和手续费列表json') VARCHAR(255)"`
CanExchangeMoney int `json:"can_exchange_money" xorm:"not null default 0 comment('现金能否兑换:0否 1是') TINYINT(1)"`
IsBlock int `json:"is_block" xorm:"not null default 0 comment('是否区块币:0否 1是') TINYINT(1)"`
FunctionType string `json:"function_type" xorm:"comment('功能类型') VARCHAR(255)"`
CanCny int `json:"can_cny" xorm:"not null default 0 comment('是否能兑换余额:0否 1是') TINYINT(1)"`
CanTransfer int `json:"can_transfer" xorm:"not null default 0 comment('是否能支持转账:0否 1是') TINYINT(1)"`
CanBackout int `json:"can_backout" xorm:"not null default 0 comment('是否能支持转账撤回:0否 1是') TINYINT(1)"`
LimitLevelTransfer string `json:"limit_level_transfer" xorm:"default '' comment('能支持转账的用户等级') VARCHAR(600)"`
LimitLevelBackout string `json:"limit_level_backout" xorm:"comment('能支持撤回的用户等级') VARCHAR(600)"`
}

+ 17
- 0
app/db/model/virtual_coin_relate.go Visa fil

@@ -0,0 +1,17 @@
package model

type VirtualCoinRelate struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Oid int64 `json:"oid" xorm:"not null default 0 comment('订单号') index unique(IDX_ORD) BIGINT(20)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户ID') unique(IDX_ORD) index INT(10)"`
CoinId int `json:"coin_id" xorm:"comment('虚拟币id') unique(IDX_ORD) INT(11)"`
Amount string `json:"amount" xorm:"not null default 0.000000 comment('数量') DECIMAL(16,6)"`
Pvd string `json:"pvd" xorm:"not null default '' comment('供应商taobao,jd,pdd,vip,suning,kaola,mall_goods,group_buy') index VARCHAR(255)"`
CreateAt int `json:"create_at" xorm:"not null default 0 comment('订单创建时间') index INT(10)"`
Level int `json:"level" xorm:"not null default 0 comment('0自购 1直推 大于1:间推') INT(10)"`
Mode string `json:"mode" xorm:"default '' comment('分佣方案类型') VARCHAR(255)"`
AdditionalSubsidy string `json:"additional_subsidy" xorm:"default 0.000000 comment('额外补贴 酒庄模式才有效') DECIMAL(16,6)"`
AdditionalSubsidyBili string `json:"additional_subsidy_bili" xorm:"default 0.000000 comment('额外补贴比例 酒庄模式才有效') DECIMAL(16,6)"`
TeamFreeze int `json:"team_freeze" xorm:"comment('定制') INT(1)"`
ExtendType int `json:"extend_type" xorm:"default 0 comment('0普通 1超级推荐人 2团长 3团长上级超级推荐人 4团长担保用户') unique(IDX_ORD) INT(11)"`
}

+ 44
- 0
app/db/model/wx_applet_list.go Visa fil

@@ -0,0 +1,44 @@
package model

import (
"time"
)

type WxAppletList struct {
Id int `json:"id" xorm:"not null pk autoincr INT(10)"`
Memo string `json:"memo" xorm:"not null default '' comment('备注') unique VARCHAR(255)"`
CompanyName string `json:"company_name" xorm:"not null default '' comment('企业名(需与工商部门登记信息一致);如果是“无主体名称个体工商户”则填“个体户+法人姓名”,例如“个体户张三”') VARCHAR(255)"`
Code string `json:"code" xorm:"not null default '' comment('企业代码') VARCHAR(255)"`
CodeType int `json:"code_type" xorm:"not null default 3 comment('企业代码类型 1:统一社会信用代码(18 位) 2:组织机构代码(9 位 xxxxxxxx-x) 3:营业执照注册号(15 位)') TINYINT(3)"`
LegalPersonaWechat string `json:"legal_persona_wechat" xorm:"not null default '' comment('法人微信号') VARCHAR(255)"`
LegalPersonaName string `json:"legal_persona_name" xorm:"not null default '' comment('法人姓名(绑定银行卡)') VARCHAR(255)"`
State int `json:"state" xorm:"not null default 0 comment('创建状态(0:创建中 1:创建成功 2:创建失败)') TINYINT(3)"`
Ext string `json:"ext" xorm:"comment('拓展字段') TEXT"`
UniqueIdentifier string `json:"unique_identifier" xorm:"not null default '' comment('唯一标识符(企业名称、企业代码、法人微信、法人姓名四个字段作为每次任务的唯一标示,来区别每次任务。)') VARCHAR(255)"`
AppId string `json:"app_id" xorm:"default '' comment('小程序appId') VARCHAR(255)"`
OriginalAppId string `json:"original_app_id" xorm:"default '' comment('原始ID') VARCHAR(255)"`
AuthorizerToken string `json:"authorizer_token" xorm:"default '' comment('授权token') VARCHAR(255)"`
AuthorizerRefreshToken string `json:"authorizer_refresh_token" xorm:"default '' comment('授权更新token') VARCHAR(255)"`
AuditVersionState int `json:"audit_version_state" xorm:"not null default 0 comment('线上版本号') TINYINT(3)"`
PublishVersionNum string `json:"publish_version_num" xorm:"comment('审核状态(0:暂无审核;1:审核中;2:审核通过;3:审核驳回)') VARCHAR(255)"`
AppletName string `json:"applet_name" xorm:"default '' comment('小程序名字') VARCHAR(255)"`
AppletSignature string `json:"applet_signature" xorm:"default '' comment('小程序简介') VARCHAR(255)"`
AppletLogo string `json:"applet_logo" xorm:"default '' comment('小程序logo') VARCHAR(255)"`
SetAppletNameInfo string `json:"set_applet_name_info" xorm:"default '' comment('小程序改名证件url') VARCHAR(255)"`
SetAppletNameInfoType int `json:"set_applet_name_info_type" xorm:"default 1 comment('小程序改名证件类型(1:个人号 2:组织号)') TINYINT(3)"`
SetAppletNameState int `json:"set_applet_name_state" xorm:"default 0 comment('小程序改名状态(0:未进行 1:进行中 2:改名成功 3:改名失败)') TINYINT(3)"`
SetAppletNameAuditId string `json:"set_applet_name_audit_id" xorm:"default '' comment('小程序改名的审核单id') VARCHAR(255)"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' TIMESTAMP"`
IsFilterTaobao int `json:"is_filter_taobao" xorm:"default 0 comment('是否过滤淘宝商品 0否 1是') INT(1)"`
CateId string `json:"cate_id" xorm:"default '' comment('主营类目id') VARCHAR(50)"`
BottomNavCssId int `json:"bottom_nav_css_id" xorm:"default 0 comment('底部导航样式id') INT(11)"`
AuthType string `json:"auth_type" xorm:"default 'reg' comment('授权方式 直接授权old_auth 注册授权reg') VARCHAR(100)"`
MpAuditVersion string `json:"mp_audit_version" xorm:"default '' comment('审核版本') VARCHAR(100)"`
MpAuditCssId int `json:"mp_audit_css_id" xorm:"default 0 comment('审核版本底部样式ID') INT(11)"`
MpAuditGoodsDetailCssId int `json:"mp_audit_goods_detail_css_id" xorm:"default 0 comment('审核版本底部样式ID') INT(11)"`
AppletBgColor string `json:"applet_bg_color" xorm:"default '' comment('导航栏/状态栏背景色') VARCHAR(100)"`
AppletNavColor string `json:"applet_nav_color" xorm:"default '' comment('导航栏/状态栏字体色') VARCHAR(100)"`
ShareUse int `json:"share_use" xorm:"default 0 comment('分享使用') INT(11)"`
OrderCssId int `json:"order_css_id" xorm:"default 0 comment('') INT(11)"`
}

+ 23
- 0
app/db/offical/db_sys_cfg.go Visa fil

@@ -0,0 +1,23 @@
package offical

import (
"applet/app/db"
officialModel "applet/app/db/offical/model"
)

func SysCfgByKey(key string) *officialModel.SysCfg {
var data officialModel.SysCfg
get, err := db.Db.Where("k=?", key).Get(&data)
if get == false || err != nil {
return nil
}
return &data
}
func SysCfgByKeyStr(key string) string {
var data officialModel.SysCfg
get, err := db.Db.Where("k=?", key).Get(&data)
if get == false || err != nil {
return ""
}
return data.V
}

+ 15
- 0
app/db/offical/db_user_app_list.go Visa fil

@@ -0,0 +1,15 @@
package offical

import (
"applet/app/db"
"applet/app/db/offical/model"
)

func GetUserAppList(uid string) *model.UserAppList {
var data model.UserAppList
get, err := db.Db.Where("uuid=?", uid).Get(&data)
if get == false || err != nil {
return nil
}
return &data
}

+ 9
- 0
app/db/offical/model/master_list_cfg.go Visa fil

@@ -0,0 +1,9 @@
package model

type MasterListCfg struct {
K string `json:"k" xorm:"not null VARCHAR(255)"`
V string `json:"v" xorm:"TEXT"`
Memo string `json:"memo" xorm:"VARCHAR(255)"`
Uid string `json:"uid" xorm:"comment('0是官方') VARCHAR(255)"`
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
}

+ 7
- 0
app/db/offical/model/sys_cfg.go Visa fil

@@ -0,0 +1,7 @@
package model

type SysCfg struct {
K string `json:"k" xorm:"not null pk comment('键') VARCHAR(127)"`
V string `json:"v" xorm:"comment('值') TEXT"`
Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"`
}

+ 33
- 0
app/db/offical/model/user_app_list.go Visa fil

@@ -0,0 +1,33 @@
package model

type UserAppList struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uuid int `json:"uuid" xorm:"not null comment('masterId') INT(10)"`
Uid int `json:"uid" xorm:"not null comment('用户ID') INT(10)"`
AppId int `json:"app_id" xorm:"not null comment('应用ID') INT(10)"`
PlanId string `json:"plan_id" xorm:"not null default '' comment('套餐ID') VARCHAR(100)"`
Expire int `json:"expire" xorm:"not null default 0 comment('过期时间') INT(10)"`
Name string `json:"name" xorm:"not null default '' comment('应用主名称') VARCHAR(32)"`
Icon string `json:"icon" xorm:"not null default '' comment('应用主图标') VARCHAR(250)"`
CreateTime int `json:"create_time" xorm:"not null default 0 comment('初次激活时间') INT(10)"`
RenewTime int `json:"renew_time" xorm:"not null default 0 comment('上次续费时间') INT(10)"`
Domain string `json:"domain" xorm:"not null default '' comment('域名') index VARCHAR(110)"`
DomainAlias string `json:"domain_alias" xorm:"not null default '' comment('域名别名') index VARCHAR(110)"`
Platform string `json:"platform" xorm:"not null default '' comment('平台信息 ios,android,applet') VARCHAR(100)"`
Info string `json:"info" xorm:"comment('平台名称如ios.name.#ddd;') TEXT"`
PayMode int `json:"pay_mode" xorm:"not null default 1 comment('付费模式,0授信,1付款') TINYINT(1)"`
Price float32 `json:"price" xorm:"not null default 0.00 comment('应用价格') FLOAT(10,2)"`
PricePay float32 `json:"price_pay" xorm:"not null default 0.00 comment('实际付款价格') FLOAT(10,2)"`
OfficialPrice float32 `json:"official_price" xorm:"not null default 0.00 comment('应用价格') FLOAT(10,2)"`
OfficialPricePay float32 `json:"official_price_pay" xorm:"not null default 0.00 comment('实际付款价格') FLOAT(10,2)"`
State int `json:"state" xorm:"not null default 0 comment('0未创建,1正常,2停用,3过期') TINYINT(1)"`
DeleteAt int `json:"delete_at" xorm:"not null default 0 TINYINT(1)"`
CustomAndroidCount int `json:"custom_android_count" xorm:"default 0 comment('客户端安卓包名重置次数') INT(11)"`
CustomIosCount int `json:"custom_ios_count" xorm:"default 0 comment('客户端ios包名重置次数') INT(11)"`
StoreAndroidCount int `json:"store_android_count" xorm:"default 0 comment('商家端安卓包名重置次数') INT(11)"`
StoreIosCount int `json:"store_ios_count" xorm:"default 0 comment('商家端ios包名重置次数') INT(11)"`
SmsPlatform string `json:"sms_platform" xorm:"default 'mob' comment('mob ljioe联江') VARCHAR(255)"`
IsClose int `json:"is_close" xorm:"default 0 comment('是否关闭') INT(1)"`
Puid int `json:"puid" xorm:"default 0 comment('') INT(11)"`
StoreRateInfo string `json:"store_rate_info" xorm:"comment('付呗商品进件费率') TEXT"`
}

+ 166
- 0
app/db/wechat_applet_info.go Visa fil

@@ -0,0 +1,166 @@
package db

import (
"applet/app/cfg"
"applet/app/db/model"
"applet/app/utils"
"applet/app/utils/cache"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"xorm.io/xorm"
)

func GetAppletKey(c *gin.Context, eg *xorm.Engine) map[string]string {
appId := c.GetHeader("appid")
isFilterTaobao := "0"
appletName := ""
appletLogo := ""
originalAppId := ""
bottomNavCssId := ""
mpAuditVersion := ""
MpAuditGoodsDetailCssId := ""
orderCssId := ""
if appId == "" {
wxAppletCfg := SysCfgGetWithDb(eg, c.GetString("mid"), "wx_applet_key")
isFilterTaobao = gjson.Get(wxAppletCfg, "taobaoGoodsOnOff").String()
appletName = gjson.Get(wxAppletCfg, "appletName").String()
originalAppId = gjson.Get(wxAppletCfg, "originalAppId").String()
appletLogo = gjson.Get(wxAppletCfg, "appletIcon").String()
mpAuditVersion = SysCfgGetWithDb(eg, c.GetString("mid"), "mp_audit_version")
var tm model.SysTemplate
if has, err := eg.Where("is_use = 1 AND type = 'bottom' AND platform = 4 ").
Cols("id,uid,name,is_use,is_system").
Get(&tm); err != nil || has == false {
bottomNavCssId = ""
} else {
bottomNavCssId = utils.IntToStr(tm.Id)
}
if c.GetHeader("AppVersionName") == mpAuditVersion && c.GetHeader("AppVersionName") != "" {
m := SysCfgGetWithDb(eg, c.GetString("mid"), "mp_audit_template")
if m != "" {
bottomNavCssId = utils.Int64ToStr(gjson.Get(m, "bottom").Int())
}
m1 := SysCfgGet(c, "mp_audit_template")
if m1 != "" {
MpAuditGoodsDetailCssId = utils.Int64ToStr(gjson.Get(m1, "product_detail").Int())
}
}
appId = gjson.Get(wxAppletCfg, "appId").String()
} else {
var wxApplet model.WxAppletList
has, err2 := eg.Where("app_id=?", appId).Get(&wxApplet)
if has && err2 == nil {
isFilterTaobao = utils.IntToStr(wxApplet.IsFilterTaobao)
appletName = wxApplet.AppletName
appletLogo = wxApplet.AppletLogo
originalAppId = wxApplet.OriginalAppId
orderCssId = utils.IntToStr(wxApplet.OrderCssId)
mpAuditVersion = wxApplet.MpAuditVersion
bottomNavCssId = utils.IntToStr(wxApplet.BottomNavCssId)
MpAuditGoodsDetailCssId = ""
if c.GetHeader("AppVersionName") == mpAuditVersion && c.GetHeader("AppVersionName") != "" {
bottomNavCssId = utils.IntToStr(wxApplet.MpAuditCssId)
MpAuditGoodsDetailCssId = utils.IntToStr(wxApplet.MpAuditGoodsDetailCssId)
}
}
}
r := map[string]string{
"order_css_id": orderCssId,
"app_id": appId,
"is_filter_taobao": isFilterTaobao,
"applet_name": appletName,
"applet_logo": appletLogo,
"original_app_id": originalAppId,
"bottom_nav_css_id": bottomNavCssId,
"mp_audit_version": mpAuditVersion,
"mp_audit_goods_detail_css_id": MpAuditGoodsDetailCssId,
}
return r

}
func GetShareUse(c *gin.Context, eg *xorm.Engine) map[string]string {
var wxApplet model.WxAppletList
has, err2 := eg.Where("share_use=?", 1).Asc("id").Get(&wxApplet)
wxAppletCfg := SysCfgGetWithDb(eg, c.GetString("mid"), "wx_applet_key")
originalAppId := gjson.Get(wxAppletCfg, "originalAppId").String()
appId := gjson.Get(wxAppletCfg, "appId").String()
if has && err2 == nil {
originalAppId = wxApplet.OriginalAppId
appId = wxApplet.AppId
}
r := map[string]string{
"app_id": appId,
"original_app_id": originalAppId,
}
return r
}
func GetAppletToken(c *gin.Context, appId string, isMore, isReset string) (accessToken string) {
key := fmt.Sprintf("%s:%s:%s", c.GetString("mid"), "wx_applet_access_token2", appId)
token, err := cache.GetString(key)
if err == nil && token != "" && strings.Contains(token, "{") == false && isReset == "0" {
// 有缓存
accessToken = token
} else {
ExpiresIn := 1800
accessTokenStr := ApiToSuperAdminWx(c, appId, isMore)
if accessTokenStr == "" {
return ""
}
ExpiresIn = int(gjson.Get(accessTokenStr, "expires_in").Int()) - 60*60*1 //TODO::暂时只用1个小时
accessToken = gjson.Get(accessTokenStr, "authorizer_access_token").String()
if ExpiresIn > 0 {
//fmt.Printf("返回结果: %#v", res)
_, err = cache.SetEx(key, accessToken, ExpiresIn)
if err != nil {
fmt.Println("微信授权错误", err)
return ""
}
}

}
return accessToken
}

// 总后台微信token isMore多小程序登录总后台要判断读另一个表
func ApiToSuperAdminWx(c *gin.Context, appid string, isMore string) string {
var req = make(map[string]string, 0)
var host string
host = cfg.WebsiteBackend.URL + "/Wx/getAuthorizerResult?appid=" + appid + "&is_more=" + isMore
fmt.Println(host)
tr := &http.Transport{
MaxIdleConnsPerHost: 200,
MaxIdleConns: 200,
MaxConnsPerHost: 200,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{
Timeout: 5 * time.Second,
Transport: tr,
}
byte1, _ := json.Marshal(req)
req1, _ := http.NewRequest("POST", host, strings.NewReader(string(byte1)))
req1.Header.Set("Content-Type", "application/json")
resp, err := (client).Do(req1)
if err != nil || resp == nil {
if resp != nil {
_, _ = io.Copy(ioutil.Discard, resp.Body)
}
return ""
}
defer resp.Body.Close()
respByte, _ := ioutil.ReadAll(resp.Body)

if len(respByte) == 0 {
return ""
}
return string(respByte)

}

+ 42
- 0
app/db/zhimeng_db.go Visa fil

@@ -0,0 +1,42 @@
package db

import (
"fmt"
"os"

_ "github.com/go-sql-driver/mysql"
"xorm.io/xorm"
"xorm.io/xorm/log"

"applet/app/cfg"
)

var ZhimengDb *xorm.Engine

func InitZhimengDB(c *cfg.DBCfg) error {
var err error
if ZhimengDb, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil {
return err
}
ZhimengDb.SetConnMaxLifetime(c.MaxLifetime)
ZhimengDb.SetMaxOpenConns(c.MaxOpenConns)
ZhimengDb.SetMaxIdleConns(c.MaxIdleConns)
if err = Db.Ping(); err != nil {
return err
}
if c.ShowLog {
ZhimengDb.ShowSQL(true)
ZhimengDb.Logger().SetLevel(0)
f, err := os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
os.RemoveAll(c.Path)
if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil {
return err
}
}
logger := log.NewSimpleLogger(f)
logger.ShowSQL(true)
ZhimengDb.SetLogger(logger)
}
return nil
}

+ 244
- 0
app/e/code.go Visa fil

@@ -0,0 +1,244 @@
package e

const (
// 200 因为部分第三方接口不能返回错误头,因此在此定义部分错误
ERR_FILE_SAVE = 200001
// 400 系列
ERR_BAD_REQUEST = 400000
ERR_INVALID_ARGS = 400001
ERR_API_RESPONSE = 400002
ERR_NO_DATA = 400003
ERR_MOBILE_NIL = 400004
ERR_MOBILE_MATH = 400005
ERR_FILE_EXT = 400006
ERR_FILE_MAX_SIZE = 400007
ERR_SIGN = 400008
ERR_PASSWORD_MATH = 400009
ERR_PROVIDER_RESPONSE = 400010
ERR_AES_ENCODE = 400011
ERR_ADMIN_API = 400012
ERR_QINIUAPI_RESPONSE = 400013
ERR_URL_TURNCHAIN = 400014

// 401 未授权
ERR_UNAUTHORIZED = 401000
ERR_NOT_AUTH = 401001
ERR_SMS_AUTH = 401002
ERR_TOKEN_AUTH = 401003
ERR_TOKEN_FORMAT = 401004
ERR_TOKEN_GEN = 401005
// 403 禁止
ERR_FORBIDEN = 403000
ERR_PLATFORM = 403001
ERR_MOBILE_EXIST = 403002
ERR_USER_NO_EXIST = 403003
ERR_MOBILE_NO_EXIST = 403004
ERR_FORBIDEN_VALID = 403005
ERR_RELATE_ERR = 403006
ERR_REPEAT_RELATE = 403007
ERR_MOB_FORBIDEN = 403008
ERR_MOB_SMS_NO_AVA = 403009
ERR_USER_IS_REG = 403010
ERR_MASTER_ID = 403011
ERR_CASH_OUT_TIME = 403012
ERR_CASH_OUT_FEE = 403013
ERR_CASH_OUT_USER_NOT_FOUND = 403014
ERR_CASH_OUT_FAIL = 403015
ERR_CASH_OUT_TIMES = 403016
ERR_CASH_OUT_MINI = 403017
ERR_CASH_OUT_MUT = 403018
ERR_CASH_OUT_NOT_DECIMAL = 403019
ERR_CASH_OUT_NOT_DAY_AVA = 403020
ERR_USER_LEVEL_PAY_CHECK_TASK_NO_DONE = 403021
ERR_USER_LEVEL_PAY_CHECK_NO_CROSS = 403022
ERR_USER_LEVEL_ORD_EXP = 403023
ERR_IS_BIND_THIRDPARTY = 403024
ERR_USER_LEVEL_UPDATE_CHECK_TASK_NO_DONE = 403025
ERR_USER_LEVEL_UPDATE_CHECK_NOT_FOUND_ORDER = 403026
ERR_USER_LEVEL_UPDATE_REPEAT = 403027
ERR_USER_NO_ACTIVE = 403028
ERR_USER_IS_BAN = 403029
ERR_ALIPAY_SETTING = 403030
ERR_ALIPAY_ORDERTYPE = 403031
ERR_CLIPBOARD_UNSUP = 403032
ERR_SYSUNION_CONFIG = 403033
ERR_WECAHT_MINI = 403034
ERR_WECAHT_MINI_CACHE = 403035
ERR_WECAHT_MINI_DECODE = 403036
ERR_WECHAT_MINI_ACCESSTOKEN = 403037
ERR_CURRENT_VIP_LEVEL_AUDITING = 403038
ERR_LEVEL_RENEW_SHOULD_KEEP_CURRENT = 403039
ERR_LEVEL_UPGRADE_APPLY_AUDITTING = 403040
ERR_LEVEL_TASK_PAY_TYPE = 403041
ERR_BALANCE_NOT_ENOUGH = 403042
ERR_ADMIN_PUSH = 403043
ERR_PLAN = 403044
ERR_MOB_CONFIG = 403045
ERR_BAlANCE_PAY_ORDERTYPE = 403046
ERR_PHONE_EXISTED = 403047
ERR_NOT_RESULT = 403048
ERR_REVIEW = 403049
ERR_USER_LEVEL_HAS_PAID = 403050
ERR_USER_BIND_OWN = 403051
ERR_PARENTUID_ERR = 403052
ERR_USER_DEL = 403053
ERR_SEARCH_ERR = 403054
ERR_LEVEL_REACH_TOP = 403055
ERR_USER_CHECK_ERR = 403056
ERR_PASSWORD_ERR = 403057
ERR_IS_BIND_PDD_ERR = 403058
ERR_MOB_SMS_NO_SAME = 403059
ERR_MOB_SMS_NO_EXISTS = 403060
// 404
ERR_USER_NOTFOUND = 404001
ERR_SUP_NOTFOUND = 404002
ERR_LEVEL_MAP = 404003
ERR_MOD_NOTFOUND = 404004
ERR_CLIPBOARD_PARSE = 404005
ERR_NOT_FAN = 404006
ERR_USER_LEVEL = 404007
ERR_LACK_PAY_CFG = 404008
ERR_NOT_LEVEL_TASK = 404009
ERR_ITEM_NOT_FOUND = 404012
ERR_WX_CHECKFILE_NOTFOUND = 404011

// 429 请求频繁
ERR_TOO_MANY_REQUESTS = 429000
// 500 系列
ERR = 500000
ERR_UNMARSHAL = 500001
ERR_UNKNOWN = 500002
ERR_SMS = 500003
ERR_ARKID_REGISTER = 500004
ERR_ARKID_WHITELIST = 500005
ERR_ARKID_LOGIN = 500006
ERR_CFG = 500007
ERR_DB_ORM = 500008
ERR_CFG_CACHE = 500009
ERR_ZHIMENG_CONVERT_ERR = 500010
ERR_ALIPAY_ERR = 500011
ERR_ALIPAY_ORDER_ERR = 500012
ERR_PAY_ERR = 500013
ERR_IS_BIND_THIRDOTHER = 500014
ERR_IS_BIND_THIRDOTHERWECHAT = 500015
ERR_INIT_RABBITMQ = 500016
)

var MsgFlags = map[int]string{
// 200
ERR_FILE_SAVE: "文件保存失败",
// 400
ERR_BAD_REQUEST: "请求失败..",
ERR_INVALID_ARGS: "请求参数错误",
ERR_API_RESPONSE: "API错误",
ERR_QINIUAPI_RESPONSE: "七牛请求API错误",
ERR_URL_TURNCHAIN: "转链失败",
ERR_NO_DATA: "暂无数据",
ERR_MOBILE_NIL: "电话号码不能为空",
ERR_MOBILE_MATH: "电话号码输入有误",
ERR_FILE_MAX_SIZE: "文件上传大小超限",
ERR_FILE_EXT: "文件类型不支持",
ERR_SIGN: "签名校验失败",
ERR_PROVIDER_RESPONSE: "提供商接口错误",
ERR_AES_ENCODE: "加解密错误",
ERR_ADMIN_API: "后台接口请求失败",
// 401
ERR_NOT_AUTH: "请登录后操作",
ERR_SMS_AUTH: "验证码过期或无效",
ERR_UNAUTHORIZED: "验证用户失败",
ERR_TOKEN_FORMAT: "Token格式不对",
ERR_TOKEN_GEN: "生成Token失败",
// 403
ERR_FORBIDEN: "禁止访问",
ERR_PLATFORM: "平台不支持",
ERR_MOBILE_EXIST: "该号码已注册过",
ERR_USER_NO_EXIST: "用户没有注册或账号密码不正确",
ERR_PASSWORD_ERR: "输入两次密码不一致",
ERR_RELATE_ERR: "推荐人不能是自己的粉丝",
ERR_PARENTUID_ERR: "推荐人不存在",
ERR_TOKEN_AUTH: "登录信息失效,请重新登录",
ERR_MOB_SMS_NO_AVA: "短信余额不足",
ERR_MOB_SMS_NO_SAME: "验证码不一致",
ERR_MOB_SMS_NO_EXISTS: "验证码已失效",
ERR_USER_IS_REG: "用户已注册",
ERR_MASTER_ID: "找不到对应站长的数据库",
ERR_CASH_OUT_TIME: "非可提现时间段",
ERR_CASH_OUT_USER_NOT_FOUND: "收款账号不存在",
ERR_CASH_OUT_FAIL: "提现失败",
ERR_CASH_OUT_FEE: "提现金额必须大于手续费",
ERR_CASH_OUT_TIMES: "当日提现次数已达上线",
ERR_CASH_OUT_MINI: "申请提现金额未达到最低金额要求",
ERR_CASH_OUT_MUT: "申请提现金额未达到整数倍要求",
ERR_CASH_OUT_NOT_DECIMAL: "提现申请金额只能是整数",
ERR_CASH_OUT_NOT_DAY_AVA: "不在可提现日期范围内",
ERR_USER_LEVEL_PAY_CHECK_TASK_NO_DONE: "请先完成其他任务",
ERR_USER_LEVEL_PAY_CHECK_NO_CROSS: "无法跨越升级",
ERR_USER_LEVEL_ORD_EXP: "付费订单已失效",
ERR_IS_BIND_THIRDPARTY: "该用户已经绑定了",
ERR_IS_BIND_THIRDOTHER: "该账号已经被绑定了",
ERR_IS_BIND_THIRDOTHERWECHAT: "该账号已经绑定了其他微信账号",
ERR_USER_LEVEL_UPDATE_CHECK_TASK_NO_DONE: "请完成指定任务",
ERR_USER_LEVEL_UPDATE_CHECK_NOT_FOUND_ORDER: "没有找到对应的订单",
ERR_USER_LEVEL_UPDATE_REPEAT: "不允许重复升级",
ERR_USER_NO_ACTIVE: "账户没激活",
ERR_USER_IS_BAN: "账户已被冻结",
ERR_SYSUNION_CONFIG: "联盟设置错误,请检查配置",
ERR_WECAHT_MINI: "小程序响应错误,请检查小程序配置",
ERR_WECAHT_MINI_CACHE: "获取小程序缓存失败",
ERR_WECAHT_MINI_DECODE: "小程序解密失败",
ERR_WECHAT_MINI_ACCESSTOKEN: "无法获取accesstoekn",
ERR_CURRENT_VIP_LEVEL_AUDITING: "当前等级正在审核中",
ERR_LEVEL_RENEW_SHOULD_KEEP_CURRENT: "续费只能在当前等级续费",
ERR_LEVEL_UPGRADE_APPLY_AUDITTING: "已有申请正在审核中,暂时不能申请",
ERR_LEVEL_TASK_PAY_TYPE: "任务付费类型错误",
ERR_BALANCE_NOT_ENOUGH: "余额不足",
ERR_ADMIN_PUSH: "后台MOB推送错误",
ERR_PLAN: "分拥方案出错",
ERR_MOB_CONFIG: "Mob 配置错误",
ERR_BAlANCE_PAY_ORDERTYPE: "无效余额支付订单类型",
ERR_PHONE_EXISTED: "手机号码已存在",
ERR_NOT_RESULT: "已加载完毕",
ERR_REVIEW: "审核模板错误",
ERR_USER_LEVEL_HAS_PAID: "该等级已经付过款",
ERR_IS_BIND_PDD_ERR: "获取PDD绑定信息失败",
// 404
ERR_USER_NOTFOUND: "用户不存在",
ERR_USER_DEL: "账号被删除,如有疑问请联系客服",
ERR_SUP_NOTFOUND: "上级用户不存在",
ERR_LEVEL_MAP: "无等级映射关系",
ERR_MOD_NOTFOUND: "没有找到对应模块",
ERR_CLIPBOARD_PARSE: "无法解析剪切板内容",
ERR_NOT_FAN: "没有粉丝",
ERR_CLIPBOARD_UNSUP: "不支持该平台",
ERR_USER_LEVEL: "该等级已不存在",
ERR_LACK_PAY_CFG: "支付配置不完整",
ERR_NOT_LEVEL_TASK: "等级任务查找错误",
ERR_ITEM_NOT_FOUND: "找不到对应商品",
ERR_WX_CHECKFILE_NOTFOUND: "找不到微信校验文件",
ERR_USER_BIND_OWN: "不能填写自己的邀请码",
// 429
ERR_TOO_MANY_REQUESTS: "请求频繁,请稍后重试",
// 500 内部错误
ERR: "接口错误",
ERR_SMS: "短信发送出错",
ERR_CFG: "服务器配置错误",
ERR_UNMARSHAL: "JSON解码错误",
ERR_UNKNOWN: "未知错误",
ERR_ARKID_LOGIN: "登录失败",
ERR_MOBILE_NO_EXIST: "该用户未设定手机号",
ERR_FORBIDEN_VALID: "验证码错误",
ERR_CFG_CACHE: "获取配置缓存失败",
ERR_DB_ORM: "数据操作失败",
ERR_REPEAT_RELATE: "重复关联",
ERR_ZHIMENG_CONVERT_ERR: "智盟转链失败",
ERR_MOB_FORBIDEN: "Mob调用失败",
ERR_ALIPAY_ERR: "支付宝参数错误",
ERR_ALIPAY_SETTING: "请在后台正确配置支付宝",
ERR_ALIPAY_ORDERTYPE: "无效支付宝订单类型",
ERR_ALIPAY_ORDER_ERR: "订单创建错误",
ERR_PAY_ERR: "未找到支付方式",
ERR_SEARCH_ERR: "暂无该分类商品",
ERR_LEVEL_REACH_TOP: "已经是最高等级",
ERR_USER_CHECK_ERR: "校验失败",
ERR_INIT_RABBITMQ: "连接mq失败",
}

+ 72
- 0
app/e/error.go Visa fil

@@ -0,0 +1,72 @@
package e

import (
"fmt"
"path"
"runtime"
)

type E struct {
Code int // 错误码
msg string // 报错代码
st string // 堆栈信息
}

func NewErrCode(code int) error {
if msg, ok := MsgFlags[code]; ok {
return E{code, msg, stack(3)}
}
return E{ERR_UNKNOWN, "unknown", stack(3)}
}

func NewErr(code int, msg string) error {
return E{code, msg, stack(3)}
}

func NewErrf(code int, msg string, args ...interface{}) error {
return E{code, fmt.Sprintf(msg, args), stack(3)}
}

func (e E) Error() string {
return e.msg
}

func stack(skip int) string {
stk := make([]uintptr, 32)
str := ""
l := runtime.Callers(skip, stk[:])
for i := 0; i < l; i++ {
f := runtime.FuncForPC(stk[i])
name := f.Name()
file, line := f.FileLine(stk[i])
str += fmt.Sprintf("\n%-30s[%s:%d]", name, path.Base(file), line)
}
return str
}

// ErrorIsAccountBan is 检查这个账号是否被禁用的错误
func ErrorIsAccountBan(e error) bool {
err, ok := e.(E)
if ok && err.Code == 403029 {
return true
}
return false
}

// ErrorIsAccountNoActive is 检查这个账号是否被禁用的错误
func ErrorIsAccountNoActive(e error) bool {
err, ok := e.(E)
if ok && err.Code == 403028 {
return true
}
return false
}

// ErrorIsUserDel is 检查这个账号是否被删除
func ErrorIsUserDel(e error) bool {
err, ok := e.(E)
if ok && err.Code == 403053 {
return true
}
return false
}

+ 212
- 0
app/e/msg.go Visa fil

@@ -0,0 +1,212 @@
package e

import (
"applet/app/utils"
"encoding/json"
"net/http"

"github.com/gin-gonic/gin"

"applet/app/utils/logx"
)

// GetMsg get error information based on Code
// 因为这里code是自己控制的, 因此没考虑报错信息
func GetMsg(code int) (int, string) {
if msg, ok := MsgFlags[code]; ok {
return code / 1000, msg
}
if http.StatusText(code) == "" {
code = 200
}
return code, MsgFlags[ERR_BAD_REQUEST]
}

// 成功输出, fields 是额外字段, 与code, msg同级
func OutSuc(c *gin.Context, data interface{}, fields map[string]interface{}) {
res := gin.H{
"code": 1,
"msg": "ok",
"data": data,
}
if fields != nil {
for k, v := range fields {
res[k] = v
}
}
jsonData, _ := json.Marshal(res)
strs := string(jsonData)
if c.GetString("translate_open") != "" {
strs = utils.ReadReverse(c, string(jsonData))
}
if utils.GetApiVersion(c) > 0 && utils.CheckUri(c) > 0 { //加了签名校验只返回加密的字符串
strs = utils.ResultAes(c, []byte(strs))
}
c.Writer.WriteString(strs)
}

func OutSucByLianlian(c *gin.Context, code string, msg string, data interface{}) {
res := gin.H{
"code": code,
"msg": msg,
"data": data,
}
jsonData, _ := json.Marshal(res)
strs := string(jsonData)
c.Writer.WriteString(strs)

}
func OutSucPure(c *gin.Context, data interface{}, fields map[string]interface{}) {
res := gin.H{
"code": 1,
"msg": "ok",
"data": data,
}
if fields != nil {
for k, v := range fields {
res[k] = v
}
}
jsonData, _ := json.Marshal(res)
strs := string(jsonData)
if c.GetString("translate_open") != "" {
strs = utils.ReadReverse(c, string(jsonData))
}
if utils.GetApiVersion(c) > 0 && utils.CheckUri(c) > 0 { //加了签名校验只返回加密的字符串
strs = utils.ResultAes(c, []byte(strs))
}
c.Writer.WriteString(strs)

}

// 错误输出
func OutErr(c *gin.Context, code int, err ...interface{}) {
statusCode, msg := GetMsg(code)
if len(err) > 0 && err[0] != nil {
e := err[0]
switch v := e.(type) {
case E:
statusCode = v.Code / 1000
msg = v.Error()
logx.Error(v.msg + ": " + v.st) // 记录堆栈信息
case error:
logx.Error(v)
break
case string:
msg = v
case int:
if _, ok := MsgFlags[v]; ok {
msg = MsgFlags[v]
}
}
}
if c.GetString("translate_open") != "" {
msg = utils.ReadReverse(c, msg)
}
if utils.GetApiVersion(c) > 0 && utils.CheckUri(c) > 0 { //加了签名校验只返回加密的字符串
jsonData, _ := json.Marshal(gin.H{
"code": code,
"msg": msg,
"data": []struct{}{},
})
str := utils.ResultAes(c, jsonData)
if code > 100000 {
code = int(utils.FloatFormat(float64(code/1000), 0))
}
c.Status(500)
c.Writer.WriteString(str)
} else {
c.AbortWithStatusJSON(statusCode, gin.H{
"code": code,
"msg": msg,
"data": []struct{}{},
})
}

}
func OutErrSecond(c *gin.Context, code int, err ...interface{}) {
statusCode, msg := GetMsg(code)
if len(err) > 0 && err[0] != nil {
e := err[0]
switch v := e.(type) {
case E:
statusCode = v.Code / 1000
msg = v.Error()
logx.Error(v.msg + ": " + v.st) // 记录堆栈信息
case error:
logx.Error(v)
break
case string:
msg = v
case int:
if _, ok := MsgFlags[v]; ok {
msg = MsgFlags[v]
}
}
}
if c.GetString("translate_open") != "" {
msg = utils.ReadReverse(c, msg)
}
if utils.GetApiVersion(c) > 0 && utils.CheckUri(c) > 0 { //加了签名校验只返回加密的字符串
jsonData, _ := json.Marshal(gin.H{
"code": code,
"msg": msg,
"data": "",
})
str := utils.ResultAes(c, jsonData)
if code > 100000 {
code = int(utils.FloatFormat(float64(code/1000), 0))
}
c.Status(500)
c.Writer.WriteString(str)
} else {
c.AbortWithStatusJSON(statusCode, gin.H{
"code": code,
"msg": msg,
"data": "",
})
}

}

// 重定向
func OutRedirect(c *gin.Context, code int, loc string) {
if code < 301 || code > 308 {
code = 303
}
c.Redirect(code, loc)
c.Abort()
}
func DouYouReturnMsg(c *gin.Context, statusCode, msg string) {
res := gin.H{
"status_code": statusCode,
}
if msg != "" {
res["message"] = msg
}
jsonData, _ := json.Marshal(res)
strs := string(jsonData)
c.Writer.WriteString(strs)
}
func MeituanLmReturnMsg(c *gin.Context, statusCode, msg string) {
res := gin.H{
"errcode": statusCode,
}
if msg != "" {
res["errmsg"] = msg
}
jsonData, _ := json.Marshal(res)
strs := string(jsonData)
c.Writer.WriteString(strs)
}
func TaskBoxReturnMsg(c *gin.Context, statusCode int, msg string) {
res := gin.H{
"code": statusCode,
}
if msg != "" {
res["message"] = msg
}
jsonData, _ := json.Marshal(res)
strs := string(jsonData)
c.Writer.WriteString(strs)
}

+ 8
- 0
app/e/set_cache.go Visa fil

@@ -0,0 +1,8 @@
package e

func SetCache(cacheTime int64) map[string]interface{} {
if cacheTime == 0 {
return map[string]interface{}{"cache_time": cacheTime}
}
return map[string]interface{}{"cache_time": cacheTime}
}

+ 190
- 0
app/enum/enum_merchant_coupon_scheme.go Visa fil

@@ -0,0 +1,190 @@
package enum

// ActCouponType 优惠券类型
type ActCouponType int

const (
ActCouponTypeImmediate ActCouponType = iota + 1 // 立减
ActCouponTypeReachReduce // 满减
ActCouponTypeReachDiscount // 满折
)

func (em ActCouponType) String() string {
switch em {
case ActCouponTypeImmediate:
return "立减券"
case ActCouponTypeReachReduce:
return "满减券"
case ActCouponTypeReachDiscount:
return "折扣券"
default:
return "未知类型"
}
}

// ActCouponSendWay 发放形式
type ActCouponSendWay int

const (
ActCouponSendWayPositive ActCouponSendWay = iota + 1
ActCouponSendWayManual
)

func (em ActCouponSendWay) String() string {
switch em {
case ActCouponSendWayPositive:
return "主动发放"
case ActCouponSendWayManual:
return "手动领取"
default:
return "未知类型"
}
}

// ActCouponSendTimeType 发放时间类型
type ActCouponSendTimeType int

const (
ActCouponSendTimeTypeImmediate ActCouponSendTimeType = iota + 1
ActCouponSendTimeTypeTiming
)

func (em ActCouponSendTimeType) String() string {
switch em {
case ActCouponSendTimeTypeImmediate:
return "立即发放"
case ActCouponSendTimeTypeTiming:
return "定时"
default:
return "未知类型"
}
}

// ActCouponSendUserType 发放用户
type ActCouponSendUserType int

const (
ActCouponSendUserTypeLevel ActCouponSendUserType = iota + 1
ActCouponSendUserTypeAll
ActCouponSendUserTypeSpecify
)

func (em ActCouponSendUserType) String() string {
switch em {
case ActCouponSendUserTypeLevel:
return "指定会员等级"
case ActCouponSendUserTypeAll:
return "所有人可领"
case ActCouponSendUserTypeSpecify:
return "指定用户"
default:
return "未知类型"
}
}

// ActCouponValidTimeType 有效时间
type ActCouponValidTimeType int

const (
ActCouponValidTimeTypeFix ActCouponValidTimeType = iota + 1 // 固定日期
ActCouponValidTimeTypeXDay // 领取当日开始计算有效期
ActCouponValidTimeTypeXNextDay // 领取次日开始计算有效期
)

func (em ActCouponValidTimeType) String() string {
switch em {
case ActCouponValidTimeTypeFix:
return "固定日期"
case ActCouponValidTimeTypeXDay:
return "自领取当日起,%d天内有效"
case ActCouponValidTimeTypeXNextDay:
return "自领取次日起,%d天内有效"
default:
return "未知类型"
}
}

// ActCouponUseRule 使用规则
type ActCouponUseRule int

const (
ActCouponUseRuleAll ActCouponUseRule = iota + 1 // 全部商品可用
ActCouponUseRuleSpecifyGoods // 仅可用于指定商品
ActCouponUseRuleSpecifyActivity // 可用于活动类型
)

func (em ActCouponUseRule) String() string {
switch em {
case ActCouponUseRuleAll:
return "全部商品可用"
case ActCouponUseRuleSpecifyGoods:
return "仅可用于指定商品"
case ActCouponUseRuleSpecifyActivity:
return "可用于活动类型"
default:
return "未知类型"
}
}

type ActCouponUseActivityType int

const (
ActCouponUseActivityTypeForGroup ActCouponUseActivityType = iota + 1
ActCouponUseActivityTypeForSecondKill
ActCouponUseActivityTypeForBargain
)

func (em ActCouponUseActivityType) String() string {
switch em {
case ActCouponUseActivityTypeForGroup:
return "拼团活动"
case ActCouponUseActivityTypeForSecondKill:
return "秒杀活动"
case ActCouponUseActivityTypeForBargain:
return "砍价活动"
default:
return "未知类型"
}
}

type ActCouponSendState int

const (
ActCouponSendStateUnProvide ActCouponSendState = iota + 1 // 未发放
ActCouponSendStateProvide // 已发放
ActCouponSendStateProviding // 发放中
)

func (em ActCouponSendState) String() string {
switch em {
case ActCouponSendStateUnProvide:
return "未发放"
case ActCouponSendStateProvide:
return "已发放"
case ActCouponSendStateProviding:
return "发放中"
default:
return "未知类型"
}
}

type ActUserCouponUseState int

const (
ActUserCouponUseStateUnUse ActUserCouponUseState = iota // 未使用
ActUserCouponUseStateUsed // 已使用
ActUserCouponUseStateUnValid // 失效
)

func (em ActUserCouponUseState) String() string {
switch em {
case ActUserCouponUseStateUnUse:
return "未使用"
case ActUserCouponUseStateUsed:
return "已使用"
case ActUserCouponUseStateUnValid:
return "失效"
default:
return "未知类型"
}
}

+ 10
- 0
app/hdl/hdl_cate.go Visa fil

@@ -0,0 +1,10 @@
package hdl

import (
"applet/app/svc"
"github.com/gin-gonic/gin"
)

func Cate(c *gin.Context) {
svc.Cate(c)
}

+ 16
- 0
app/hdl/hdl_goods.go Visa fil

@@ -0,0 +1,16 @@
package hdl

import (
"applet/app/svc"
"github.com/gin-gonic/gin"
)

func Goods(c *gin.Context) {
svc.Goods(c)
}
func GoodsSku(c *gin.Context) {
svc.GoodsSku(c)
}
func GoodsCoupon(c *gin.Context) {
svc.GoodsCoupon(c)
}

+ 28
- 0
app/hdl/hdl_order.go Visa fil

@@ -0,0 +1,28 @@
package hdl

import (
"applet/app/svc"
"github.com/gin-gonic/gin"
)

func OrderTotal(c *gin.Context) {
svc.OrderTotal(c)
}
func OrderCreate(c *gin.Context) {
svc.OrderCreate(c)
}
func OrderCoupon(c *gin.Context) {
svc.OrderCoupon(c)
}
func OrderCancel(c *gin.Context) {
svc.OrderCancel(c)
}
func OrderList(c *gin.Context) {
svc.OrderList(c)
}
func OrderCate(c *gin.Context) {
svc.OrderCate(c)
}
func OrderDetail(c *gin.Context) {
svc.OrderDetail(c)
}

+ 37
- 0
app/hdl/hdl_pay.go Visa fil

@@ -0,0 +1,37 @@
package hdl

import (
"applet/app/e"
"applet/app/svc"
"github.com/gin-gonic/gin"
)

func Pay(c *gin.Context) {
orderType := c.Param("orderType")
payMethod := c.Param("payMethod")
if orderType == "" || payMethod == "" {
e.OutErr(c, e.ERR_INVALID_ARGS)
return
}
payFunc, ok := svc.PayFuncList[orderType][payMethod]
if !ok || payFunc == nil {
e.OutErr(c, e.ERR, e.NewErr(500, "不存在该支付方式"))
return
}
r, err := payFunc(c)
if err != nil {
switch err.(type) {
case e.E:
err1 := err.(e.E)
e.OutErr(c, err1.Code, err1.Error())
return
default:
e.OutErr(c, e.ERR_PAY_ERR, e.NewErr(e.ERR_PAY_ERR, err.Error()))
return
}
}
e.OutSuc(c, r, nil)
return

return
}

+ 29
- 0
app/hdl/hdl_store.go Visa fil

@@ -0,0 +1,29 @@
package hdl

import (
"applet/app/e"
"applet/app/svc"
"github.com/gin-gonic/gin"
)

func BankStoreCate(c *gin.Context) {
var res = []map[string]string{
{"name": "全部网点", "value": ""},
{"name": "附近网点", "value": "1"},
{"name": "关注网点", "value": "2"},
}
e.OutSuc(c, res, nil)
return
}
func BankStore(c *gin.Context) {
svc.BankStore(c)
}
func Store(c *gin.Context) {
svc.Store(c)
}
func StoreAddLike(c *gin.Context) {
svc.StoreAddLike(c)
}
func StoreCancelLike(c *gin.Context) {
svc.StoreCancelLike(c)
}

+ 19
- 0
app/hdl/hdl_store_order.go Visa fil

@@ -0,0 +1,19 @@
package hdl

import (
"applet/app/svc"
"github.com/gin-gonic/gin"
)

func StoreOrderList(c *gin.Context) {
svc.StoreOrderList(c)
}
func StoreOrderCate(c *gin.Context) {
svc.StoreOrderCate(c)
}
func StoreOrderDetail(c *gin.Context) {
svc.StoreOrderDetail(c)
}
func StoreOrderConfirm(c *gin.Context) {
svc.StoreOrderConfirm(c)
}

+ 334
- 0
app/lib/alipay/api.go Visa fil

@@ -0,0 +1,334 @@
package alipay

import (
"applet/app/cfg"
"applet/app/md"
"applet/app/utils/logx"
"fmt"

"github.com/iGoogle-ink/gopay"
"github.com/iGoogle-ink/gopay/alipay"
)

func commClient(appID, priKey, RSA, PKCS string, paySet *md.PayData) (*alipay.Client, error) {
client := alipay.NewClient(appID, priKey, true)
client.DebugSwitch = gopay.DebugOn
//判断密钥的类型
rsaType := alipay.RSA2
pkcsType := alipay.PKCS1
if RSA == "1" {
rsaType = alipay.RSA
}
if PKCS == "1" {
pkcsType = alipay.PKCS8
}
if paySet.PayAliUseType == "1" {
rsaType = alipay.RSA2
pkcsType = alipay.PKCS8
}
//配置公共参数
client.SetCharset("utf-8").
SetSignType(rsaType).
SetPrivateKeyType(pkcsType)
//新支付宝支付
if paySet.PayAliUseType == "1" {
appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAppCertSn)
if err != nil {
return nil, err
}
if appCertSN == "" {
return nil, err
}
client.SetAppCertSN(appCertSN)
aliPayRootCertSN := "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6"
client.SetAliPayRootCertSN(aliPayRootCertSN)
aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayrsaPublicKey)
if err != nil {
return nil, err
}
if aliPayPublicCertSN == "" {
return nil, err
}
client.SetAliPayPublicCertSN(aliPayPublicCertSN)
}
return client, nil
}

//(实名证件信息比对验证预咨询)
//https://opendocs.alipay.com/apis/api_2/alipay.user.certdoc.certverify.preconsult
func UserCertverifyPreconsult(appID, priKey, userName, certNo, RSA, PKCS string, paySet *md.PayData) (*md.AlipayUserCertdocCertverifyPreconsult, error) {
client, _ := commClient(appID, priKey, RSA, PKCS, paySet)
//请求参数
body := make(gopay.BodyMap)
body.Set("user_name", userName)
body.Set("cert_type", "IDENTITY_CARD")
body.Set("cert_no", certNo)
var aliPsp md.AlipayUserCertdocCertverifyPreconsult
err := client.PostAliPayAPISelfV2(body, "alipay.user.certdoc.certverify.preconsult", aliPsp)
if err != nil {
return nil, err
}
return &aliPsp, err
}

//(实名证件信息比对验证咨询)
//https://opendocs.alipay.com/apis/api_2/alipay.user.certdoc.certverify.consult
func UserCertverifyConsult(appID, priKey, verifyId, RSA, PKCS string, paySet *md.PayData) (*md.AlipayUserCertdocCertverifyConsult, error) {
client, _ := commClient(appID, priKey, RSA, PKCS, paySet)
//请求参数
body := make(gopay.BodyMap)
body.Set("verify_id", verifyId)
var aliPsp md.AlipayUserCertdocCertverifyConsult
err := client.PostAliPayAPISelfV2(body, "alipay.user.certdoc.certverify.consult", aliPsp)
if err != nil {
return nil, err
}
return &aliPsp, err
}

// TradeAppPay is 支付宝APP支付
// 抖音头条小程序使用APP调起
func TradeAppPay(appID, priKey, subject, orderID, amount, notiURL, RSA, PKCS string, paySet *md.PayData) (string, error) {
//初始化支付宝客户端
// appID 是在支付宝申请的APPID
// priKey 是支付宝私钥
// subject 是支付订单的主题
// orderID 是智莺这边生成的订单id
// amount 是付费金额
// notiURL 通知地址url
// passback_params 回调通知参数

client := alipay.NewClient(appID, priKey, true)
client.DebugSwitch = gopay.DebugOn
//判断密钥的类型
rsa_type := alipay.RSA2
pkcs_type := alipay.PKCS1
if RSA == "1" {
rsa_type = alipay.RSA
}
if PKCS == "1" {
pkcs_type = alipay.PKCS8
}
if paySet.PayAliUseType == "1" {
rsa_type = alipay.RSA2
pkcs_type = alipay.PKCS8
}
//配置公共参数
client.SetCharset("utf-8").
SetSignType(rsa_type).
SetPrivateKeyType(pkcs_type)
if notiURL != "" {
client.SetNotifyUrl(notiURL)
}
//新支付宝支付
if paySet.PayAliUseType == "1" {
appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAppCertSn)
fmt.Println("-应用-")
fmt.Println(appCertSN)
if err != nil {
fmt.Println(err)
return "", err
}
if appCertSN == "" {
fmt.Println(err)
return "", err
}
client.SetAppCertSN(appCertSN)
//aliPayRootCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayRootCertSn)
aliPayRootCertSN := "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6"
client.SetAliPayRootCertSN(aliPayRootCertSN)
aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayrsaPublicKey)
fmt.Println("-公钥-")
fmt.Println(aliPayPublicCertSN)

if err != nil {
fmt.Println(err)
return "", err
}
if aliPayPublicCertSN == "" {
fmt.Println(err)
return "", err
}
client.SetAliPayPublicCertSN(aliPayPublicCertSN)
}
fmt.Println(client)
//请求参数
body := make(gopay.BodyMap)
body.Set("subject", subject)
body.Set("body", subject)
body.Set("out_trade_no", orderID)
body.Set("total_amount", amount)
body.Set("timeout_express", "30m")

// body.Set("passback_params", orderID)
//手机APP支付参数请求
payParam, err := client.TradeAppPay(body)
if err != nil {
return "", logx.Warn(err)
}
return payParam, nil
}

// TradeAppPay is 支付宝H5支付
func TradeWapPay(appID, priKey, subject, orderID, amount, notiURL, RSA, PKCS, page_url string, paySet *md.PayData) (string, error) {
//aliPayPublicKey := "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1wn1sU/8Q0rYLlZ6sq3enrPZw2ptp6FecHR2bBFLjJ+sKzepROd0bKddgj+Mr1ffr3Ej78mLdWV8IzLfpXUi945DkrQcOUWLY0MHhYVG2jSs/qzFfpzmtut2Cl2TozYpE84zom9ei06u2AXLMBkU6VpznZl+R4qIgnUfByt3Ix5b3h4Cl6gzXMAB1hJrrrCkq+WvWb3Fy0vmk/DUbJEz8i8mQPff2gsHBE1nMPvHVAMw1GMk9ImB4PxucVek4ZbUzVqxZXphaAgUXFK2FSFU+Q+q1SPvHbUsjtIyL+cLA6H/6ybFF9Ffp27Y14AHPw29+243/SpMisbGcj2KD+evBwIDAQAB"
privateKey := priKey
//判断密钥的类型
rsa_type := alipay.RSA2
pkcs_type := alipay.PKCS1
if RSA == "1" {
rsa_type = alipay.RSA
}
if PKCS == "1" {
pkcs_type = alipay.PKCS8
}
if paySet.PayAliUseType == "1" {
rsa_type = alipay.RSA2
pkcs_type = alipay.PKCS8
}
//初始化支付宝客户端
// appId:应用ID
// privateKey:应用秘钥
// isProd:是否是正式环境
client := alipay.NewClient(appID, privateKey, true)
//配置公共参数
client.SetCharset("utf-8").
SetSignType(rsa_type).
SetPrivateKeyType(pkcs_type).
SetReturnUrl(page_url).
SetNotifyUrl(notiURL)
//新支付宝支付
if paySet.PayAliUseType == "1" {
appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAppCertSn)
if err != nil {
fmt.Println(err)
return "", err
}
if appCertSN == "" {
fmt.Println(err)
return "", err
}
client.SetAppCertSN(appCertSN)
//aliPayRootCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayRootCertSn)
//if err != nil {
// fmt.Println(err)
// return "", err
//}
//if aliPayRootCertSN == "" {
// fmt.Println(err)
// return "", err
//}
aliPayRootCertSN := "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6"
client.SetAliPayRootCertSN(aliPayRootCertSN)
aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayrsaPublicKey)
if err != nil {
fmt.Println(err)
return "", err
}
if aliPayPublicCertSN == "" {
fmt.Println(err)
return "", err
}
client.SetAliPayPublicCertSN(aliPayPublicCertSN)
}
//请求参数
body := make(gopay.BodyMap)
body.Set("subject", subject)
body.Set("out_trade_no", orderID)
// quit_url is 用户付款中途退出返回商户网站的地址
body.Set("quit_url", notiURL)
body.Set("total_amount", amount)
// product_code is 销售产品码,商家和支付宝签约的产品码
body.Set("product_code", "QUICK_WAP_WAY")
//手机网站支付请求
payUrl, err := client.TradeWapPay(body)
if err != nil {
return "", logx.Warn(err)

}
return payUrl, nil
}

// TradeAppPay is 支付宝小程序本身支付
func TradeCreate(appID, priKey, subject, orderID, amount, notiURL, RSA, PKCS string, paySet *md.PayData) (*alipay.TradeCreateResponse, error) {
//aliPayPublicKey := "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1wn1sU/8Q0rYLlZ6sq3enrPZw2ptp6FecHR2bBFLjJ+sKzepROd0bKddgj+Mr1ffr3Ej78mLdWV8IzLfpXUi945DkrQcOUWLY0MHhYVG2jSs/qzFfpzmtut2Cl2TozYpE84zom9ei06u2AXLMBkU6VpznZl+R4qIgnUfByt3Ix5b3h4Cl6gzXMAB1hJrrrCkq+WvWb3Fy0vmk/DUbJEz8i8mQPff2gsHBE1nMPvHVAMw1GMk9ImB4PxucVek4ZbUzVqxZXphaAgUXFK2FSFU+Q+q1SPvHbUsjtIyL+cLA6H/6ybFF9Ffp27Y14AHPw29+243/SpMisbGcj2KD+evBwIDAQAB"
privateKey := priKey
rsa_type := alipay.RSA2
pkcs_type := alipay.PKCS1
if RSA == "1" {
rsa_type = alipay.RSA
}
if PKCS == "1" {
pkcs_type = alipay.PKCS8
}
if paySet.PayAliUseType == "1" {
rsa_type = alipay.RSA2
pkcs_type = alipay.PKCS8
}
//初始化支付宝客户端
// appId:应用ID
// privateKey:应用私钥,支持PKCS1和PKCS8
// isProd:是否是正式环境
client := alipay.NewClient(appID, privateKey, true)
//配置公共参数
client.SetCharset("utf-8").
SetSignType(rsa_type).
SetPrivateKeyType(pkcs_type).
SetNotifyUrl(notiURL)
if paySet.PayAliUseType == "1" {
appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAppCertSn)
if err != nil {
fmt.Println(err)
return nil, err
}
if appCertSN == "" {
fmt.Println(err)
return nil, err
}
client.SetAppCertSN(appCertSN)
//aliPayRootCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayRootCertSn)
//if err != nil {
// fmt.Println(err)
// return nil, err
//}
//if aliPayRootCertSN == "" {
// fmt.Println(err)
// return nil, err
//}
aliPayRootCertSN := "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6"
client.SetAliPayRootCertSN(aliPayRootCertSN)
aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayrsaPublicKey)
if err != nil {
fmt.Println(err)
return nil, err
}
if aliPayPublicCertSN == "" {
fmt.Println(err)
return nil, err
}
client.SetAliPayPublicCertSN(aliPayPublicCertSN)
}
//请求参数
body := make(gopay.BodyMap)
body.Set("subject", subject)
// 支付宝小程序支付时 buyer_id 为必传参数,需要提前获取,获取方法如下两种
// 1、alipay.SystemOauthToken() 返回取值:rsp.SystemOauthTokenResponse.UserId
// 2、client.SystemOauthToken() 返回取值:aliRsp.SystemOauthTokenResponse.UserId
buyer_id, err := client.SystemOauthToken(body)
if err != nil {
return nil, logx.Warn(err)
}
body.Set("buyer_id", buyer_id)
body.Set("out_trade_no", orderID)
body.Set("total_amount", amount)
//创建订单
aliRsp, err := client.TradeCreate(body)

if err != nil {
return nil, logx.Warn(err)
}
logx.Warn("aliRsp:", *aliRsp)
logx.Warn("aliRsp.TradeNo:", aliRsp.Response.TradeNo)
return aliRsp, nil

}

+ 148
- 0
app/lib/arkid/api.go Visa fil

@@ -0,0 +1,148 @@
package arkid

import (
"encoding/json"
"errors"
"fmt"

"applet/app/cfg"
"applet/app/utils"
"applet/app/utils/cache"
"applet/app/utils/logx"
)

func arkidLogin(args map[string]interface{}) ([]byte, error) {
url := cfg.ArkID.Url + "/siteapi/v1/ucenter/login/"
b, err := json.Marshal(args)
if err != nil {
return nil, logx.Error(err)
}
var d []byte
d, err = utils.CurlPost(url, b, nil)
if err != nil {
return nil, logx.Error(err)
}
return d, nil
}

func arkidLogout(token string) ([]byte, error) {
// fmt.Println(cfg.ArkID.Url)
url := cfg.ArkID.Url + "/siteapi/v1/revoke/token/"
h := map[string]string{"authorization": fmt.Sprintf("token %s", token)}
d, err := utils.CurlPost(url, "", h)
if err != nil {
return nil, logx.Error(err)
}
return d, nil
}

func arkidUserInfo(token string) ([]byte, error) {
url := cfg.ArkID.Url + "/siteapi/v1/auth/token/"
h := map[string]string{"authorization": fmt.Sprintf("token %s", token)}
d, err := utils.CurlGet(url, h)
if err != nil {
return nil, logx.Error(err)
}
return d, nil
}

func arkidRegister(args map[string]interface{}) ([]byte, error) {
url := cfg.ArkID.Url + "/siteapi/oneid/user/"
b, err := json.Marshal(args)
if err != nil {
return nil, logx.Error(err)
}
admin, err := getArkIDAdmin()
if err != nil {
return nil, logx.Error(err)
}
h := map[string]string{"authorization": fmt.Sprintf("token %s", admin.Token)}
var d []byte
d, err = utils.CurlPost(url, b, h)
if err != nil {
return nil, logx.Error(err)
}
return d, nil
}

func arkidAppAccessWhiteList(args map[string]interface{}, permName string) ([]byte, error) {
if permName == "" {
return nil, errors.New("The perm_name arg must required")
}
path := fmt.Sprintf("/siteapi/oneid/perm/%s/owner/", permName)
url := cfg.ArkID.Url + path
b, err := json.Marshal(args)
if err != nil {
return nil, logx.Error(err)
}
admin, err := getArkIDAdmin()
if err != nil {
return nil, logx.Error(err)
}
// fmt.Println(admin.Token)
h := map[string]string{"authorization": fmt.Sprintf("token %s", admin.Token)}
var d []byte
d, err = utils.CurlPatch(url, b, h)
if err != nil {
return nil, logx.Error(err)
}
return d, nil
}

func arkidUserDelete(username string) ([]byte, error) {
if username == "" {
return nil, errors.New("The username arg must required")
}
path := fmt.Sprintf("/siteapi/oneid/user/%s/", username)
url := cfg.ArkID.Url + path
admin, err := getArkIDAdmin()
if err != nil {
return nil, logx.Error(err)
}
// fmt.Println(admin.Token)
h := map[string]string{"authorization": fmt.Sprintf("token %s", admin.Token)}
var d []byte
d, err = utils.CurlDelete(url, nil, h)
if err != nil {
return nil, logx.Error(err)
}
return d, nil
}

func arkidUserUpdate(username string, args map[string]interface{}) ([]byte, error) {
if username == "" {
return nil, errors.New("The username arg must required")
}
b, err := json.Marshal(args)
if err != nil {
return nil, logx.Error(err)
}
path := fmt.Sprintf("/siteapi/oneid/user/%s/", username)
url := cfg.ArkID.Url + path
var admin *ArkIDUser
admin, err = getArkIDAdmin()
if err != nil {
return nil, logx.Error(err)
}
h := map[string]string{"authorization": fmt.Sprintf("token %s", admin.Token)}
d, err := utils.CurlPatch(url, b, h)
if err != nil {
return nil, logx.Error(err)
}
return d, nil
}

func getArkIDAdmin() (*ArkIDUser, error) {
c, err := cache.Bytes(cache.Get(ARKID_ADMIN_TOKEN))
if err != nil {
logx.Error(err)
}
if c != nil && err == nil {
admin := new(ArkIDUser)
if err = json.Unmarshal(c, admin); err != nil {
return admin, err
}
return admin, nil
}
return Init()
}

+ 6
- 0
app/lib/arkid/base.go Visa fil

@@ -0,0 +1,6 @@
package arkid

const (
BASE_URL = "http://k8s.arkid.izhim.cn"
ARKID_ADMIN_TOKEN = "arkid_admin_token"
)

+ 24
- 0
app/lib/arkid/init.go Visa fil

@@ -0,0 +1,24 @@
package arkid

import (
"applet/app/cfg"
"applet/app/utils"
"applet/app/utils/cache"
)

// Init is cache token to redis
func Init() (*ArkIDUser, error) {
arkidsdk := NewArkID()
arkadmin := new(ArkIDUser)
err := arkidsdk.SelectFunction("arkid_login").WithArgs(RequestBody{
Username: cfg.ArkID.Admin,
Password: cfg.ArkID.AdminPassword,
}).Result(arkadmin)
if err != nil {
panic(err)
}

// token 默认30天过期
cache.SetEx(ARKID_ADMIN_TOKEN, utils.Serialize(arkadmin), 2592000)
return arkadmin, err
}

+ 62
- 0
app/lib/arkid/model.go Visa fil

@@ -0,0 +1,62 @@
package arkid

type ArkIDUser struct {
Token string `json:"token"`
UserID int `json:"user_id"`
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
Mobile string `json:"mobile"`
EmployeeNumber string `json:"employee_number"`
Gender int `json:"gender"`
Perms []string `json:"perms"`
Avatar string `json:"avatar"`
Roles []string `json:"roles"`
PrivateEmail string `json:"private_email"`
Position string `json:"position"`
IsSettled bool `json:"is_settled"`
IsManager bool `json:"is_manager"`
IsAdmin bool `json:"is_admin"`
IsExternUser bool `json:"is_extern_user"`
OriginVerbose string `json:"origin_verbose"`
RequireResetPassword bool `json:"require_reset_password"`
HasPassword bool `json:"has_password"`
}

type RequestBody struct {
Token string `json:"token,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
User struct {
Avatar string `json:"avatar,omitempty"`
Email string `json:"email,omitempty"`
EmployeeNumber string `json:"employee_number,omitempty"`
Gender int `json:"gende,omitemptyr"`
Mobile string `json:"mobile,omitempty"`
Name string `json:"name,omitempty"`
Position string `json:"position,omitempty"`
PrivateEmail string `json:"private_email,omitempty"`
Username string `json:"username,omitempty"`
Depts interface{} `json:"depts,omitempty"`
Roles interface{} `json:"roles,omitempty"`
Nodes []interface{} `json:"nodes,omitempty"`
IsSettled bool `json:"is_settled,omitempty"`
Password string `json:"password,omitempty"`
RequireResetPassword bool `json:"require_reset_password,omitempty"`
HasPassword bool `json:"has_password,omitempty"`
} `json:"user,omitempty"`
NodeUids []string `json:"node_uids,omitempty"`
PermName string `json:"perm_name,omitempty"`
UserPermStatus []struct {
UID string `json:"uid,omitempty"`
Status int `json:"status,omitempty"`
} `json:"user_perm_status,omitempty"`
}

type AppAccessWhiteListResult struct {
UserPermStatus []struct {
UID string `json:"uid"`
Status int `json:"status"`
} `json:"user_perm_status"`
NodePermStatus []interface{} `json:"node_perm_status"`
}

+ 165
- 0
app/lib/arkid/sdk.go Visa fil

@@ -0,0 +1,165 @@
package arkid

import (
"applet/app/utils/cache"
"applet/app/utils/logx"
"encoding/json"
"errors"
"fmt"
)

type SDK struct {
response []byte
fmap map[string]func(RequestBody)
fname string
err error
}

//Init is init sdk
func (s *SDK) Init() {
s.fmap = make(map[string]func(RequestBody))
}

//SelectFunction is choose func
func (s *SDK) SelectFunction(fname string) *SDK {
s.fname = fname
return s
}

//WithArgs is request args
func (s *SDK) WithArgs(r RequestBody) *SDK {
f := s.fmap[s.fname]
f(r)
return s
}

//Result is result to p
func (s *SDK) Result(p interface{}) error {
if s.err != nil {
return s.err
}
if string(s.response) == "" {
return nil
}
if err := json.Unmarshal(s.response, p); err != nil {
return logx.Error(string(s.response), err)
}
return nil
}

// Register is register func
func (s *SDK) Register(name string, f func(RequestBody)) {
s.fmap[name] = f
}

//getAdmin arkid 用户的信息 ,主要是token
func (s *SDK) arkidLogin(r RequestBody) {
postData := map[string]interface{}{
"username": r.Username,
"password": r.Password,
}
s.response, s.err = arkidLogin(postData)
}

func (s *SDK) arkidRegister(r RequestBody) {
postData := map[string]interface{}{}
b, err := json.Marshal(r)
if err != nil {
s.err = err
}
if err := json.Unmarshal(b, &postData); err != nil {
s.err = err
}
s.response, s.err = arkidRegister(postData)
}

func (s *SDK) arkidAppAccessWhiteList(r RequestBody) {
postData := map[string]interface{}{}
b, err := json.Marshal(r)
if err != nil {
s.err = err
}
if err := json.Unmarshal(b, &postData); err != nil {
s.err = err
}
s.response, s.err = arkidAppAccessWhiteList(postData, r.PermName)
}

func (s *SDK) arkidUserInfo(r RequestBody) {
s.response, s.err = arkidUserInfo(r.Token)
}

func (s *SDK) arkidUserDelete(r RequestBody) {
s.response, s.err = arkidUserDelete(r.Username)
}

func (s *SDK) arkidUserUpdate(r RequestBody) {
postData := map[string]interface{}{}
b, err := json.Marshal(r.User)
if err != nil {
s.err = err
}
if err := json.Unmarshal(b, &postData); err != nil {
s.err = err
}
s.response, s.err = arkidUserUpdate(r.Username, postData)
}

func (s *SDK) arkidLogout(r RequestBody) {
s.response, s.err = arkidLogout(r.Token)
}

// NewArkID is con
func NewArkID() *SDK {
sdk := new(SDK)
sdk.Init()
sdk.Register("arkid_login", sdk.arkidLogin)
sdk.Register("arkid_register", sdk.arkidRegister)
sdk.Register("arkid_app_access_white_list", sdk.arkidAppAccessWhiteList)
sdk.Register("arkid_delete_user", sdk.arkidUserDelete)
sdk.Register("arkid_user_info", sdk.arkidUserInfo)
sdk.Register("arkid_user_update", sdk.arkidUserUpdate)
sdk.Register("arkid_logout", sdk.arkidLogout)
return sdk
}

// GetArkIDUser is get arkid token if redis is existed unless send request to arkid
func GetArkIDUser(username string, MD5passowrd string) (*ArkIDUser, error) {
key := fmt.Sprintf("arkid_user_%s", username)
arkidUser := new(ArkIDUser)
c, err := cache.GetBytes(key)
if c != nil && err == nil {
if err := json.Unmarshal(c, arkidUser); err != nil {
return arkidUser, err
}
if arkidUser.Token == "" {

return arkidUser, errors.New("Get Arkid User error, Token missing")
}

return arkidUser, err
}
arkidSdk := NewArkID()
err = arkidSdk.SelectFunction("arkid_login").WithArgs(RequestBody{
Username: username,
Password: MD5passowrd,
}).Result(arkidUser)
if arkidUser.Token == "" {
return arkidUser, errors.New("Get Arkid User error, Token missing")
}
// 缓存30天
// cache.SetEx(key, utils.Serialize(arkidUser), 2592000)
return arkidUser, err
}

// RegisterRollback is 注册时的错误回滚
func RegisterRollback(username string) error {
sdk := NewArkID()
err := sdk.SelectFunction("arkid_delete_user").WithArgs(RequestBody{
Username: username,
}).Result(nil)
if err != nil {
return err
}
return nil
}

+ 25
- 0
app/lib/auth/base.go Visa fil

@@ -0,0 +1,25 @@
package auth

import (
"time"

"github.com/dgrijalva/jwt-go"
)

// TokenExpireDuration is jwt 过期时间
const TokenExpireDuration = time.Hour * 4380

const RefreshTokenExpireDuration = time.Hour * 4380

var Secret = []byte("zyos")

// JWTUser 如果想要保存更多信息,都可以添加到这个结构体中
type JWTUser struct {
UID int `json:"uid"`
Username string `json:"username"`
Phone string `json:"phone"`
AppName string `json:"app_name"`
MiniOpenID string `json:"mini_open_id"` // 小程序的open_id
MiniSK string `json:"mini_session_key"` // 小程序的session_key
jwt.StandardClaims
}

+ 297
- 0
app/lib/mob/api.go Visa fil

@@ -0,0 +1,297 @@
package mob

import (
"applet/app/db"
"applet/app/e"
"applet/app/lib/sms"
"applet/app/lib/zhimeng"
"applet/app/utils"
"applet/app/utils/logx"
"bytes"
"crypto/cipher"
"crypto/des"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"sort"
"time"

"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
)

const base string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

// Mob is mob sdk
var Mob *SDK

// MobMap is 每个站长都要有自己的mob 对象
var MobMap map[string]*SDK

//Init 初始化
func Init() {
// 后续可能要传请求的上下文来获取对应的配置
// mob 目前都是我们来管理每个站长的app 所以使用template 库
//fmt.Println("Mob SDK init ....")
ch := make(chan struct{}) // 只是做信号标志的话 空struct 更省点资源
MobMap = make(map[string]*SDK)
// 初始化
for k, e := range db.DBs {
m := db.SysCfgGetWithDb(e, k, "third_app_push_set")
if m == "" {
fmt.Printf("masterid:%s 找不到推送配置", k)
continue
}
key := gjson.Get(m, "mobAppKey").String()
secret := gjson.Get(m, "mobAppSecret").String()
if key == "" || secret == "" {
fmt.Println(k + ":mob no config")
continue
}
// fmt.Println(k, key, secret)
mob := new(SDK)
mob.AppKey = key
mob.AppSecret = secret
MobMap[k] = mob
fmt.Println(k + ":mob config success")
}
go func() {
ch <- struct{}{}
}()

// 定时任务
go func(MobMap map[string]*SDK, ch chan struct{}) {
<-ch
ticker := time.NewTicker(time.Duration(time.Second * 15))
//每 15s 一次更新一次mob 配置
for range ticker.C {
for k, e := range db.DBs {
if err := e.Ping(); err != nil {
logx.Info(err)
continue
}
m := db.SysCfgGetWithDb(e, k, "third_app_push_set")
if m == "" {
fmt.Printf("masterid:%s 找不到推送配置", k)
continue
}
key := gjson.Get(m, "mobAppKey").String()
secret := gjson.Get(m, "mobAppSecret").String()
if key == "" || secret == "" {
fmt.Println(k + ":mob no config")
continue
}
// fmt.Println(k, key, secret)
mob := new(SDK)
mob.AppKey = key
mob.AppSecret = secret
MobMap[k] = mob
// fmt.Println(k + ":mob config success")
}
}
}(MobMap, ch)
}

// GetMobSDK is 获取mob 的sdk
func GetMobSDK(mid string) (*SDK, error) {
selectDB := db.DBs[mid]
m := db.SysCfgGetWithDb(selectDB, mid, "third_app_push_set")
if m == "" {
return nil, errors.New("获取不到推送配置")
}
key := gjson.Get(m, "mobAppKey").String()
secret := gjson.Get(m, "mobAppSecret").String()
if key == "" || secret == "" {
return nil, fmt.Errorf("%s mob not config", mid)
}

return &SDK{AppKey: key, AppSecret: secret}, nil
}

// SDK is mob_push 的sdk
type SDK struct {
AppKey string
AppSecret string
}

//MobFreeLogin is 秒验
func (s *SDK) MobFreeLogin(args map[string]interface{}) (string, error) {
var url string = "http://identify.verify.mob.com/auth/auth/sdkClientFreeLogin"
// https://www.mob.com/wiki/detailed/?wiki=miaoyan_for_fuwuduan_mianmifuwuduanjieru&id=78
//加appkey
args["appkey"] = s.AppKey
//加签名
args["sign"] = generateSign(args, s.AppSecret)
b, err := json.Marshal(args)
if err != nil {
return "", logx.Warn(err)
}
// 发送请求
respBody, err := httpPostBody(url, b)
if err != nil {
return "", logx.Warn(err)
}
// 反序列化
ret := struct {
Status int `json:"status"`
Error string `json:"error"`
Res interface{} `json:"res"`
}{}
// 要拿 ret 里面 Res 再解密
if err := json.Unmarshal(respBody, &ret); err != nil {
return "", logx.Warn(err)
}
//fmt.Println(ret)
// ret里面的Res 反序列化为结构体
res := struct {
IsValid int `json:"isValid"`
Phone string `json:"phone"`
}{}
// 判断是否返回正确 状态码
if ret.Status == 200 {
decode, _ := base64Decode([]byte(ret.Res.(string)))
decr, _ := desDecrypt(decode, []byte(s.AppSecret)[0:8])
if err := json.Unmarshal(decr, &res); err != nil {
return "", logx.Warn(err)
}
}
// 有效则拿出res 里的电话号码
if res.IsValid == 1 {
return res.Phone, nil
}
// Status 不等于200 则返回空
return "", fmt.Errorf("Mob error , status code %v ", ret.Status)
}

// MobSMS is mob 的短信验证
func (s *SDK) MobSMS(c *gin.Context, args map[string]interface{}) (bool, error) {
// mob 的短信验证
// https://www.mob.com/wiki/detailed/?wiki=SMSSDK_for_yanzhengmafuwuduanxiaoyanjiekou&id=23
url := "https://webapi.sms.mob.com/sms/verify"
//加appkey
args["appkey"] = s.AppKey
fmt.Println(args)
//fmt.Println(args)
// 发送请求
respBody, err := utils.CurlPost(url, args, nil)
if err != nil {
fmt.Println(err)
return false, logx.Warn(err)
}
fmt.Println("=======================mob")
fmt.Println("mob", string(respBody))
code := gjson.GetBytes(respBody, "status").Int()
if code == 468 {
return false, errors.New("验证码错误")
}
if code != 200 {
utils.FilePutContents("sms", string(respBody))
return false, errors.New("验证码错误~")
}

if c.GetString("not_deduction_doing") == "1" { //这是前面扣过了
return true, nil
}
// TODO 成功后扣费暂时先接旧智盟
sdk, err := sms.NewZhimengSMS(c).SelectFunction("deduction_doing").WithSMSArgs(map[string]interface{}{
"mobile": args["phone"],
"getmsg": "1",
}).Result()
if err != nil {
return false, logx.Warn(err)
}
zr := sdk.ToInterface().(string)
if zr == "1" {
logx.Infof("旧智盟扣费成功 appkey %s", zhimeng.SMS_APP_KEY)
}
return true, nil
}

func pkcs5UnPadding(origData []byte) []byte {
length := len(origData)
// 去掉最后一个字节 unpadding 次
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}

func desDecrypt(crypted, key []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, []byte("00000000"))
origData := make([]byte, len(crypted))
// origData := crypted
blockMode.CryptBlocks(origData, crypted)
origData = pkcs5UnPadding(origData)
// origData = ZeroUnPadding(origData)
return origData, nil
}

func base64Decode(src []byte) ([]byte, error) {
var coder *base64.Encoding
coder = base64.NewEncoding(base)
return coder.DecodeString(string(src))
}

func httpPostBody(url string, msg []byte) ([]byte, error) {
resp, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer(msg))
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
return body, err
}

func generateSign(request map[string]interface{}, secret string) string {
ret := ""
var keys []string
for k := range request {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
ret = ret + fmt.Sprintf("%v=%v&", k, request[k])
}
ret = ret[:len(ret)-1] + secret

md5Ctx := md5.New()
md5Ctx.Write([]byte(ret))
cipherStr := md5Ctx.Sum(nil)
return hex.EncodeToString(cipherStr)
}

func Check(c *gin.Context, phone, zone, validCode string, ok1 bool) (bool, error) {
smsPlatform := sms.GetSmsPlatform(c)

if smsPlatform == "mob" {
mob1, errr := GetMobSDK(c.GetString("mid"))
if errr != nil {
return false, e.NewErr(400, "mob配置错误")
}
send := map[string]interface{}{
"phone": phone,
"zone": zone,
"code": validCode,
}
if zone == "" {
send["zone"] = "86"
}
c.Set("not_deduction_doing", "1")
ok, err := mob1.MobSMS(c, send)
fmt.Println(ok)
if err != nil {
fmt.Println(err)
return false, e.NewErr(400, "验证码校验错误")
}

return ok, nil
}
return ok1, nil
}

+ 15
- 0
app/lib/mob/main.go Visa fil

@@ -0,0 +1,15 @@
package mob

import "applet/app/svc"

//NewMobSDK 构建一个Mobsdk对象
func NewMobSDK() *SDK {
// 后续可能要传请求的上下文来获取对应的配置
// mob 目前都是我们来管理每个站长的app 所以使用template 库
key := svc.SysCfgGet(nil, "third_mob_app_key")
secret := svc.SysCfgGet(nil, "third_mob_app_secret")
mob := new(SDK)
mob.AppKey = key
mob.AppSecret = secret
return mob
}

+ 16
- 0
app/lib/qiniu/bucket_create.go Visa fil

@@ -0,0 +1,16 @@
package qiniu

import (
"github.com/qiniu/api.v7/v7/auth"
"github.com/qiniu/api.v7/v7/storage"
)

func BucketCreate() error {
mac := auth.New(AK, SK)
cfg := storage.Config{
// 是否使用https域名进行资源管理
UseHTTPS: false,
}
bucketManager := storage.NewBucketManager(mac, &cfg)
return bucketManager.CreateBucket("", storage.RIDHuanan)
}

+ 18
- 0
app/lib/qiniu/bucket_delete.go Visa fil

@@ -0,0 +1,18 @@
package qiniu

import (
"github.com/qiniu/api.v7/v7/auth"
"github.com/qiniu/api.v7/v7/storage"
)

func BucketDelete(bucketName string) error {
mac := auth.New(AK, SK)

cfg := storage.Config{
// 是否使用https域名进行资源管理
UseHTTPS: false,
}

bucketManager := storage.NewBucketManager(mac, &cfg)
return bucketManager.DropBucket(bucketName)
}

+ 18
- 0
app/lib/qiniu/bucket_get_domain.go Visa fil

@@ -0,0 +1,18 @@
package qiniu

import (
"github.com/qiniu/api.v7/v7/auth"
"github.com/qiniu/api.v7/v7/storage"
)

func BucketGetDomain(bucketName string) (string, error) {
mac := auth.New(AK, SK)

cfg := storage.Config{UseHTTPS: false}
bucketManager := storage.NewBucketManager(mac, &cfg)
b, err := bucketManager.ListBucketDomains(bucketName)
if err != nil {
return "", err
}
return b[0].Domain, nil
}

+ 22
- 0
app/lib/qiniu/init.go Visa fil

@@ -0,0 +1,22 @@
package qiniu

import (
"applet/app/utils"
)

var (
AK = "MmxNdai23egjNUHjdzEVaTPdPCIbWzENz9BQuak3"
SK = "mElaFlM9O16rXp-ihoQdJ9KOH56naKm3MoyQBA59"
BUCKET = "dev-fnuoos" // 桶子名称
BUCKET_SCHEME = "http"
BUCKET_REGION = "up-z2.qiniup.com"
Expires uint64 = 3600
)

func Init(ak, sk, bucket, region, scheme string) {
AK, SK, BUCKET, BUCKET_REGION, BUCKET_SCHEME = ak, sk, bucket, region, scheme
}

func Sign(t string) string {
return utils.Md5(AK + SK + t)
}

+ 55
- 0
app/lib/qiniu/req_img_upload.go Visa fil

@@ -0,0 +1,55 @@
package qiniu

import (
"time"

"github.com/qiniu/api.v7/v7/auth/qbox"
_ "github.com/qiniu/api.v7/v7/conf"
"github.com/qiniu/api.v7/v7/storage"

"applet/app/md"
"applet/app/utils"
)

// 请求图片上传地址信息
func ReqImgUpload(f *md.FileCallback, callbackUrl string) interface{} {
if ext := utils.FileExt(f.FileName); ext == "png" || ext == "jpg" || ext == "jpeg" || ext == "gif" || ext == "bmp" || ext == "webp" {
f.Width = "$(imageInfo.width)"
f.Height = "$(imageInfo.height)"
}
f.Provider = "qiniu"
f.FileSize = "$(fsize)"
f.Hash = "$(etag)"
f.Bucket = "$(bucket)"
f.Mime = "$(mimeType)"
f.Time = utils.Int64ToStr(time.Now().Unix())
f.Sign = Sign(f.Time)
putPolicy := storage.PutPolicy{
Scope: BUCKET + ":" + f.FileName, // 使用覆盖方式时候必须请求里面有key,否则报错
Expires: Expires,
ForceSaveKey: true,
SaveKey: f.FileName,
//MimeLimit: "image/*", // 只允许上传图片
CallbackURL: callbackUrl,
CallbackBody: utils.SerializeStr(f),
CallbackBodyType: "application/json",
}
return &struct {
Method string `json:"method"`
Key string `json:"key"`
Host string `json:"host"`
Token string `json:"token"`
}{Key: f.FileName, Method: "POST", Host: BUCKET_SCHEME + "://" + BUCKET_REGION, Token: putPolicy.UploadToken(qbox.NewMac(AK, SK))}
}

/*
form表单上传
地址 : http://upload-z2.qiniup.com
header
- Content-Type : multipart/form-data

body :
- key : 文件名
- token : 生成token
- file : 待上传文件
*/

+ 122
- 0
app/lib/sms/sms.go Visa fil

@@ -0,0 +1,122 @@
package sms

import (
"applet/app/db"
"applet/app/lib/zhimeng"
"applet/app/svc"
"applet/app/utils/cache"
"applet/app/utils/logx"
"code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/sms"
"errors"
"fmt"
"github.com/tidwall/gjson"

"github.com/gin-gonic/gin"
)

// NewZhimengSMS is 智盟的短信服务
func NewZhimengSMS(c *gin.Context) *zhimeng.SDK {
sms := new(zhimeng.SDK)
key := svc.SysCfgGet(c, "third_zm_sms_key")
secret := svc.SysCfgGet(c, "third_zm_sms_secret")
if key == "" || secret == "" {
_ = logx.Warn("短信服务配置错误")
}
sms.Init("send_msg", key, secret)
return sms
}
func GetSmsPlatform(c *gin.Context) string {
var smsPlatform = "ljioe"
key := fmt.Sprintf("%s:sms_platform", c.GetString("mid"))
smsPlatformTmp, _ := cache.GetString(key)
if smsPlatformTmp == "" {
smsPlatformTmp = svc.GetWebSiteAppSmsPlatform(c.GetString("mid"))
if smsPlatformTmp != "" {
cache.SetEx(key, smsPlatformTmp, 300)
}
}
if smsPlatformTmp != "" {
smsPlatform = smsPlatformTmp
}
return smsPlatform
}
func GetTplId(c *gin.Context, zone, types string) string {
// 校验短信验证码
tplId := ""
if zone != "86" {
tplId = svc.SysCfgGet(c, "mob_sms_sdk_international_template_id")
} else {
tplId = svc.SysCfgGet(c, "mob_sms_sdk_template_id")
}
if c.GetString("app_type") == "o2o" {
tplId = db.SysCfgGet(c, "biz_mob_sms_sdk_template_id")
}
normal := gjson.Get(tplId, types).String()
if normal == "" {
normal = gjson.Get(tplId, "normal").String()
}
return normal
}
func GetSmsConfig(c *gin.Context, zone string, postData map[string]interface{}) error {
m := db.SysCfgGet(c, "third_app_push_set")
if c.GetString("app_type") == "o2o" {
m = db.SysCfgGet(c, "biz_third_app_push_set")
}
key := gjson.Get(m, "mobAppKey").String()
postData["is_mob"] = "1"
postData["type"] = "mob"
postData["sms_type"] = "putong"
smsPlatform := GetSmsPlatform(c)
if smsPlatform == "ljioe" {
postData["is_mob"] = "0"
postData["type"] = ""
}
token := c.GetHeader("Authorization")
if zone == "" && token != "" {
arkToken, _ := db.UserProfileFindByArkToken(svc.MasterDb(c), token)
if arkToken != nil && arkToken.Uid > 0 {
user, _ := db.UserFindByID(svc.MasterDb(c), arkToken.Uid)
if user != nil && user.Uid > 0 {
zone = user.Zone
}
}
}
if zone == "" {
zone = "86"
}
if zone != "86" { //国际短信
postData["is_sales"] = "2"
postData["sms_type"] = "international"
}
postData["templateCode"] = GetTplId(c, zone, postData["templateCode"].(string))
postData["zone"] = zone
if key != "" {
postData["smsmsg_key"] = key
}
if c.GetString("sms_type") == "1" { //新的
postData["uid"] = c.GetString("mid")
err := sms.SmsSend(db.Db, postData)
if err != nil {
return err
}
return nil
}
fmt.Println("===短信", postData, c.ClientIP())
sdk, err := NewZhimengSMS(c).SelectFunction("msg_doing").WithSMSArgs(postData).Result()
if err != nil {
msg := gjson.Get(err.Error(), "msg").String()
if msg == "" {
msg = err.Error()
}
fmt.Println("===短信", err)
errs := errors.New(msg)
return errs
}
rmap := sdk.ToInterface().(map[string]interface{})
fmt.Println("===短信", rmap)

if rmap["status"] == "" {
return err
}
return nil
}

Vissa filer visades inte eftersom för många filer har ändrats

Laddar…
Avbryt
Spara