This commit is contained in:
2025-12-29 19:37:09 +08:00
41 changed files with 1369 additions and 188 deletions

View File

@@ -65,6 +65,22 @@ service main {
// 银行卡提现审核(确认/拒绝)
@handler AdminReviewBankCardWithdrawal
post /agent-withdrawal/bank-card/review (AdminReviewBankCardWithdrawalReq) returns (AdminReviewBankCardWithdrawalResp)
// 获取提现统计数据
@handler AdminGetWithdrawalStatistics
get /agent-withdrawal/statistics (AdminGetWithdrawalStatisticsReq) returns (AdminGetWithdrawalStatisticsResp)
// 获取代理订单统计数据
@handler AdminGetAgentOrderStatistics
get /agent-order/statistics (AdminGetAgentOrderStatisticsReq) returns (AdminGetAgentOrderStatisticsResp)
// 获取代理统计数据
@handler AdminGetAgentStatistics
get /statistics (AdminGetAgentStatisticsReq) returns (AdminGetAgentStatisticsResp)
// 获取代理链接产品统计
@handler AdminGetAgentLinkProductStatistics
get /agent-link/product-statistics (AdminGetAgentLinkProductStatisticsReq) returns (AdminGetAgentLinkProductStatisticsResp)
}
type (
@@ -405,4 +421,51 @@ type (
AdminReviewBankCardWithdrawalResp {
Success bool `json:"success"` // 是否成功
}
// 获取提现统计数据请求
AdminGetWithdrawalStatisticsReq {
}
// 获取提现统计数据响应
AdminGetWithdrawalStatisticsResp {
TotalWithdrawalAmount float64 `json:"total_withdrawal_amount"` // 总提现金额
TodayWithdrawalAmount float64 `json:"today_withdrawal_amount"` // 今日提现金额
TotalActualAmount float64 `json:"total_actual_amount"` // 总实际到账金额
TotalTaxAmount float64 `json:"total_tax_amount"` // 总扣税金额
}
// 获取代理订单统计数据请求
AdminGetAgentOrderStatisticsReq {
}
// 获取代理订单统计数据响应
AdminGetAgentOrderStatisticsResp {
TotalAgentOrderCount int64 `json:"total_agent_order_count"` // 总代理订单数
TodayAgentOrderCount int64 `json:"today_agent_order_count"` // 今日代理订单数
}
// 获取代理统计数据请求
AdminGetAgentStatisticsReq {
}
// 获取代理统计数据响应
AdminGetAgentStatisticsResp {
TotalAgentCount int64 `json:"total_agent_count"` // 总代理数
TodayAgentCount int64 `json:"today_agent_count"` // 今日新增代理数
}
// 获取代理链接产品统计请求
AdminGetAgentLinkProductStatisticsReq {
}
// 代理链接产品统计列表项
AgentLinkProductStatisticsItem {
ProductName string `json:"product_name"` // 产品名称
LinkCount int64 `json:"link_count"` // 推广链接数量
}
// 获取代理链接产品统计响应
AdminGetAgentLinkProductStatisticsResp {
Items []AgentLinkProductStatisticsItem `json:"items"` // 列表数据
}
)

View File

@@ -45,8 +45,9 @@ service main {
type (
// 创建功能请求
AdminCreateFeatureReq {
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CostPrice float64 `json:"cost_price"` // 成本价
}
// 创建功能响应
AdminCreateFeatureResp {
@@ -54,9 +55,10 @@ type (
}
// 更新功能请求
AdminUpdateFeatureReq {
Id int64 `path:"id"` // 功能ID
ApiId *string `json:"api_id,optional"` // API标识
Name *string `json:"name,optional"` // 描述
Id int64 `path:"id"` // 功能ID
ApiId *string `json:"api_id,optional"` // API标识
Name *string `json:"name,optional"` // 描述
CostPrice *float64 `json:"cost_price,optional"` // 成本价
}
// 更新功能响应
AdminUpdateFeatureResp {
@@ -79,11 +81,12 @@ type (
}
// 功能列表项
FeatureListItem {
Id int64 `json:"id"` // 功能ID
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CreateTime string `json:"create_time"` // 创建时间
UpdateTime string `json:"update_time"` // 更新时间
Id int64 `json:"id"` // 功能ID
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CostPrice float64 `json:"cost_price"` // 成本价
CreateTime string `json:"create_time"` // 创建时间
UpdateTime string `json:"update_time"` // 更新时间
}
// 获取功能列表响应
AdminGetFeatureListResp {
@@ -96,11 +99,12 @@ type (
}
// 获取功能详情响应
AdminGetFeatureDetailResp {
Id int64 `json:"id"` // 功能ID
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CreateTime string `json:"create_time"` // 创建时间
UpdateTime string `json:"update_time"` // 更新时间
Id int64 `json:"id"` // 功能ID
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CostPrice float64 `json:"cost_price"` // 成本价
CreateTime string `json:"create_time"` // 创建时间
UpdateTime string `json:"update_time"` // 更新时间
}
// 配置功能示例数据请求
AdminConfigFeatureExampleReq {

View File

@@ -39,6 +39,22 @@ service main {
@doc "重新执行代理处理"
@handler AdminRetryAgentProcess
post /retry-agent-process/:id (AdminRetryAgentProcessReq) returns (AdminRetryAgentProcessResp)
@doc "获取退款统计数据"
@handler AdminGetRefundStatistics
get /refund-statistics (AdminGetRefundStatisticsReq) returns (AdminGetRefundStatisticsResp)
@doc "获取收入和利润统计数据"
@handler AdminGetRevenueStatistics
get /revenue-statistics (AdminGetRevenueStatisticsReq) returns (AdminGetRevenueStatisticsResp)
@doc "获取订单来源统计数据"
@handler AdminGetOrderSourceStatistics
get /source-statistics (AdminGetOrderSourceStatisticsReq) returns (AdminGetOrderSourceStatisticsResp)
@doc "获取订单统计数据"
@handler AdminGetOrderStatistics
get /statistics (AdminGetOrderStatisticsReq) returns (AdminGetOrderStatisticsResp)
}
type (
@@ -60,6 +76,7 @@ type (
PayTimeEnd string `form:"pay_time_end,optional"` // 支付时间结束
RefundTimeStart string `form:"refund_time_start,optional"` // 退款时间开始
RefundTimeEnd string `form:"refund_time_end,optional"` // 退款时间结束
SalesCost float64 `form:"sales_cost,optional"` // 成本价
}
// 列表响应
AdminGetOrderListResp {
@@ -75,6 +92,7 @@ type (
PaymentPlatform string `json:"payment_platform"` // 支付方式
PaymentScene string `json:"payment_scene"` // 支付平台
Amount float64 `json:"amount"` // 金额
SalesCost float64 `json:"sales_cost"` // 成本价
Status string `json:"status"` // 支付状态pending-待支付paid-已支付refunded-已退款closed-已关闭failed-支付失败
QueryState string `json:"query_state"` // 查询状态pending-待查询success-查询成功failed-查询失败 processing-查询中
CreateTime string `json:"create_time"` // 创建时间
@@ -83,6 +101,7 @@ type (
IsPromotion int64 `json:"is_promotion"` // 是否推广订单0-否1-是
IsAgentOrder bool `json:"is_agent_order"` // 是否是代理订单
AgentProcessStatus string `json:"agent_process_status"` // 代理事务处理状态not_agent-非代理订单success-处理成功failed-处理失败pending-待处理
}
// 详情请求
AdminGetOrderDetailReq {
@@ -97,6 +116,7 @@ type (
PaymentPlatform string `json:"payment_platform"` // 支付方式
PaymentScene string `json:"payment_scene"` // 支付平台
Amount float64 `json:"amount"` // 金额
SalesCost float64 `json:"sales_cost"` // 成本价
Status string `json:"status"` // 支付状态pending-待支付paid-已支付refunded-已退款closed-已关闭failed-支付失败
QueryState string `json:"query_state"` // 查询状态pending-待查询success-查询成功failed-查询失败 processing-查询中
CreateTime string `json:"create_time"` // 创建时间
@@ -170,4 +190,58 @@ type (
Message string `json:"message"` // 执行结果消息
ProcessedAt string `json:"processed_at"` // 处理时间
}
// 获取退款统计数据请求
AdminGetRefundStatisticsReq {
}
// 获取退款统计数据响应
AdminGetRefundStatisticsResp {
TotalRefundAmount float64 `json:"total_refund_amount"` // 总退款金额
TodayRefundAmount float64 `json:"today_refund_amount"` // 今日退款金额
}
// 获取收入和利润统计数据请求
AdminGetRevenueStatisticsReq {
}
// 获取收入和利润统计数据响应
AdminGetRevenueStatisticsResp {
TotalRevenueAmount float64 `json:"total_revenue_amount"` // 总收入金额
TodayRevenueAmount float64 `json:"today_revenue_amount"` // 今日收入金额
TotalProfitAmount float64 `json:"total_profit_amount"` // 总利润金额
TodayProfitAmount float64 `json:"today_profit_amount"` // 今日利润金额
}
// 获取订单来源统计数据请求
AdminGetOrderSourceStatisticsReq {
}
// 订单来源统计项
OrderSourceStatisticsItem {
ProductName string `json:"product_name"` // 产品名称
OrderCount int64 `json:"order_count"` // 订单数量
}
// 获取订单来源统计数据响应
AdminGetOrderSourceStatisticsResp {
Items []OrderSourceStatisticsItem `json:"items"` // 订单来源统计列表
}
// 获取订单统计数据请求
AdminGetOrderStatisticsReq {
Dimension string `form:"dimension"` // 时间维度day-日(当月1号到今天)month-月(今年1月到当月)year-年(过去5年)all-全部(按日统计)
}
// 订单统计项
OrderStatisticsItem {
Date string `json:"date"` // 日期
Count int64 `json:"count"` // 订单数量
Amount float64 `json:"amount"` // 订单金额
}
// 获取订单统计数据响应
AdminGetOrderStatisticsResp {
Items []OrderStatisticsItem `json:"items"` // 订单统计列表
}
)

View File

@@ -82,8 +82,8 @@ TaxConfig:
TaxRate: 0.06
TaxExemptionAmount: 0.00
Tianyuanapi:
AccessID: "7f8a9b2c4d5e6f1a"
Key: "9e4f8a1b3c6d7e2f5a8b9c0d1e4f7a2b"
AccessID: "9e60b34eb51f3827"
Key: "04c6b4c559be6d5ba5351c04c8713a64"
BaseURL: "https://api.tianyuanapi.com"
Timeout: 60
Authorization:

View File

@@ -83,8 +83,8 @@ TaxConfig:
TaxRate: 0.06
TaxExemptionAmount: 0.00
Tianyuanapi:
AccessID: "7f8a9b2c4d5e6f1a"
Key: "9e4f8a1b3c6d7e2f5a8b9c0d1e4f7a2b"
AccessID: "9e60b34eb51f3827"
Key: "04c6b4c559be6d5ba5351c04c8713a64"
BaseURL: "https://api.tianyuanapi.com"
Timeout: 60
Authorization:

View File

@@ -0,0 +1,29 @@
package admin_agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/main/api/internal/logic/admin_agent"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
)
func AdminGetAgentLinkProductStatisticsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AdminGetAgentLinkProductStatisticsReq
if err := httpx.Parse(r, &req); err != nil {
result.ParamErrorResult(r, w, err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
l := admin_agent.NewAdminGetAgentLinkProductStatisticsLogic(r.Context(), svcCtx)
resp, err := l.AdminGetAgentLinkProductStatistics(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@@ -0,0 +1,29 @@
package admin_agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/main/api/internal/logic/admin_agent"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
)
func AdminGetAgentOrderStatisticsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AdminGetAgentOrderStatisticsReq
if err := httpx.Parse(r, &req); err != nil {
result.ParamErrorResult(r, w, err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
l := admin_agent.NewAdminGetAgentOrderStatisticsLogic(r.Context(), svcCtx)
resp, err := l.AdminGetAgentOrderStatistics(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@@ -0,0 +1,29 @@
package admin_agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/main/api/internal/logic/admin_agent"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
)
func AdminGetAgentStatisticsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AdminGetAgentStatisticsReq
if err := httpx.Parse(r, &req); err != nil {
result.ParamErrorResult(r, w, err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
l := admin_agent.NewAdminGetAgentStatisticsLogic(r.Context(), svcCtx)
resp, err := l.AdminGetAgentStatistics(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@@ -0,0 +1,30 @@
package admin_agent
import (
"net/http"
"tydata-server/app/main/api/internal/logic/admin_agent"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func AdminGetWithdrawalStatisticsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AdminGetWithdrawalStatisticsReq
if err := httpx.Parse(r, &req); err != nil {
result.ParamErrorResult(r, w, err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
l := admin_agent.NewAdminGetWithdrawalStatisticsLogic(r.Context(), svcCtx)
resp, err := l.AdminGetWithdrawalStatistics(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@@ -0,0 +1,30 @@
package admin_order
import (
"net/http"
"tydata-server/app/main/api/internal/logic/admin_order"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func AdminGetOrderSourceStatisticsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AdminGetOrderSourceStatisticsReq
if err := httpx.Parse(r, &req); err != nil {
result.ParamErrorResult(r, w, err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
l := admin_order.NewAdminGetOrderSourceStatisticsLogic(r.Context(), svcCtx)
resp, err := l.AdminGetOrderSourceStatistics(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@@ -0,0 +1,29 @@
package admin_order
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/main/api/internal/logic/admin_order"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
)
func AdminGetOrderStatisticsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AdminGetOrderStatisticsReq
if err := httpx.Parse(r, &req); err != nil {
result.ParamErrorResult(r, w, err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
l := admin_order.NewAdminGetOrderStatisticsLogic(r.Context(), svcCtx)
resp, err := l.AdminGetOrderStatistics(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@@ -0,0 +1,29 @@
package admin_order
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/main/api/internal/logic/admin_order"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
)
func AdminGetRefundStatisticsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AdminGetRefundStatisticsReq
if err := httpx.Parse(r, &req); err != nil {
result.ParamErrorResult(r, w, err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
l := admin_order.NewAdminGetRefundStatisticsLogic(r.Context(), svcCtx)
resp, err := l.AdminGetRefundStatistics(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@@ -0,0 +1,30 @@
package admin_order
import (
"net/http"
"tydata-server/app/main/api/internal/logic/admin_order"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func AdminGetRevenueStatisticsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AdminGetRevenueStatisticsReq
if err := httpx.Parse(r, &req); err != nil {
result.ParamErrorResult(r, w, err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
l := admin_order.NewAdminGetRevenueStatisticsLogic(r.Context(), svcCtx)
resp, err := l.AdminGetRevenueStatistics(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@@ -52,6 +52,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/agent-link/list",
Handler: admin_agent.AdminGetAgentLinkListHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/agent-link/product-statistics",
Handler: admin_agent.AdminGetAgentLinkProductStatisticsHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/agent-membership-config/list",
@@ -67,6 +72,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/agent-membership-recharge-order/list",
Handler: admin_agent.AdminGetAgentMembershipRechargeOrderListHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/agent-order/statistics",
Handler: admin_agent.AdminGetAgentOrderStatisticsHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/agent-platform-deduction/list",
@@ -97,11 +107,21 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/agent-withdrawal/list",
Handler: admin_agent.AdminGetAgentWithdrawalListHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/agent-withdrawal/statistics",
Handler: admin_agent.AdminGetWithdrawalStatisticsHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/list",
Handler: admin_agent.AdminGetAgentListHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/statistics",
Handler: admin_agent.AdminGetAgentStatisticsHandler(serverCtx),
},
}...,
),
rest.WithPrefix("/api/v1/admin/agent"),
@@ -309,6 +329,12 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/list",
Handler: admin_order.AdminGetOrderListHandler(serverCtx),
},
{
// 获取退款统计数据
Method: http.MethodGet,
Path: "/refund-statistics",
Handler: admin_order.AdminGetRefundStatisticsHandler(serverCtx),
},
{
// 订单退款
Method: http.MethodPost,
@@ -321,6 +347,24 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/retry-agent-process/:id",
Handler: admin_order.AdminRetryAgentProcessHandler(serverCtx),
},
{
// 获取收入和利润统计数据
Method: http.MethodGet,
Path: "/revenue-statistics",
Handler: admin_order.AdminGetRevenueStatisticsHandler(serverCtx),
},
{
// 获取订单来源统计数据
Method: http.MethodGet,
Path: "/source-statistics",
Handler: admin_order.AdminGetOrderSourceStatisticsHandler(serverCtx),
},
{
// 获取订单统计数据
Method: http.MethodGet,
Path: "/statistics",
Handler: admin_order.AdminGetOrderStatisticsHandler(serverCtx),
},
{
// 更新订单
Method: http.MethodPut,

View File

@@ -0,0 +1,100 @@
package admin_agent
import (
"context"
"fmt"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"github.com/Masterminds/squirrel"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetAgentLinkProductStatisticsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetAgentLinkProductStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetAgentLinkProductStatisticsLogic {
return &AdminGetAgentLinkProductStatisticsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetAgentLinkProductStatisticsLogic) AdminGetAgentLinkProductStatistics(req *types.AdminGetAgentLinkProductStatisticsReq) (resp *types.AdminGetAgentLinkProductStatisticsResp, err error) {
// 构建查询
query := squirrel.Select(
"p.product_name",
"COUNT(al.id) as link_count",
).
From("agent_link al").
Join("product p ON al.product_id = p.id").
Where(squirrel.Eq{"al.del_state": 0}).
Where(squirrel.Eq{"p.del_state": 0}).
GroupBy("p.product_name").
OrderBy("link_count DESC")
// 执行查询
sql, args, err := query.ToSql()
if err != nil {
return nil, err
}
type Result struct {
ProductName string `db:"product_name"`
LinkCount int64 `db:"link_count"`
}
var results []Result
// 使用模型的方法执行查询
// 通过反射获取底层的QueryRowsNoCacheCtx方法避免直接类型断言
if agentLinkModel, ok := l.svcCtx.AgentLinkModel.(interface {
QueryRowsNoCacheCtx(ctx context.Context, v interface{}, query string, args ...interface{}) error
}); ok {
err = agentLinkModel.QueryRowsNoCacheCtx(l.ctx, &results, sql, args...)
} else {
// 如果无法使用模型的方法,则使用原始的连接方式(安全地获取连接)
if cachedConn, ok := l.svcCtx.AgentLinkModel.(interface {
GetConn() interface{}
}); ok {
conn := cachedConn.GetConn()
if sqlxConn, ok := conn.(interface {
QueryRowsCtx(ctx context.Context, v interface{}, query string, args ...interface{}) error
}); ok {
err = sqlxConn.QueryRowsCtx(l.ctx, &results, sql, args...)
} else {
return nil, fmt.Errorf("无法获取数据库连接")
}
} else {
return nil, fmt.Errorf("无法获取数据库连接")
}
}
if err != nil {
return nil, err
}
// 处理空结果
if len(results) == 0 {
return &types.AdminGetAgentLinkProductStatisticsResp{
Items: []types.AgentLinkProductStatisticsItem{},
}, nil
}
// 转换为返回结果
items := make([]types.AgentLinkProductStatisticsItem, 0, len(results))
for _, r := range results {
items = append(items, types.AgentLinkProductStatisticsItem{
ProductName: r.ProductName,
LinkCount: r.LinkCount,
})
}
return &types.AdminGetAgentLinkProductStatisticsResp{
Items: items,
}, nil
}

View File

@@ -0,0 +1,60 @@
package admin_agent
import (
"context"
"fmt"
"time"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetAgentOrderStatisticsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetAgentOrderStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetAgentOrderStatisticsLogic {
return &AdminGetAgentOrderStatisticsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetAgentOrderStatisticsLogic) AdminGetAgentOrderStatistics(req *types.AdminGetAgentOrderStatisticsReq) (resp *types.AdminGetAgentOrderStatisticsResp, err error) {
// 获取今日的开始和结束时间
today := time.Now()
startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
endOfDay := startOfDay.Add(24 * time.Hour)
// 构建查询条件
builder := l.svcCtx.AgentOrderModel.SelectBuilder()
// 查询总代理订单数
totalBuilder := builder
totalAgentOrderCount, err := l.svcCtx.AgentOrderModel.FindCount(l.ctx, totalBuilder, "id")
if err != nil {
logx.Errorf("查询总代理订单数失败: %v", err)
return nil, fmt.Errorf("查询总代理订单数失败: %w", err)
}
// 查询今日代理订单数
todayBuilder := builder.Where("create_time >= ? AND create_time < ?", startOfDay, endOfDay)
todayAgentOrderCount, err := l.svcCtx.AgentOrderModel.FindCount(l.ctx, todayBuilder, "id")
if err != nil {
logx.Errorf("查询今日代理订单数失败: %v", err)
return nil, fmt.Errorf("查询今日代理订单数失败: %w", err)
}
// 构建响应
resp = &types.AdminGetAgentOrderStatisticsResp{
TotalAgentOrderCount: totalAgentOrderCount,
TodayAgentOrderCount: todayAgentOrderCount,
}
return resp, nil
}

View File

@@ -0,0 +1,56 @@
package admin_agent
import (
"context"
"fmt"
"time"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetAgentStatisticsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetAgentStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetAgentStatisticsLogic {
return &AdminGetAgentStatisticsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetAgentStatisticsLogic) AdminGetAgentStatistics(req *types.AdminGetAgentStatisticsReq) (resp *types.AdminGetAgentStatisticsResp, err error) {
// 使用AgentModel的SelectBuilder和FindCount方法获取总代理数
totalBuilder := l.svcCtx.AgentModel.SelectBuilder()
totalAgentCount, err := l.svcCtx.AgentModel.FindCount(l.ctx, totalBuilder, "id")
if err != nil {
logx.Errorf("获取总代理数失败: %v", err)
return nil, fmt.Errorf("获取总代理数失败: %w", err)
}
// 获取今日新增代理数
todayBuilder := l.svcCtx.AgentModel.SelectBuilder()
today := time.Now()
startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
endOfDay := startOfDay.Add(24 * time.Hour)
todayBuilder = todayBuilder.Where("create_time >= ? AND create_time < ?", startOfDay, endOfDay)
todayAgentCount, err := l.svcCtx.AgentModel.FindCount(l.ctx, todayBuilder, "id")
if err != nil {
logx.Errorf("获取今日新增代理数失败: %v", err)
return nil, fmt.Errorf("获取今日新增代理数失败: %w", err)
}
resp = &types.AdminGetAgentStatisticsResp{
TotalAgentCount: totalAgentCount,
TodayAgentCount: todayAgentCount,
}
return resp, nil
}

View File

@@ -0,0 +1,76 @@
package admin_agent
import (
"context"
"fmt"
"time"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetWithdrawalStatisticsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetWithdrawalStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetWithdrawalStatisticsLogic {
return &AdminGetWithdrawalStatisticsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetWithdrawalStatisticsLogic) AdminGetWithdrawalStatistics(req *types.AdminGetWithdrawalStatisticsReq) (resp *types.AdminGetWithdrawalStatisticsResp, err error) {
// 获取今日的开始和结束时间
today := time.Now()
startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
endOfDay := startOfDay.Add(24 * time.Hour)
// 构建查询条件
builder := l.svcCtx.AgentWithdrawalModel.SelectBuilder()
// 查询总提现金额status=2表示成功
totalBuilder := builder.Where("status = ?", 2)
totalWithdrawalAmount, err := l.svcCtx.AgentWithdrawalModel.FindSum(l.ctx, totalBuilder, "amount")
if err != nil {
logx.Errorf("查询总提现金额失败: %v", err)
return nil, fmt.Errorf("查询总提现金额失败: %w", err)
}
// 查询今日提现金额status=2表示成功
todayBuilder := builder.Where("status = ? AND create_time >= ? AND create_time < ?", 2, startOfDay, endOfDay)
todayWithdrawalAmount, err := l.svcCtx.AgentWithdrawalModel.FindSum(l.ctx, todayBuilder, "amount")
if err != nil {
logx.Errorf("查询今日提现金额失败: %v", err)
return nil, fmt.Errorf("查询今日提现金额失败: %w", err)
}
// 查询总实际到账金额status=2表示成功
totalActualAmount, err := l.svcCtx.AgentWithdrawalModel.FindSum(l.ctx, totalBuilder, "actual_amount")
if err != nil {
logx.Errorf("查询总实际到账金额失败: %v", err)
return nil, fmt.Errorf("查询总实际到账金额失败: %w", err)
}
// 查询总扣税金额status=2表示成功
totalTaxAmount, err := l.svcCtx.AgentWithdrawalModel.FindSum(l.ctx, totalBuilder, "tax_amount")
if err != nil {
logx.Errorf("查询总扣税金额失败: %v", err)
return nil, fmt.Errorf("查询总扣税金额失败: %w", err)
}
// 构建响应
resp = &types.AdminGetWithdrawalStatisticsResp{
TotalWithdrawalAmount: totalWithdrawalAmount,
TodayWithdrawalAmount: todayWithdrawalAmount,
TotalActualAmount: totalActualAmount,
TotalTaxAmount: totalTaxAmount,
}
return resp, nil
}

View File

@@ -29,8 +29,9 @@ func NewAdminCreateFeatureLogic(ctx context.Context, svcCtx *svc.ServiceContext)
func (l *AdminCreateFeatureLogic) AdminCreateFeature(req *types.AdminCreateFeatureReq) (resp *types.AdminCreateFeatureResp, err error) {
// 1. 数据转换
data := &model.Feature{
ApiId: req.ApiId,
Name: req.Name,
ApiId: req.ApiId,
Name: req.Name,
CostPrice: req.CostPrice,
}
// 2. 数据库操作

View File

@@ -38,6 +38,7 @@ func (l *AdminGetFeatureDetailLogic) AdminGetFeatureDetail(req *types.AdminGetFe
Id: record.Id,
ApiId: record.ApiId,
Name: record.Name,
CostPrice: record.CostPrice,
CreateTime: record.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: record.UpdateTime.Format("2006-01-02 15:04:05"),
}

View File

@@ -54,6 +54,7 @@ func (l *AdminGetFeatureListLogic) AdminGetFeatureList(req *types.AdminGetFeatur
Name: item.Name,
CreateTime: item.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: item.UpdateTime.Format("2006-01-02 15:04:05"),
CostPrice: item.CostPrice,
}
items = append(items, listItem)
}

View File

@@ -46,6 +46,9 @@ func (l *AdminUpdateFeatureLogic) AdminUpdateFeature(req *types.AdminUpdateFeatu
if req.Name != nil && *req.Name != "" {
record.Name = *req.Name
}
if req.CostPrice != nil {
record.CostPrice = *req.CostPrice
}
// 4. 执行更新操作
err = l.svcCtx.FeatureModel.UpdateWithVersion(l.ctx, nil, record)

View File

@@ -115,6 +115,7 @@ func (l *AdminGetOrderDetailLogic) AdminGetOrderDetail(req *types.AdminGetOrderD
PaymentPlatform: order.PaymentPlatform,
PaymentScene: order.PaymentScene,
Amount: order.Amount,
SalesCost: order.SalesCost,
Status: order.Status,
CreateTime: order.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: order.UpdateTime.Format("2006-01-02 15:04:05"),

View File

@@ -264,6 +264,7 @@ func (l *AdminGetOrderListLogic) AdminGetOrderList(req *types.AdminGetOrderListR
PaymentPlatform: order.PaymentPlatform,
PaymentScene: order.PaymentScene,
Amount: order.Amount,
SalesCost: order.SalesCost,
Status: order.Status,
CreateTime: order.CreateTime.Format("2006-01-02 15:04:05"),
QueryState: queryStateMap[order.Id],

View File

@@ -0,0 +1,87 @@
package admin_order
import (
"context"
"fmt"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetOrderSourceStatisticsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetOrderSourceStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetOrderSourceStatisticsLogic {
return &AdminGetOrderSourceStatisticsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetOrderSourceStatisticsLogic) AdminGetOrderSourceStatistics(req *types.AdminGetOrderSourceStatisticsReq) (resp *types.AdminGetOrderSourceStatisticsResp, err error) {
// 查询所有有产品ID的订单
builder := l.svcCtx.OrderModel.SelectBuilder()
builder = builder.Where("product_id IS NOT NULL")
// 获取所有符合条件的订单
orders, err := l.svcCtx.OrderModel.FindAll(l.ctx, builder, "id DESC")
if err != nil {
logx.Errorf("查询订单列表失败: %v", err)
return nil, fmt.Errorf("查询订单列表失败: %w", err)
}
logx.Infof("获取到订单数量: %d", len(orders))
// 统计每个产品的订单数量
productCountMap := make(map[int64]int64)
for _, order := range orders {
productCountMap[order.ProductId]++
}
// 构建返回结果
items := make([]types.OrderSourceStatisticsItem, 0, len(productCountMap))
for productId, count := range productCountMap {
// 获取产品信息
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, productId)
if err != nil {
logx.Errorf("查询产品信息失败 productId=%d, err=%v", productId, err)
// 如果查询失败,使用默认值
items = append(items, types.OrderSourceStatisticsItem{
ProductName: "未知产品",
OrderCount: count,
})
continue
}
items = append(items, types.OrderSourceStatisticsItem{
ProductName: product.ProductName,
OrderCount: count,
})
}
// 按订单数量降序排序
for i := 0; i < len(items)-1; i++ {
for j := i + 1; j < len(items); j++ {
if items[i].OrderCount < items[j].OrderCount {
items[i], items[j] = items[j], items[i]
}
}
}
logx.Infof("查询到订单来源统计数据: %d 个产品,订单总数: %d", len(items), len(orders))
return &types.AdminGetOrderSourceStatisticsResp{
Items: items,
}, nil
}
// 定义结果结构体
type OrderSourceResult struct {
ProductName string `db:"product_name"`
OrderCount int64 `db:"order_count"`
}

View File

@@ -0,0 +1,106 @@
package admin_order
import (
"context"
"fmt"
"time"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetOrderStatisticsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetOrderStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetOrderStatisticsLogic {
return &AdminGetOrderStatisticsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetOrderStatisticsLogic) AdminGetOrderStatistics(req *types.AdminGetOrderStatisticsReq) (resp *types.AdminGetOrderStatisticsResp, err error) {
// 获取当前时间
now := time.Now()
var startTime, endTime time.Time
// 根据时间维度设置时间范围和格式
switch req.Dimension {
case "day":
// 日当月1号到今天
startTime = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
endTime = time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 999999999, now.Location())
case "month":
// 月今年1月到当月
startTime = time.Date(now.Year(), 1, 1, 0, 0, 0, 0, now.Location())
endTime = time.Date(now.Year(), now.Month(), 1, 23, 59, 59, 999999999, now.Location()).AddDate(0, 1, -1)
case "year":
// 年过去5年
startTime = time.Date(now.Year()-5, 1, 1, 0, 0, 0, 0, now.Location())
endTime = time.Date(now.Year(), 12, 31, 23, 59, 59, 999999999, now.Location())
case "all":
// 全部:所有时间,但按日统计
startTime = time.Date(2020, 1, 1, 0, 0, 0, 0, now.Location()) // 假设从2020年开始
endTime = now
default:
// 默认为日
startTime = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
endTime = time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 999999999, now.Location())
}
// 构建查询条件
builder := l.svcCtx.OrderModel.SelectBuilder().
Where("create_time >= ? AND create_time <= ?", startTime, endTime).
Where("status = ?", "paid") // 只统计已支付的订单
// 查询所有符合条件的订单
orders, err := l.svcCtx.OrderModel.FindAll(l.ctx, builder, "create_time ASC")
if err != nil {
logx.Errorf("查询订单统计数据失败: %v", err)
return nil, fmt.Errorf("查询订单统计数据失败: %w", err)
}
// 按日期分组统计
dateMap := make(map[string]*types.OrderStatisticsItem)
for _, order := range orders {
var dateKey string
if req.Dimension == "year" {
dateKey = order.CreateTime.Format("2006")
} else if req.Dimension == "month" {
dateKey = order.CreateTime.Format("2006-01")
} else {
dateKey = order.CreateTime.Format("2006-01-02")
}
if item, exists := dateMap[dateKey]; exists {
item.Count++
item.Amount += order.Amount
} else {
dateMap[dateKey] = &types.OrderStatisticsItem{
Date: dateKey,
Count: 1,
Amount: order.Amount,
}
}
}
// 转换为切片
items := make([]types.OrderStatisticsItem, 0, len(dateMap))
for date := range dateMap {
items = append(items, *dateMap[date])
}
// 构建响应
resp = &types.AdminGetOrderStatisticsResp{
Items: items,
}
return resp, nil
}

View File

@@ -0,0 +1,60 @@
package admin_order
import (
"context"
"fmt"
"time"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetRefundStatisticsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetRefundStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetRefundStatisticsLogic {
return &AdminGetRefundStatisticsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetRefundStatisticsLogic) AdminGetRefundStatistics(req *types.AdminGetRefundStatisticsReq) (resp *types.AdminGetRefundStatisticsResp, err error) {
// 获取今日的开始和结束时间
today := time.Now()
startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
endOfDay := startOfDay.Add(24 * time.Hour)
// 构建查询条件
builder := l.svcCtx.OrderModel.SelectBuilder()
// 查询总退款金额status=refunded表示已退款
totalBuilder := builder.Where("status = ?", "refunded")
totalRefundAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, totalBuilder, "amount")
if err != nil {
logx.Errorf("查询总退款金额失败: %v", err)
return nil, fmt.Errorf("查询总退款金额失败: %w", err)
}
// 查询今日退款金额status=refunded表示已退款且退款时间为今日
todayBuilder := builder.Where("status = ? AND refund_time >= ? AND refund_time < ?", "refunded", startOfDay, endOfDay)
todayRefundAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, todayBuilder, "amount")
if err != nil {
logx.Errorf("查询今日退款金额失败: %v", err)
return nil, fmt.Errorf("查询今日退款金额失败: %w", err)
}
// 构建响应
resp = &types.AdminGetRefundStatisticsResp{
TotalRefundAmount: totalRefundAmount,
TodayRefundAmount: todayRefundAmount,
}
return resp, nil
}

View File

@@ -0,0 +1,84 @@
package admin_order
import (
"context"
"fmt"
"time"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetRevenueStatisticsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetRevenueStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetRevenueStatisticsLogic {
return &AdminGetRevenueStatisticsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetRevenueStatisticsLogic) AdminGetRevenueStatistics(req *types.AdminGetRevenueStatisticsReq) (resp *types.AdminGetRevenueStatisticsResp, err error) {
// 获取今日的开始和结束时间
today := time.Now()
startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
endOfDay := startOfDay.Add(24 * time.Hour)
// 构建查询条件
builder := l.svcCtx.OrderModel.SelectBuilder()
// 查询总收入金额status=paid表示已支付
totalRevenueBuilder := builder.Where("status = ?", "paid")
totalRevenueAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, totalRevenueBuilder, "amount")
if err != nil {
logx.Errorf("查询总收入金额失败: %v", err)
return nil, fmt.Errorf("查询总收入金额失败: %w", err)
}
// 查询今日收入金额status=paid表示已支付且支付时间为今日
todayRevenueBuilder := builder.Where("status = ? AND pay_time >= ? AND pay_time < ?", "paid", startOfDay, endOfDay)
todayRevenueAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, todayRevenueBuilder, "amount")
if err != nil {
logx.Errorf("查询今日收入金额失败: %v", err)
return nil, fmt.Errorf("查询今日收入金额失败: %w", err)
}
// 查询总成本金额status=paid表示已支付
totalCostBuilder := builder.Where("status = ?", "paid")
totalCostAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, totalCostBuilder, "sales_cost")
if err != nil {
logx.Errorf("查询总成本金额失败: %v", err)
return nil, fmt.Errorf("查询总成本金额失败: %w", err)
}
// 查询今日成本金额status=paid表示已支付且支付时间为今日
todayCostBuilder := builder.Where("status = ? AND pay_time >= ? AND pay_time < ?", "paid", startOfDay, endOfDay)
todayCostAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, todayCostBuilder, "sales_cost")
if err != nil {
logx.Errorf("查询今日成本金额失败: %v", err)
return nil, fmt.Errorf("查询今日成本金额失败: %w", err)
}
// 计算总利润 = 总收入 - 总成本
totalProfitAmount := totalRevenueAmount - totalCostAmount
// 计算今日利润 = 今日收入 - 今日成本
todayProfitAmount := todayRevenueAmount - todayCostAmount
// 构建响应
resp = &types.AdminGetRevenueStatisticsResp{
TotalRevenueAmount: totalRevenueAmount,
TodayRevenueAmount: todayRevenueAmount,
TotalProfitAmount: totalProfitAmount,
TodayProfitAmount: todayProfitAmount,
}
return resp, nil
}

View File

@@ -2,11 +2,11 @@ package admin_product
import (
"context"
"sync"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/app/main/model"
"tydata-server/common/xerr"
"sync"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
@@ -146,6 +146,7 @@ func (l *AdminUpdateProductFeaturesLogic) AdminUpdateProductFeatures(req *types.
return updateErr
}
// 不自动更新产品成本价,保留用户手动设置的值
return nil
})
@@ -155,5 +156,7 @@ func (l *AdminUpdateProductFeaturesLogic) AdminUpdateProductFeatures(req *types.
}
// 5. 返回结果
return &types.AdminUpdateProductFeaturesResp{Success: true}, nil
return &types.AdminUpdateProductFeaturesResp{
Success: true,
}, nil
}

View File

@@ -2,10 +2,10 @@ package admin_product
import (
"context"
"database/sql"
"tydata-server/app/main/api/internal/svc"
"tydata-server/app/main/api/internal/types"
"tydata-server/common/xerr"
"database/sql"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"

View File

@@ -142,10 +142,44 @@ func (l *PaySuccessNotifyUserHandler) ProcessTask(ctx context.Context, t *asynq.
}
// 调用API请求服务
combinedResponse, err := l.svcCtx.ApiRequestService.ProcessRequests(decryptData, product.Id)
responseData, err := l.svcCtx.ApiRequestService.ProcessRequests(decryptData, product.Id)
if err != nil {
return l.handleError(ctx, err, order, query)
}
// 计算成功模块的总成本价
totalCostPrice := 0.0
if responseData != nil {
for _, item := range responseData {
if item.Success {
// 根据API ID查找功能模块
feature, err := l.svcCtx.FeatureModel.FindOneByApiId(ctx, item.ApiID)
if err != nil {
logx.Errorf("查找功能模块失败, API ID: %s, 错误: %v", item.ApiID, err)
continue
}
// 累加成本价
totalCostPrice += feature.CostPrice
}
}
}
// 更新订单的销售成本
order.SalesCost = totalCostPrice
updateOrderErr := l.svcCtx.OrderModel.UpdateWithVersion(ctx, nil, order)
if updateOrderErr != nil {
logx.Errorf("更新订单销售成本失败, 订单ID: %d, 错误: %v", order.Id, updateOrderErr)
// 注意:这里不返回错误,因为订单销售成本更新失败不应影响整个查询流程
} else {
logx.Infof("成功更新订单销售成本, 订单ID: %d, 总成本价: %f", order.Id, totalCostPrice)
}
// 对返回的类型进行二进制转换
combinedResponse, marshalErr := json.Marshal(responseData)
if marshalErr != nil {
err = fmt.Errorf("响应数据转 JSON 失败: %v", marshalErr)
return l.handleError(ctx, err, order, query)
}
// 加密返回响应
encryptData, aesEncryptErr := crypto.AesEncrypt(combinedResponse, key)
if aesEncryptErr != nil {

View File

@@ -80,13 +80,13 @@ func (l *AgentService) AgentProcess(ctx context.Context, order *model.Order) err
return findAgentProductConfigModelErr
}
// 平台底价成本
PlatformCostAmount, platformCostErr := l.PlatformCost(transCtx, agentID, agentProductConfigModel, session)
PlatformCostAmount, platformCostErr := l.PlatformCost(transCtx, agentID, order.Id, agentProductConfigModel, session)
if platformCostErr != nil {
return platformCostErr
}
// 平台提价成本
PlatformPricingAmount, platformPricingErr := l.PlatformPricing(transCtx, agentID, order.Amount, agentProductConfigModel, session)
PlatformPricingAmount, platformPricingErr := l.PlatformPricing(transCtx, agentID, order.Id, order.Amount, agentProductConfigModel, session)
if platformPricingErr != nil {
return platformPricingErr
}
@@ -227,10 +227,11 @@ func (l *AgentService) AncestorCommission(ctx context.Context, descendantId int6
}
// PlatformCost 平台底价成本
func (l *AgentService) PlatformCost(ctx context.Context, agentID int64, agentProductConfigModel *model.AgentProductConfig, session sqlx.Session) (float64, error) {
func (l *AgentService) PlatformCost(ctx context.Context, agentID int64, orderID int64, agentProductConfigModel *model.AgentProductConfig, session sqlx.Session) (float64, error) {
costAgentPlatformDeductionModel := model.AgentPlatformDeduction{
AgentId: agentID,
OrderId: orderID,
Amount: agentProductConfigModel.CostPrice,
Type: model.AgentDeductionTypeCost,
}
@@ -243,7 +244,7 @@ func (l *AgentService) PlatformCost(ctx context.Context, agentID int64, agentPro
}
// PlatformPricing 平台提价成本
func (l *AgentService) PlatformPricing(ctx context.Context, agentID int64, pricing float64, agentProductConfigModel *model.AgentProductConfig, session sqlx.Session) (float64, error) {
func (l *AgentService) PlatformPricing(ctx context.Context, agentID int64, orderID int64, pricing float64, agentProductConfigModel *model.AgentProductConfig, session sqlx.Session) (float64, error) {
// 2. 计算平台提价成本
if pricing > agentProductConfigModel.PricingStandard {
// 超出部分
@@ -254,6 +255,7 @@ func (l *AgentService) PlatformPricing(ctx context.Context, agentID int64, prici
pricingAgentPlatformDeductionModel := model.AgentPlatformDeduction{
AgentId: agentID,
OrderId: orderID,
Amount: overpricingCost,
Type: model.AgentDeductionTypePricing,
}
@@ -384,7 +386,7 @@ func (l *AgentService) GiveUpgradeReward(ctx context.Context, agentID int64, old
// 获取各等级的奖励金额
var vipRewardAmount float64
var svipRewardAmount float64
if agentMembershipConfigModel.LowerConvertVipReward.Valid {
vipRewardAmount = agentMembershipConfigModel.LowerConvertVipReward.Float64
}
@@ -500,7 +502,7 @@ func (l *AgentService) GiveWithdrawReward(ctx context.Context, agentID int64, wi
return nil
}
rewardAmount := withdrawAmount * rewardRatio
if rewardAmount > 0 {
// 创建奖励记录
agentRewards := model.AgentRewards{

View File

@@ -58,7 +58,7 @@ type APIResponseData struct {
}
// ProcessRequests 处理请求
func (a *ApiRequestService) ProcessRequests(params []byte, productID int64) ([]byte, error) {
func (a *ApiRequestService) ProcessRequests(params []byte, productID int64) ([]APIResponseData, error) {
var ctx, cancel = context.WithCancel(context.Background())
defer cancel()
build := a.productFeatureModel.SelectBuilder().Where(squirrel.Eq{
@@ -166,12 +166,7 @@ func (a *ApiRequestService) ProcessRequests(params []byte, productID int64) ([]b
return nil, fmt.Errorf("请求失败次数超过 %d 次: %v", errorLimit, allErrors)
}
combinedResponse, err := json.Marshal(responseData)
if err != nil {
return nil, fmt.Errorf("响应数据转 JSON 失败: %v", err)
}
return combinedResponse, nil
return responseData, nil
}
// ------------------------------------请求处理器--------------------------
@@ -1419,6 +1414,7 @@ func (a *ApiRequestService) ProcessIVYZ7F3ARequest(params []byte) ([]byte, error
// 直接返回解密后的数据而不是再次进行JSON编码
return convertTianyuanResponse(resp)
}
// ProcessIVYZ3P9MRequest 学历实时查询
func (a *ApiRequestService) ProcessIVYZ3P9MRequest(params []byte) ([]byte, error) {
idCard := gjson.GetBytes(params, "id_card")

View File

@@ -21,9 +21,9 @@ type ServiceContext struct {
Redis *redis.Redis
// 中间件
AuthInterceptor rest.Middleware
UserAuthInterceptor rest.Middleware
AdminAuthInterceptor rest.Middleware
AuthInterceptor rest.Middleware
UserAuthInterceptor rest.Middleware
AdminAuthInterceptor rest.Middleware
// 用户相关模型
UserModel model.UserModel
@@ -80,8 +80,8 @@ type ServiceContext struct {
AdminPromotionOrderModel model.AdminPromotionOrderModel
// 其他模型
ExampleModel model.ExampleModel
GlobalNotificationsModel model.GlobalNotificationsModel
ExampleModel model.ExampleModel
GlobalNotificationsModel model.GlobalNotificationsModel
AuthorizationDocumentModel model.AuthorizationDocumentModel
// 服务
@@ -98,7 +98,6 @@ type ServiceContext struct {
AdminPromotionLinkStatsService *service.AdminPromotionLinkStatsService
ImageService *service.ImageService
AuthorizationService *service.AuthorizationService
}
// NewServiceContext 创建服务上下文
@@ -173,7 +172,6 @@ func NewServiceContext(c config.Config) *ServiceContext {
globalNotificationsModel := model.NewGlobalNotificationsModel(db, cacheConf)
authorizationDocumentModel := model.NewAuthorizationDocumentModel(db, cacheConf)
// ============================== 第三方服务初始化 ==============================
tianyuanapi, err := tianyuanapi.NewClient(tianyuanapi.Config{
AccessID: c.Tianyuanapi.AccessID,
@@ -220,9 +218,9 @@ func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
Redis: redisClient,
AuthInterceptor: middleware.NewAuthInterceptorMiddleware(c).Handle,
UserAuthInterceptor: middleware.NewUserAuthInterceptorMiddleware().Handle,
AdminAuthInterceptor: middleware.NewAdminAuthInterceptorMiddleware(c,
AuthInterceptor: middleware.NewAuthInterceptorMiddleware(c).Handle,
UserAuthInterceptor: middleware.NewUserAuthInterceptorMiddleware().Handle,
AdminAuthInterceptor: middleware.NewAdminAuthInterceptorMiddleware(c,
adminUserModel, adminUserRoleModel, adminRoleModel, adminApiModel, adminRoleApiModel).Handle,
// 用户相关模型
@@ -280,8 +278,8 @@ func NewServiceContext(c config.Config) *ServiceContext {
AdminPromotionOrderModel: adminPromotionOrderModel,
// 其他模型
ExampleModel: exampleModel,
GlobalNotificationsModel: globalNotificationsModel,
ExampleModel: exampleModel,
GlobalNotificationsModel: globalNotificationsModel,
AuthorizationDocumentModel: authorizationDocumentModel,
// 服务
@@ -298,7 +296,6 @@ func NewServiceContext(c config.Config) *ServiceContext {
AdminPromotionLinkStatsService: adminPromotionLinkStatsService,
ImageService: imageService,
AuthorizationService: authorizationService,
}
}

View File

@@ -68,8 +68,9 @@ type AdminCreateApiResp struct {
}
type AdminCreateFeatureReq struct {
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CostPrice float64 `json:"cost_price"` // 成本价
}
type AdminCreateFeatureResp struct {
@@ -238,6 +239,13 @@ type AdminGetAgentLinkListResp struct {
Items []AgentLinkListItem `json:"items"` // 列表数据
}
type AdminGetAgentLinkProductStatisticsReq struct {
}
type AdminGetAgentLinkProductStatisticsResp struct {
Items []AgentLinkProductStatisticsItem `json:"items"` // 列表数据
}
type AdminGetAgentListReq struct {
Page int64 `form:"page"` // 页码
PageSize int64 `form:"pageSize"` // 每页数量
@@ -278,6 +286,14 @@ type AdminGetAgentMembershipRechargeOrderListResp struct {
Items []AgentMembershipRechargeOrderListItem `json:"items"` // 列表数据
}
type AdminGetAgentOrderStatisticsReq struct {
}
type AdminGetAgentOrderStatisticsResp struct {
TotalAgentOrderCount int64 `json:"total_agent_order_count"` // 总代理订单数
TodayAgentOrderCount int64 `json:"today_agent_order_count"` // 今日代理订单数
}
type AdminGetAgentPlatformDeductionListReq struct {
Page int64 `form:"page"` // 页码
PageSize int64 `form:"pageSize"` // 每页数量
@@ -316,6 +332,14 @@ type AdminGetAgentRewardListResp struct {
Items []AgentRewardListItem `json:"items"` // 列表数据
}
type AdminGetAgentStatisticsReq struct {
}
type AdminGetAgentStatisticsResp struct {
TotalAgentCount int64 `json:"total_agent_count"` // 总代理数
TodayAgentCount int64 `json:"today_agent_count"` // 今日新增代理数
}
type AdminGetAgentWithdrawalListReq struct {
Page int64 `form:"page"` // 页码
PageSize int64 `form:"pageSize"` // 每页数量
@@ -363,11 +387,12 @@ type AdminGetFeatureDetailReq struct {
}
type AdminGetFeatureDetailResp struct {
Id int64 `json:"id"` // 功能ID
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CreateTime string `json:"create_time"` // 创建时间
UpdateTime string `json:"update_time"` // 更新时间
Id int64 `json:"id"` // 功能ID
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CostPrice float64 `json:"cost_price"` // 成本价
CreateTime string `json:"create_time"` // 创建时间
UpdateTime string `json:"update_time"` // 更新时间
}
type AdminGetFeatureExampleReq struct {
@@ -440,6 +465,7 @@ type AdminGetOrderDetailResp struct {
PaymentPlatform string `json:"payment_platform"` // 支付方式
PaymentScene string `json:"payment_scene"` // 支付平台
Amount float64 `json:"amount"` // 金额
SalesCost float64 `json:"sales_cost"` // 成本价
Status string `json:"status"` // 支付状态pending-待支付paid-已支付refunded-已退款closed-已关闭failed-支付失败
QueryState string `json:"query_state"` // 查询状态pending-待查询success-查询成功failed-查询失败 processing-查询中
CreateTime string `json:"create_time"` // 创建时间
@@ -468,6 +494,7 @@ type AdminGetOrderListReq struct {
PayTimeEnd string `form:"pay_time_end,optional"` // 支付时间结束
RefundTimeStart string `form:"refund_time_start,optional"` // 退款时间开始
RefundTimeEnd string `form:"refund_time_end,optional"` // 退款时间结束
SalesCost float64 `form:"sales_cost,optional"` // 成本价
}
type AdminGetOrderListResp struct {
@@ -475,6 +502,21 @@ type AdminGetOrderListResp struct {
Items []OrderListItem `json:"items"` // 列表
}
type AdminGetOrderSourceStatisticsReq struct {
}
type AdminGetOrderSourceStatisticsResp struct {
Items []OrderSourceStatisticsItem `json:"items"` // 订单来源统计列表
}
type AdminGetOrderStatisticsReq struct {
Dimension string `form:"dimension"` // 时间维度day-日(当月1号到今天)month-月(今年1月到当月)year-年(过去5年)all-全部(按日统计)
}
type AdminGetOrderStatisticsResp struct {
Items []OrderStatisticsItem `json:"items"` // 订单统计列表
}
type AdminGetPlatformUserDetailReq struct {
Id int64 `path:"id"` // 用户ID
}
@@ -599,6 +641,24 @@ type AdminGetQueryDetailByOrderIdResp struct {
QueryState string `json:"query_state"` // 查询状态
}
type AdminGetRefundStatisticsReq struct {
}
type AdminGetRefundStatisticsResp struct {
TotalRefundAmount float64 `json:"total_refund_amount"` // 总退款金额
TodayRefundAmount float64 `json:"today_refund_amount"` // 今日退款金额
}
type AdminGetRevenueStatisticsReq struct {
}
type AdminGetRevenueStatisticsResp struct {
TotalRevenueAmount float64 `json:"total_revenue_amount"` // 总收入金额
TodayRevenueAmount float64 `json:"today_revenue_amount"` // 今日收入金额
TotalProfitAmount float64 `json:"total_profit_amount"` // 总利润金额
TodayProfitAmount float64 `json:"today_profit_amount"` // 今日利润金额
}
type AdminGetRoleApiListReq struct {
RoleId int64 `path:"role_id"`
}
@@ -634,6 +694,16 @@ type AdminGetUserListResp struct {
Items []AdminUserListItem `json:"items"` // 列表
}
type AdminGetWithdrawalStatisticsReq struct {
}
type AdminGetWithdrawalStatisticsResp struct {
TotalWithdrawalAmount float64 `json:"total_withdrawal_amount"` // 总提现金额
TodayWithdrawalAmount float64 `json:"today_withdrawal_amount"` // 今日提现金额
TotalActualAmount float64 `json:"total_actual_amount"` // 总实际到账金额
TotalTaxAmount float64 `json:"total_tax_amount"` // 总扣税金额
}
type AdminLoginReq struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
@@ -764,9 +834,10 @@ type AdminUpdateApiResp struct {
}
type AdminUpdateFeatureReq struct {
Id int64 `path:"id"` // 功能ID
ApiId *string `json:"api_id,optional"` // API标识
Name *string `json:"name,optional"` // 描述
Id int64 `path:"id"` // 功能ID
ApiId *string `json:"api_id,optional"` // API标识
Name *string `json:"name,optional"` // 描述
CostPrice *float64 `json:"cost_price,optional"` // 成本价
}
type AdminUpdateFeatureResp struct {
@@ -967,6 +1038,11 @@ type AgentLinkListItem struct {
CreateTime string `json:"create_time"` // 创建时间
}
type AgentLinkProductStatisticsItem struct {
ProductName string `json:"product_name"` // 产品名称
LinkCount int64 `json:"link_count"` // 推广链接数量
}
type AgentListItem struct {
Id int64 `json:"id"` // 主键
UserId int64 `json:"user_id"` // 用户ID
@@ -1275,11 +1351,12 @@ type Feature struct {
}
type FeatureListItem struct {
Id int64 `json:"id"` // 功能ID
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CreateTime string `json:"create_time"` // 创建时间
UpdateTime string `json:"update_time"` // 更新时间
Id int64 `json:"id"` // 功能ID
ApiId string `json:"api_id"` // API标识
Name string `json:"name"` // 描述
CostPrice float64 `json:"cost_price"` // 成本价
CreateTime string `json:"create_time"` // 创建时间
UpdateTime string `json:"update_time"` // 更新时间
}
type GetAgentPromotionQrcodeReq struct {
@@ -1638,6 +1715,7 @@ type OrderListItem struct {
PaymentPlatform string `json:"payment_platform"` // 支付方式
PaymentScene string `json:"payment_scene"` // 支付平台
Amount float64 `json:"amount"` // 金额
SalesCost float64 `json:"sales_cost"` // 成本价
Status string `json:"status"` // 支付状态pending-待支付paid-已支付refunded-已退款closed-已关闭failed-支付失败
QueryState string `json:"query_state"` // 查询状态pending-待查询success-查询成功failed-查询失败 processing-查询中
CreateTime string `json:"create_time"` // 创建时间
@@ -1648,6 +1726,17 @@ type OrderListItem struct {
AgentProcessStatus string `json:"agent_process_status"` // 代理事务处理状态not_agent-非代理订单success-处理成功failed-处理失败pending-待处理
}
type OrderSourceStatisticsItem struct {
ProductName string `json:"product_name"` // 产品名称
OrderCount int64 `json:"order_count"` // 订单数量
}
type OrderStatisticsItem struct {
Date string `json:"date"` // 日期
Count int64 `json:"count"` // 订单数量
Amount float64 `json:"amount"` // 订单金额
}
type PaymentCheckReq struct {
OrderNo string `json:"order_no" validate:"required"`
}

View File

@@ -27,9 +27,9 @@ var (
agentRowsExpectAutoSet = strings.Join(stringx.Remove(agentFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
agentRowsWithPlaceHolder = strings.Join(stringx.Remove(agentFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
cacheHmAgentIdPrefix = "cache:tydata:agent:id:"
cacheHmAgentMobilePrefix = "cache:tydata:agent:mobile:"
cacheHmAgentUserIdPrefix = "cache:tydata:agent:userId:"
cacheTydataAgentIdPrefix = "cache:tydata:agent:id:"
cacheTydataAgentMobilePrefix = "cache:tydata:agent:mobile:"
cacheTydataAgentUserIdPrefix = "cache:tydata:agent:userId:"
)
type (
@@ -83,22 +83,22 @@ func newAgentModel(conn sqlx.SqlConn, c cache.CacheConf) *defaultAgentModel {
func (m *defaultAgentModel) Insert(ctx context.Context, session sqlx.Session, data *Agent) (sql.Result, error) {
data.DelState = globalkey.DelStateNo
hmAgentIdKey := fmt.Sprintf("%s%v", cacheHmAgentIdPrefix, data.Id)
hmAgentMobileKey := fmt.Sprintf("%s%v", cacheHmAgentMobilePrefix, data.Mobile)
hmAgentUserIdKey := fmt.Sprintf("%s%v", cacheHmAgentUserIdPrefix, data.UserId)
tydataAgentIdKey := fmt.Sprintf("%s%v", cacheTydataAgentIdPrefix, data.Id)
tydataAgentMobileKey := fmt.Sprintf("%s%v", cacheTydataAgentMobilePrefix, data.Mobile)
tydataAgentUserIdKey := fmt.Sprintf("%s%v", cacheTydataAgentUserIdPrefix, data.UserId)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, agentRowsExpectAutoSet)
if session != nil {
return session.ExecCtx(ctx, query, data.UserId, data.LevelName, data.Region, data.Mobile, data.WechatId, data.MembershipExpiryTime, data.DeleteTime, data.DelState, data.Version)
}
return conn.ExecCtx(ctx, query, data.UserId, data.LevelName, data.Region, data.Mobile, data.WechatId, data.MembershipExpiryTime, data.DeleteTime, data.DelState, data.Version)
}, hmAgentIdKey, hmAgentMobileKey, hmAgentUserIdKey)
}, tydataAgentIdKey, tydataAgentMobileKey, tydataAgentUserIdKey)
}
func (m *defaultAgentModel) FindOne(ctx context.Context, id int64) (*Agent, error) {
hmAgentIdKey := fmt.Sprintf("%s%v", cacheHmAgentIdPrefix, id)
tydataAgentIdKey := fmt.Sprintf("%s%v", cacheTydataAgentIdPrefix, id)
var resp Agent
err := m.QueryRowCtx(ctx, &resp, hmAgentIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
err := m.QueryRowCtx(ctx, &resp, tydataAgentIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", agentRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id, globalkey.DelStateNo)
})
@@ -113,9 +113,9 @@ func (m *defaultAgentModel) FindOne(ctx context.Context, id int64) (*Agent, erro
}
func (m *defaultAgentModel) FindOneByMobile(ctx context.Context, mobile string) (*Agent, error) {
hmAgentMobileKey := fmt.Sprintf("%s%v", cacheHmAgentMobilePrefix, mobile)
tydataAgentMobileKey := fmt.Sprintf("%s%v", cacheTydataAgentMobilePrefix, mobile)
var resp Agent
err := m.QueryRowIndexCtx(ctx, &resp, hmAgentMobileKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
err := m.QueryRowIndexCtx(ctx, &resp, tydataAgentMobileKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
query := fmt.Sprintf("select %s from %s where `mobile` = ? and del_state = ? limit 1", agentRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, mobile, globalkey.DelStateNo); err != nil {
return nil, err
@@ -133,9 +133,9 @@ func (m *defaultAgentModel) FindOneByMobile(ctx context.Context, mobile string)
}
func (m *defaultAgentModel) FindOneByUserId(ctx context.Context, userId int64) (*Agent, error) {
hmAgentUserIdKey := fmt.Sprintf("%s%v", cacheHmAgentUserIdPrefix, userId)
tydataAgentUserIdKey := fmt.Sprintf("%s%v", cacheTydataAgentUserIdPrefix, userId)
var resp Agent
err := m.QueryRowIndexCtx(ctx, &resp, hmAgentUserIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
err := m.QueryRowIndexCtx(ctx, &resp, tydataAgentUserIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
query := fmt.Sprintf("select %s from %s where `user_id` = ? and del_state = ? limit 1", agentRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, userId, globalkey.DelStateNo); err != nil {
return nil, err
@@ -157,16 +157,16 @@ func (m *defaultAgentModel) Update(ctx context.Context, session sqlx.Session, ne
if err != nil {
return nil, err
}
hmAgentIdKey := fmt.Sprintf("%s%v", cacheHmAgentIdPrefix, data.Id)
hmAgentMobileKey := fmt.Sprintf("%s%v", cacheHmAgentMobilePrefix, data.Mobile)
hmAgentUserIdKey := fmt.Sprintf("%s%v", cacheHmAgentUserIdPrefix, data.UserId)
tydataAgentIdKey := fmt.Sprintf("%s%v", cacheTydataAgentIdPrefix, data.Id)
tydataAgentMobileKey := fmt.Sprintf("%s%v", cacheTydataAgentMobilePrefix, data.Mobile)
tydataAgentUserIdKey := fmt.Sprintf("%s%v", cacheTydataAgentUserIdPrefix, data.UserId)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, agentRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, newData.UserId, newData.LevelName, newData.Region, newData.Mobile, newData.WechatId, newData.MembershipExpiryTime, newData.DeleteTime, newData.DelState, newData.Version, newData.Id)
}
return conn.ExecCtx(ctx, query, newData.UserId, newData.LevelName, newData.Region, newData.Mobile, newData.WechatId, newData.MembershipExpiryTime, newData.DeleteTime, newData.DelState, newData.Version, newData.Id)
}, hmAgentIdKey, hmAgentMobileKey, hmAgentUserIdKey)
}, tydataAgentIdKey, tydataAgentMobileKey, tydataAgentUserIdKey)
}
func (m *defaultAgentModel) UpdateWithVersion(ctx context.Context, session sqlx.Session, newData *Agent) error {
@@ -181,16 +181,16 @@ func (m *defaultAgentModel) UpdateWithVersion(ctx context.Context, session sqlx.
if err != nil {
return err
}
hmAgentIdKey := fmt.Sprintf("%s%v", cacheHmAgentIdPrefix, data.Id)
hmAgentMobileKey := fmt.Sprintf("%s%v", cacheHmAgentMobilePrefix, data.Mobile)
hmAgentUserIdKey := fmt.Sprintf("%s%v", cacheHmAgentUserIdPrefix, data.UserId)
tydataAgentIdKey := fmt.Sprintf("%s%v", cacheTydataAgentIdPrefix, data.Id)
tydataAgentMobileKey := fmt.Sprintf("%s%v", cacheTydataAgentMobilePrefix, data.Mobile)
tydataAgentUserIdKey := fmt.Sprintf("%s%v", cacheTydataAgentUserIdPrefix, data.UserId)
sqlResult, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ? and version = ? ", m.table, agentRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, newData.UserId, newData.LevelName, newData.Region, newData.Mobile, newData.WechatId, newData.MembershipExpiryTime, newData.DeleteTime, newData.DelState, newData.Version, newData.Id, oldVersion)
}
return conn.ExecCtx(ctx, query, newData.UserId, newData.LevelName, newData.Region, newData.Mobile, newData.WechatId, newData.MembershipExpiryTime, newData.DeleteTime, newData.DelState, newData.Version, newData.Id, oldVersion)
}, hmAgentIdKey, hmAgentMobileKey, hmAgentUserIdKey)
}, tydataAgentIdKey, tydataAgentMobileKey, tydataAgentUserIdKey)
if err != nil {
return err
}
@@ -413,20 +413,20 @@ func (m *defaultAgentModel) Delete(ctx context.Context, session sqlx.Session, id
return err
}
hmAgentIdKey := fmt.Sprintf("%s%v", cacheHmAgentIdPrefix, id)
hmAgentMobileKey := fmt.Sprintf("%s%v", cacheHmAgentMobilePrefix, data.Mobile)
hmAgentUserIdKey := fmt.Sprintf("%s%v", cacheHmAgentUserIdPrefix, data.UserId)
tydataAgentIdKey := fmt.Sprintf("%s%v", cacheTydataAgentIdPrefix, id)
tydataAgentMobileKey := fmt.Sprintf("%s%v", cacheTydataAgentMobilePrefix, data.Mobile)
tydataAgentUserIdKey := fmt.Sprintf("%s%v", cacheTydataAgentUserIdPrefix, data.UserId)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
if session != nil {
return session.ExecCtx(ctx, query, id)
}
return conn.ExecCtx(ctx, query, id)
}, hmAgentIdKey, hmAgentMobileKey, hmAgentUserIdKey)
}, tydataAgentIdKey, tydataAgentMobileKey, tydataAgentUserIdKey)
return err
}
func (m *defaultAgentModel) formatPrimary(primary interface{}) string {
return fmt.Sprintf("%s%v", cacheHmAgentIdPrefix, primary)
return fmt.Sprintf("%s%v", cacheTydataAgentIdPrefix, primary)
}
func (m *defaultAgentModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", agentRows, m.table)

View File

@@ -27,7 +27,7 @@ var (
agentPlatformDeductionRowsExpectAutoSet = strings.Join(stringx.Remove(agentPlatformDeductionFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
agentPlatformDeductionRowsWithPlaceHolder = strings.Join(stringx.Remove(agentPlatformDeductionFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
cacheHmAgentPlatformDeductionIdPrefix = "cache:tydata:agentPlatformDeduction:id:"
cacheTydataAgentPlatformDeductionIdPrefix = "cache:tydata:agentPlatformDeduction:id:"
)
type (
@@ -56,6 +56,7 @@ type (
AgentPlatformDeduction struct {
Id int64 `db:"id"`
OrderId int64 `db:"order_id"` // 订单ID
AgentId int64 `db:"agent_id"` // 被抽佣代理ID
Amount float64 `db:"amount"`
Type string `db:"type"`
@@ -77,20 +78,20 @@ func newAgentPlatformDeductionModel(conn sqlx.SqlConn, c cache.CacheConf) *defau
func (m *defaultAgentPlatformDeductionModel) Insert(ctx context.Context, session sqlx.Session, data *AgentPlatformDeduction) (sql.Result, error) {
data.DelState = globalkey.DelStateNo
hmAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheHmAgentPlatformDeductionIdPrefix, data.Id)
tydataAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheTydataAgentPlatformDeductionIdPrefix, data.Id)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?)", m.table, agentPlatformDeductionRowsExpectAutoSet)
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?)", m.table, agentPlatformDeductionRowsExpectAutoSet)
if session != nil {
return session.ExecCtx(ctx, query, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version)
return session.ExecCtx(ctx, query, data.OrderId, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version)
}
return conn.ExecCtx(ctx, query, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version)
}, hmAgentPlatformDeductionIdKey)
return conn.ExecCtx(ctx, query, data.OrderId, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version)
}, tydataAgentPlatformDeductionIdKey)
}
func (m *defaultAgentPlatformDeductionModel) FindOne(ctx context.Context, id int64) (*AgentPlatformDeduction, error) {
hmAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheHmAgentPlatformDeductionIdPrefix, id)
tydataAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheTydataAgentPlatformDeductionIdPrefix, id)
var resp AgentPlatformDeduction
err := m.QueryRowCtx(ctx, &resp, hmAgentPlatformDeductionIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
err := m.QueryRowCtx(ctx, &resp, tydataAgentPlatformDeductionIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", agentPlatformDeductionRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id, globalkey.DelStateNo)
})
@@ -105,14 +106,14 @@ func (m *defaultAgentPlatformDeductionModel) FindOne(ctx context.Context, id int
}
func (m *defaultAgentPlatformDeductionModel) Update(ctx context.Context, session sqlx.Session, data *AgentPlatformDeduction) (sql.Result, error) {
hmAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheHmAgentPlatformDeductionIdPrefix, data.Id)
tydataAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheTydataAgentPlatformDeductionIdPrefix, data.Id)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, agentPlatformDeductionRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id)
return session.ExecCtx(ctx, query, data.OrderId, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id)
}
return conn.ExecCtx(ctx, query, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id)
}, hmAgentPlatformDeductionIdKey)
return conn.ExecCtx(ctx, query, data.OrderId, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id)
}, tydataAgentPlatformDeductionIdKey)
}
func (m *defaultAgentPlatformDeductionModel) UpdateWithVersion(ctx context.Context, session sqlx.Session, data *AgentPlatformDeduction) error {
@@ -123,14 +124,14 @@ func (m *defaultAgentPlatformDeductionModel) UpdateWithVersion(ctx context.Conte
var sqlResult sql.Result
var err error
hmAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheHmAgentPlatformDeductionIdPrefix, data.Id)
tydataAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheTydataAgentPlatformDeductionIdPrefix, data.Id)
sqlResult, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ? and version = ? ", m.table, agentPlatformDeductionRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id, oldVersion)
return session.ExecCtx(ctx, query, data.OrderId, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id, oldVersion)
}
return conn.ExecCtx(ctx, query, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id, oldVersion)
}, hmAgentPlatformDeductionIdKey)
return conn.ExecCtx(ctx, query, data.OrderId, data.AgentId, data.Amount, data.Type, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id, oldVersion)
}, tydataAgentPlatformDeductionIdKey)
if err != nil {
return err
}
@@ -348,18 +349,18 @@ func (m *defaultAgentPlatformDeductionModel) SelectBuilder() squirrel.SelectBuil
return squirrel.Select().From(m.table)
}
func (m *defaultAgentPlatformDeductionModel) Delete(ctx context.Context, session sqlx.Session, id int64) error {
hmAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheHmAgentPlatformDeductionIdPrefix, id)
tydataAgentPlatformDeductionIdKey := fmt.Sprintf("%s%v", cacheTydataAgentPlatformDeductionIdPrefix, id)
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
if session != nil {
return session.ExecCtx(ctx, query, id)
}
return conn.ExecCtx(ctx, query, id)
}, hmAgentPlatformDeductionIdKey)
}, tydataAgentPlatformDeductionIdKey)
return err
}
func (m *defaultAgentPlatformDeductionModel) formatPrimary(primary interface{}) string {
return fmt.Sprintf("%s%v", cacheHmAgentPlatformDeductionIdPrefix, primary)
return fmt.Sprintf("%s%v", cacheTydataAgentPlatformDeductionIdPrefix, primary)
}
func (m *defaultAgentPlatformDeductionModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", agentPlatformDeductionRows, m.table)

View File

@@ -27,8 +27,8 @@ var (
featureRowsExpectAutoSet = strings.Join(stringx.Remove(featureFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
featureRowsWithPlaceHolder = strings.Join(stringx.Remove(featureFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
cacheHmFeatureIdPrefix = "cache:tydata:feature:id:"
cacheHmFeatureApiIdPrefix = "cache:tydata:feature:apiId:"
cacheTydataFeatureIdPrefix = "cache:tydata:feature:id:"
cacheTydataFeatureApiIdPrefix = "cache:tydata:feature:apiId:"
)
type (
@@ -65,6 +65,7 @@ type (
Version int64 `db:"version"` // 版本号
ApiId string `db:"api_id"` // API标识
Name string `db:"name"` // 描述
CostPrice float64 `db:"cost_price"` // 成本价
}
)
@@ -77,21 +78,21 @@ func newFeatureModel(conn sqlx.SqlConn, c cache.CacheConf) *defaultFeatureModel
func (m *defaultFeatureModel) Insert(ctx context.Context, session sqlx.Session, data *Feature) (sql.Result, error) {
data.DelState = globalkey.DelStateNo
hmFeatureApiIdKey := fmt.Sprintf("%s%v", cacheHmFeatureApiIdPrefix, data.ApiId)
hmFeatureIdKey := fmt.Sprintf("%s%v", cacheHmFeatureIdPrefix, data.Id)
tydataFeatureApiIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureApiIdPrefix, data.ApiId)
tydataFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureIdPrefix, data.Id)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, featureRowsExpectAutoSet)
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?)", m.table, featureRowsExpectAutoSet)
if session != nil {
return session.ExecCtx(ctx, query, data.DeleteTime, data.DelState, data.Version, data.ApiId, data.Name)
return session.ExecCtx(ctx, query, data.DeleteTime, data.DelState, data.Version, data.ApiId, data.Name, data.CostPrice)
}
return conn.ExecCtx(ctx, query, data.DeleteTime, data.DelState, data.Version, data.ApiId, data.Name)
}, hmFeatureApiIdKey, hmFeatureIdKey)
return conn.ExecCtx(ctx, query, data.DeleteTime, data.DelState, data.Version, data.ApiId, data.Name, data.CostPrice)
}, tydataFeatureApiIdKey, tydataFeatureIdKey)
}
func (m *defaultFeatureModel) FindOne(ctx context.Context, id int64) (*Feature, error) {
hmFeatureIdKey := fmt.Sprintf("%s%v", cacheHmFeatureIdPrefix, id)
tydataFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureIdPrefix, id)
var resp Feature
err := m.QueryRowCtx(ctx, &resp, hmFeatureIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
err := m.QueryRowCtx(ctx, &resp, tydataFeatureIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", featureRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id, globalkey.DelStateNo)
})
@@ -106,9 +107,9 @@ func (m *defaultFeatureModel) FindOne(ctx context.Context, id int64) (*Feature,
}
func (m *defaultFeatureModel) FindOneByApiId(ctx context.Context, apiId string) (*Feature, error) {
hmFeatureApiIdKey := fmt.Sprintf("%s%v", cacheHmFeatureApiIdPrefix, apiId)
tydataFeatureApiIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureApiIdPrefix, apiId)
var resp Feature
err := m.QueryRowIndexCtx(ctx, &resp, hmFeatureApiIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
err := m.QueryRowIndexCtx(ctx, &resp, tydataFeatureApiIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
query := fmt.Sprintf("select %s from %s where `api_id` = ? and del_state = ? limit 1", featureRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, apiId, globalkey.DelStateNo); err != nil {
return nil, err
@@ -130,15 +131,15 @@ func (m *defaultFeatureModel) Update(ctx context.Context, session sqlx.Session,
if err != nil {
return nil, err
}
hmFeatureApiIdKey := fmt.Sprintf("%s%v", cacheHmFeatureApiIdPrefix, data.ApiId)
hmFeatureIdKey := fmt.Sprintf("%s%v", cacheHmFeatureIdPrefix, data.Id)
tydataFeatureApiIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureApiIdPrefix, data.ApiId)
tydataFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureIdPrefix, data.Id)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, featureRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, newData.DeleteTime, newData.DelState, newData.Version, newData.ApiId, newData.Name, newData.Id)
return session.ExecCtx(ctx, query, newData.DeleteTime, newData.DelState, newData.Version, newData.ApiId, newData.Name, newData.CostPrice, newData.Id)
}
return conn.ExecCtx(ctx, query, newData.DeleteTime, newData.DelState, newData.Version, newData.ApiId, newData.Name, newData.Id)
}, hmFeatureApiIdKey, hmFeatureIdKey)
return conn.ExecCtx(ctx, query, newData.DeleteTime, newData.DelState, newData.Version, newData.ApiId, newData.Name, newData.CostPrice, newData.Id)
}, tydataFeatureApiIdKey, tydataFeatureIdKey)
}
func (m *defaultFeatureModel) UpdateWithVersion(ctx context.Context, session sqlx.Session, newData *Feature) error {
@@ -153,15 +154,15 @@ func (m *defaultFeatureModel) UpdateWithVersion(ctx context.Context, session sql
if err != nil {
return err
}
hmFeatureApiIdKey := fmt.Sprintf("%s%v", cacheHmFeatureApiIdPrefix, data.ApiId)
hmFeatureIdKey := fmt.Sprintf("%s%v", cacheHmFeatureIdPrefix, data.Id)
tydataFeatureApiIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureApiIdPrefix, data.ApiId)
tydataFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureIdPrefix, data.Id)
sqlResult, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ? and version = ? ", m.table, featureRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, newData.DeleteTime, newData.DelState, newData.Version, newData.ApiId, newData.Name, newData.Id, oldVersion)
return session.ExecCtx(ctx, query, newData.DeleteTime, newData.DelState, newData.Version, newData.ApiId, newData.Name, newData.CostPrice, newData.Id, oldVersion)
}
return conn.ExecCtx(ctx, query, newData.DeleteTime, newData.DelState, newData.Version, newData.ApiId, newData.Name, newData.Id, oldVersion)
}, hmFeatureApiIdKey, hmFeatureIdKey)
return conn.ExecCtx(ctx, query, newData.DeleteTime, newData.DelState, newData.Version, newData.ApiId, newData.Name, newData.CostPrice, newData.Id, oldVersion)
}, tydataFeatureApiIdKey, tydataFeatureIdKey)
if err != nil {
return err
}
@@ -384,19 +385,19 @@ func (m *defaultFeatureModel) Delete(ctx context.Context, session sqlx.Session,
return err
}
hmFeatureApiIdKey := fmt.Sprintf("%s%v", cacheHmFeatureApiIdPrefix, data.ApiId)
hmFeatureIdKey := fmt.Sprintf("%s%v", cacheHmFeatureIdPrefix, id)
tydataFeatureApiIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureApiIdPrefix, data.ApiId)
tydataFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataFeatureIdPrefix, id)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
if session != nil {
return session.ExecCtx(ctx, query, id)
}
return conn.ExecCtx(ctx, query, id)
}, hmFeatureApiIdKey, hmFeatureIdKey)
}, tydataFeatureApiIdKey, tydataFeatureIdKey)
return err
}
func (m *defaultFeatureModel) formatPrimary(primary interface{}) string {
return fmt.Sprintf("%s%v", cacheHmFeatureIdPrefix, primary)
return fmt.Sprintf("%s%v", cacheTydataFeatureIdPrefix, primary)
}
func (m *defaultFeatureModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", featureRows, m.table)

View File

@@ -27,8 +27,8 @@ var (
orderRowsExpectAutoSet = strings.Join(stringx.Remove(orderFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
orderRowsWithPlaceHolder = strings.Join(stringx.Remove(orderFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
cacheHmOrderIdPrefix = "cache:tydata:order:id:"
cacheHmOrderOrderNoPrefix = "cache:tydata:order:orderNo:"
cacheTydataOrderIdPrefix = "cache:tydata:order:id:"
cacheTydataOrderOrderNoPrefix = "cache:tydata:order:orderNo:"
)
type (
@@ -74,6 +74,7 @@ type (
RefundTime sql.NullTime `db:"refund_time"` // 退款时间
CloseTime sql.NullTime `db:"close_time"` // 订单关闭时间
DeleteTime sql.NullTime `db:"delete_time"` // 删除时间
SalesCost float64 `db:"sales_cost"` // 销售成本
}
)
@@ -86,21 +87,21 @@ func newOrderModel(conn sqlx.SqlConn, c cache.CacheConf) *defaultOrderModel {
func (m *defaultOrderModel) Insert(ctx context.Context, session sqlx.Session, data *Order) (sql.Result, error) {
data.DelState = globalkey.DelStateNo
hmOrderIdKey := fmt.Sprintf("%s%v", cacheHmOrderIdPrefix, data.Id)
hmOrderOrderNoKey := fmt.Sprintf("%s%v", cacheHmOrderOrderNoPrefix, data.OrderNo)
tydataOrderIdKey := fmt.Sprintf("%s%v", cacheTydataOrderIdPrefix, data.Id)
tydataOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataOrderOrderNoPrefix, data.OrderNo)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, orderRowsExpectAutoSet)
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, orderRowsExpectAutoSet)
if session != nil {
return session.ExecCtx(ctx, query, data.OrderNo, data.UserId, data.ProductId, data.PaymentPlatform, data.PaymentScene, data.PlatformOrderId, data.Amount, data.Status, data.DelState, data.Version, data.PayTime, data.RefundTime, data.CloseTime, data.DeleteTime)
return session.ExecCtx(ctx, query, data.OrderNo, data.UserId, data.ProductId, data.PaymentPlatform, data.PaymentScene, data.PlatformOrderId, data.Amount, data.Status, data.DelState, data.Version, data.PayTime, data.RefundTime, data.CloseTime, data.DeleteTime, data.SalesCost)
}
return conn.ExecCtx(ctx, query, data.OrderNo, data.UserId, data.ProductId, data.PaymentPlatform, data.PaymentScene, data.PlatformOrderId, data.Amount, data.Status, data.DelState, data.Version, data.PayTime, data.RefundTime, data.CloseTime, data.DeleteTime)
}, hmOrderIdKey, hmOrderOrderNoKey)
return conn.ExecCtx(ctx, query, data.OrderNo, data.UserId, data.ProductId, data.PaymentPlatform, data.PaymentScene, data.PlatformOrderId, data.Amount, data.Status, data.DelState, data.Version, data.PayTime, data.RefundTime, data.CloseTime, data.DeleteTime, data.SalesCost)
}, tydataOrderIdKey, tydataOrderOrderNoKey)
}
func (m *defaultOrderModel) FindOne(ctx context.Context, id int64) (*Order, error) {
hmOrderIdKey := fmt.Sprintf("%s%v", cacheHmOrderIdPrefix, id)
tydataOrderIdKey := fmt.Sprintf("%s%v", cacheTydataOrderIdPrefix, id)
var resp Order
err := m.QueryRowCtx(ctx, &resp, hmOrderIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
err := m.QueryRowCtx(ctx, &resp, tydataOrderIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", orderRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id, globalkey.DelStateNo)
})
@@ -115,9 +116,9 @@ func (m *defaultOrderModel) FindOne(ctx context.Context, id int64) (*Order, erro
}
func (m *defaultOrderModel) FindOneByOrderNo(ctx context.Context, orderNo string) (*Order, error) {
hmOrderOrderNoKey := fmt.Sprintf("%s%v", cacheHmOrderOrderNoPrefix, orderNo)
tydataOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataOrderOrderNoPrefix, orderNo)
var resp Order
err := m.QueryRowIndexCtx(ctx, &resp, hmOrderOrderNoKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
err := m.QueryRowIndexCtx(ctx, &resp, tydataOrderOrderNoKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
query := fmt.Sprintf("select %s from %s where `order_no` = ? and del_state = ? limit 1", orderRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, orderNo, globalkey.DelStateNo); err != nil {
return nil, err
@@ -139,15 +140,15 @@ func (m *defaultOrderModel) Update(ctx context.Context, session sqlx.Session, ne
if err != nil {
return nil, err
}
hmOrderIdKey := fmt.Sprintf("%s%v", cacheHmOrderIdPrefix, data.Id)
hmOrderOrderNoKey := fmt.Sprintf("%s%v", cacheHmOrderOrderNoPrefix, data.OrderNo)
tydataOrderIdKey := fmt.Sprintf("%s%v", cacheTydataOrderIdPrefix, data.Id)
tydataOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataOrderOrderNoPrefix, data.OrderNo)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, orderRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, newData.OrderNo, newData.UserId, newData.ProductId, newData.PaymentPlatform, newData.PaymentScene, newData.PlatformOrderId, newData.Amount, newData.Status, newData.DelState, newData.Version, newData.PayTime, newData.RefundTime, newData.CloseTime, newData.DeleteTime, newData.Id)
return session.ExecCtx(ctx, query, newData.OrderNo, newData.UserId, newData.ProductId, newData.PaymentPlatform, newData.PaymentScene, newData.PlatformOrderId, newData.Amount, newData.Status, newData.DelState, newData.Version, newData.PayTime, newData.RefundTime, newData.CloseTime, newData.DeleteTime, newData.SalesCost, newData.Id)
}
return conn.ExecCtx(ctx, query, newData.OrderNo, newData.UserId, newData.ProductId, newData.PaymentPlatform, newData.PaymentScene, newData.PlatformOrderId, newData.Amount, newData.Status, newData.DelState, newData.Version, newData.PayTime, newData.RefundTime, newData.CloseTime, newData.DeleteTime, newData.Id)
}, hmOrderIdKey, hmOrderOrderNoKey)
return conn.ExecCtx(ctx, query, newData.OrderNo, newData.UserId, newData.ProductId, newData.PaymentPlatform, newData.PaymentScene, newData.PlatformOrderId, newData.Amount, newData.Status, newData.DelState, newData.Version, newData.PayTime, newData.RefundTime, newData.CloseTime, newData.DeleteTime, newData.SalesCost, newData.Id)
}, tydataOrderIdKey, tydataOrderOrderNoKey)
}
func (m *defaultOrderModel) UpdateWithVersion(ctx context.Context, session sqlx.Session, newData *Order) error {
@@ -162,15 +163,15 @@ func (m *defaultOrderModel) UpdateWithVersion(ctx context.Context, session sqlx.
if err != nil {
return err
}
hmOrderIdKey := fmt.Sprintf("%s%v", cacheHmOrderIdPrefix, data.Id)
hmOrderOrderNoKey := fmt.Sprintf("%s%v", cacheHmOrderOrderNoPrefix, data.OrderNo)
tydataOrderIdKey := fmt.Sprintf("%s%v", cacheTydataOrderIdPrefix, data.Id)
tydataOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataOrderOrderNoPrefix, data.OrderNo)
sqlResult, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ? and version = ? ", m.table, orderRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, newData.OrderNo, newData.UserId, newData.ProductId, newData.PaymentPlatform, newData.PaymentScene, newData.PlatformOrderId, newData.Amount, newData.Status, newData.DelState, newData.Version, newData.PayTime, newData.RefundTime, newData.CloseTime, newData.DeleteTime, newData.Id, oldVersion)
return session.ExecCtx(ctx, query, newData.OrderNo, newData.UserId, newData.ProductId, newData.PaymentPlatform, newData.PaymentScene, newData.PlatformOrderId, newData.Amount, newData.Status, newData.DelState, newData.Version, newData.PayTime, newData.RefundTime, newData.CloseTime, newData.DeleteTime, newData.SalesCost, newData.Id, oldVersion)
}
return conn.ExecCtx(ctx, query, newData.OrderNo, newData.UserId, newData.ProductId, newData.PaymentPlatform, newData.PaymentScene, newData.PlatformOrderId, newData.Amount, newData.Status, newData.DelState, newData.Version, newData.PayTime, newData.RefundTime, newData.CloseTime, newData.DeleteTime, newData.Id, oldVersion)
}, hmOrderIdKey, hmOrderOrderNoKey)
return conn.ExecCtx(ctx, query, newData.OrderNo, newData.UserId, newData.ProductId, newData.PaymentPlatform, newData.PaymentScene, newData.PlatformOrderId, newData.Amount, newData.Status, newData.DelState, newData.Version, newData.PayTime, newData.RefundTime, newData.CloseTime, newData.DeleteTime, newData.SalesCost, newData.Id, oldVersion)
}, tydataOrderIdKey, tydataOrderOrderNoKey)
if err != nil {
return err
}
@@ -393,19 +394,19 @@ func (m *defaultOrderModel) Delete(ctx context.Context, session sqlx.Session, id
return err
}
hmOrderIdKey := fmt.Sprintf("%s%v", cacheHmOrderIdPrefix, id)
hmOrderOrderNoKey := fmt.Sprintf("%s%v", cacheHmOrderOrderNoPrefix, data.OrderNo)
tydataOrderIdKey := fmt.Sprintf("%s%v", cacheTydataOrderIdPrefix, id)
tydataOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataOrderOrderNoPrefix, data.OrderNo)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
if session != nil {
return session.ExecCtx(ctx, query, id)
}
return conn.ExecCtx(ctx, query, id)
}, hmOrderIdKey, hmOrderOrderNoKey)
}, tydataOrderIdKey, tydataOrderOrderNoKey)
return err
}
func (m *defaultOrderModel) formatPrimary(primary interface{}) string {
return fmt.Sprintf("%s%v", cacheHmOrderIdPrefix, primary)
return fmt.Sprintf("%s%v", cacheTydataOrderIdPrefix, primary)
}
func (m *defaultOrderModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", orderRows, m.table)

View File

@@ -27,8 +27,8 @@ var (
productFeatureRowsExpectAutoSet = strings.Join(stringx.Remove(productFeatureFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
productFeatureRowsWithPlaceHolder = strings.Join(stringx.Remove(productFeatureFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
cacheHmProductFeatureIdPrefix = "cache:tydata:productFeature:id:"
cacheHmProductFeatureProductIdFeatureIdPrefix = "cache:tydata:productFeature:productId:featureId:"
cacheTydataProductFeatureIdPrefix = "cache:tydata:productFeature:id:"
cacheTydataProductFeatureProductIdFeatureIdPrefix = "cache:tydata:productFeature:productId:featureId:"
)
type (
@@ -80,21 +80,21 @@ func newProductFeatureModel(conn sqlx.SqlConn, c cache.CacheConf) *defaultProduc
func (m *defaultProductFeatureModel) Insert(ctx context.Context, session sqlx.Session, data *ProductFeature) (sql.Result, error) {
data.DelState = globalkey.DelStateNo
hmProductFeatureIdKey := fmt.Sprintf("%s%v", cacheHmProductFeatureIdPrefix, data.Id)
hmProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheHmProductFeatureProductIdFeatureIdPrefix, data.ProductId, data.FeatureId)
tydataProductFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataProductFeatureIdPrefix, data.Id)
tydataProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheTydataProductFeatureProductIdFeatureIdPrefix, data.ProductId, data.FeatureId)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?)", m.table, productFeatureRowsExpectAutoSet)
if session != nil {
return session.ExecCtx(ctx, query, data.ProductId, data.FeatureId, data.DeleteTime, data.DelState, data.Version, data.Sort, data.IsImportant, data.Enable)
}
return conn.ExecCtx(ctx, query, data.ProductId, data.FeatureId, data.DeleteTime, data.DelState, data.Version, data.Sort, data.IsImportant, data.Enable)
}, hmProductFeatureIdKey, hmProductFeatureProductIdFeatureIdKey)
}, tydataProductFeatureIdKey, tydataProductFeatureProductIdFeatureIdKey)
}
func (m *defaultProductFeatureModel) FindOne(ctx context.Context, id int64) (*ProductFeature, error) {
hmProductFeatureIdKey := fmt.Sprintf("%s%v", cacheHmProductFeatureIdPrefix, id)
tydataProductFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataProductFeatureIdPrefix, id)
var resp ProductFeature
err := m.QueryRowCtx(ctx, &resp, hmProductFeatureIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
err := m.QueryRowCtx(ctx, &resp, tydataProductFeatureIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", productFeatureRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id, globalkey.DelStateNo)
})
@@ -109,9 +109,9 @@ func (m *defaultProductFeatureModel) FindOne(ctx context.Context, id int64) (*Pr
}
func (m *defaultProductFeatureModel) FindOneByProductIdFeatureId(ctx context.Context, productId int64, featureId int64) (*ProductFeature, error) {
hmProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheHmProductFeatureProductIdFeatureIdPrefix, productId, featureId)
tydataProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheTydataProductFeatureProductIdFeatureIdPrefix, productId, featureId)
var resp ProductFeature
err := m.QueryRowIndexCtx(ctx, &resp, hmProductFeatureProductIdFeatureIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
err := m.QueryRowIndexCtx(ctx, &resp, tydataProductFeatureProductIdFeatureIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
query := fmt.Sprintf("select %s from %s where `product_id` = ? and `feature_id` = ? and del_state = ? limit 1", productFeatureRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, productId, featureId, globalkey.DelStateNo); err != nil {
return nil, err
@@ -133,15 +133,15 @@ func (m *defaultProductFeatureModel) Update(ctx context.Context, session sqlx.Se
if err != nil {
return nil, err
}
hmProductFeatureIdKey := fmt.Sprintf("%s%v", cacheHmProductFeatureIdPrefix, data.Id)
hmProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheHmProductFeatureProductIdFeatureIdPrefix, data.ProductId, data.FeatureId)
tydataProductFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataProductFeatureIdPrefix, data.Id)
tydataProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheTydataProductFeatureProductIdFeatureIdPrefix, data.ProductId, data.FeatureId)
return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, productFeatureRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, newData.ProductId, newData.FeatureId, newData.DeleteTime, newData.DelState, newData.Version, newData.Sort, newData.IsImportant, newData.Enable, newData.Id)
}
return conn.ExecCtx(ctx, query, newData.ProductId, newData.FeatureId, newData.DeleteTime, newData.DelState, newData.Version, newData.Sort, newData.IsImportant, newData.Enable, newData.Id)
}, hmProductFeatureIdKey, hmProductFeatureProductIdFeatureIdKey)
}, tydataProductFeatureIdKey, tydataProductFeatureProductIdFeatureIdKey)
}
func (m *defaultProductFeatureModel) UpdateWithVersion(ctx context.Context, session sqlx.Session, newData *ProductFeature) error {
@@ -156,15 +156,15 @@ func (m *defaultProductFeatureModel) UpdateWithVersion(ctx context.Context, sess
if err != nil {
return err
}
hmProductFeatureIdKey := fmt.Sprintf("%s%v", cacheHmProductFeatureIdPrefix, data.Id)
hmProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheHmProductFeatureProductIdFeatureIdPrefix, data.ProductId, data.FeatureId)
tydataProductFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataProductFeatureIdPrefix, data.Id)
tydataProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheTydataProductFeatureProductIdFeatureIdPrefix, data.ProductId, data.FeatureId)
sqlResult, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ? and version = ? ", m.table, productFeatureRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, newData.ProductId, newData.FeatureId, newData.DeleteTime, newData.DelState, newData.Version, newData.Sort, newData.IsImportant, newData.Enable, newData.Id, oldVersion)
}
return conn.ExecCtx(ctx, query, newData.ProductId, newData.FeatureId, newData.DeleteTime, newData.DelState, newData.Version, newData.Sort, newData.IsImportant, newData.Enable, newData.Id, oldVersion)
}, hmProductFeatureIdKey, hmProductFeatureProductIdFeatureIdKey)
}, tydataProductFeatureIdKey, tydataProductFeatureProductIdFeatureIdKey)
if err != nil {
return err
}
@@ -387,19 +387,19 @@ func (m *defaultProductFeatureModel) Delete(ctx context.Context, session sqlx.Se
return err
}
hmProductFeatureIdKey := fmt.Sprintf("%s%v", cacheHmProductFeatureIdPrefix, id)
hmProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheHmProductFeatureProductIdFeatureIdPrefix, data.ProductId, data.FeatureId)
tydataProductFeatureIdKey := fmt.Sprintf("%s%v", cacheTydataProductFeatureIdPrefix, id)
tydataProductFeatureProductIdFeatureIdKey := fmt.Sprintf("%s%v:%v", cacheTydataProductFeatureProductIdFeatureIdPrefix, data.ProductId, data.FeatureId)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
if session != nil {
return session.ExecCtx(ctx, query, id)
}
return conn.ExecCtx(ctx, query, id)
}, hmProductFeatureIdKey, hmProductFeatureProductIdFeatureIdKey)
}, tydataProductFeatureIdKey, tydataProductFeatureProductIdFeatureIdKey)
return err
}
func (m *defaultProductFeatureModel) formatPrimary(primary interface{}) string {
return fmt.Sprintf("%s%v", cacheHmProductFeatureIdPrefix, primary)
return fmt.Sprintf("%s%v", cacheTydataProductFeatureIdPrefix, primary)
}
func (m *defaultProductFeatureModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", productFeatureRows, m.table)