Compare commits

...

2 Commits

Author SHA1 Message Date
0493efefc7 v2.0 2025-05-11 01:49:52 +08:00
d7f8e9c090 add agent stats 2025-05-10 21:43:10 +08:00
104 changed files with 1876 additions and 469 deletions

View File

@ -57,6 +57,14 @@ service main {
// 获取推广定价配置
@handler GetAgentProductConfig
get /product_config returns (AgentProductConfigResp)
// 获取下级分页列表
@handler GetAgentSubordinateList
get /subordinate/list (GetAgentSubordinateListReq) returns (GetAgentSubordinateListResp)
// 下级贡献详情
@handler GetAgentSubordinateContributionDetail
get /subordinate/contribution/detail (GetAgentSubordinateContributionDetailReq) returns (GetAgentSubordinateContributionDetailResp)
}
type (
@ -68,6 +76,7 @@ type (
region string `json:"region"`
mobile string `json:"mobile"`
wechatID string `json:"wechat_id"`
expiryTime string `json:"expiry_time"`
}
// 查询代理申请状态响应
AgentAuditStatusResp {
@ -84,6 +93,63 @@ type (
AgentProductConfigResp {
AgentProductConfig []AgentProductConfig
}
GetAgentSubordinateListReq {
Page int64 `form:"page"` // 页码
PageSize int64 `form:"page_size"` // 每页数据量
}
GetAgentSubordinateListResp {
Total int64 `json:"total"` // 总记录数
List []AgentSubordinateList `json:"list"` // 查询列表
}
AgentSubordinateList {
ID int64 `json:"id"`
Mobile string `json:"mobile"`
CreateTime string `json:"create_time"`
LevelName string `json:"level_name"`
TotalOrders int64 `json:"total_orders"` // 总单量
TotalEarnings float64 `json:"total_earnings"` // 总金额
TotalContribution float64 `json:"total_contribution"` // 总贡献
}
GetAgentSubordinateContributionDetailReq {
Page int64 `form:"page"` // 页码
PageSize int64 `form:"page_size"` // 每页数据量
SubordinateID int64 `form:"subordinate_id"` // 下级ID
}
GetAgentSubordinateContributionDetailResp {
Mobile string `json:"mobile"`
Total int64 `json:"total"` // 总记录数
CreateTime string `json:"create_time"`
TotalEarnings float64 `json:"total_earnings"` // 总金额
TotalContribution float64 `json:"total_contribution"` // 总贡献
TotalOrders int64 `json:"total_orders"` // 总单量
LevelName string `json:"level_name"` // 等级名称
List []AgentSubordinateContributionDetail `json:"list"` // 查询列表
Stats AgentSubordinateContributionStats `json:"stats"` // 统计数据
}
AgentSubordinateContributionDetail {
ID int64 `json:"id"`
CreateTime string `json:"create_time"`
Amount float64 `json:"amount"`
Type string `json:"type"`
}
AgentSubordinateContributionStats {
CostCount int64 `json:"cost_count"` // 成本扣除次数
CostAmount float64 `json:"cost_amount"` // 成本扣除总额
PricingCount int64 `json:"pricing_count"` // 定价扣除次数
PricingAmount float64 `json:"pricing_amount"` // 定价扣除总额
DescendantPromotionCount int64 `json:"descendant_promotion_count"` // 下级推广次数
DescendantPromotionAmount float64 `json:"descendant_promotion_amount"` // 下级推广总额
DescendantUpgradeVipCount int64 `json:"descendant_upgrade_vip_count"` // 下级升级VIP次数
DescendantUpgradeVipAmount float64 `json:"descendant_upgrade_vip_amount"` // 下级升级VIP总额
DescendantUpgradeSvipCount int64 `json:"descendant_upgrade_svip_count"` // 下级升级SVIP次数
DescendantUpgradeSvipAmount float64 `json:"descendant_upgrade_svip_amount"` // 下级升级SVIP总额
DescendantStayActiveCount int64 `json:"descendant_stay_active_count"` // 下级保持活跃次数
DescendantStayActiveAmount float64 `json:"descendant_stay_active_amount"` // 下级保持活跃总额
DescendantNewActiveCount int64 `json:"descendant_new_active_count"` // 下级新增活跃次数
DescendantNewActiveAmount float64 `json:"descendant_new_active_amount"` // 下级新增活跃总额
DescendantWithdrawCount int64 `json:"descendant_withdraw_count"` // 下级提现次数
DescendantWithdrawAmount float64 `json:"descendant_withdraw_amount"` // 下级提现总额
}
)
@server (
@ -141,6 +207,9 @@ service main {
@handler AgentWithdrawal
post /withdrawal (WithdrawalReq) returns (WithdrawalResp)
@handler ActivateAgentMembership
post /membership/activate (AgentActivateMembershipReq) returns (AgentActivateMembershipResp)
}
type (
@ -231,6 +300,15 @@ type (
Status int64 `json:"status"` // 1申请中 2成功 3失败
failMsg string `json:"fail_msg"`
}
// 开通代理会员请求参数
AgentActivateMembershipReq {
Type string `json:"type,oneof=VIP SVIP"` // 会员类型vip/svip
}
// 开通代理会员响应
AgentActivateMembershipResp {
Id string `json:"id"`
}
)
@server (
@ -246,8 +324,6 @@ service main {
@handler GetLinkData
get /link (GetLinkDataReq) returns (GetLinkDataResp)
@handler ActivateAgentMembership
post /membership/activate (AgentActivateMembershipReq) returns (AgentActivateMembershipResp)
}
type (
@ -270,18 +346,5 @@ type (
GetLinkDataResp {
Product
}
// 开通代理会员请求参数
AgentActivateMembershipReq {
Mobile string `json:"mobile"`
Type string `json:"type,oneof=VIP SVIP"` // 会员类型vip/svip
Amount float64 `json:"amount"`
PaymentMethod string `json:"payment_method"`
TransactionId string `json:"transaction_id"`
}
// 开通代理会员响应
AgentActivateMembershipResp {
MembershipType string `json:"membership_type"` // 最终开通的会员类型
ExpireTime string `json:"expire_time"` // 到期时间
}
)

View File

@ -39,17 +39,28 @@ service main {
@handler IapCallback
post /pay/iap_callback (IapCallbackReq)
@handler PaymentCheck
post /pay/check (PaymentCheckReq) returns (PaymentCheckResp)
}
type (
PaymentReq {
Id string `json:"id"`
PayMethod string `json:"pay_method"`
PayType string `json:"pay_type" validate:"required,oneof=query agent_vip"`
}
PaymentResp {
PrepayData interface{} `json:"prepay_data"`
PrepayId string `json:"prepay_id"`
OrderID int64 `json:"order_id"`
OrderNo string `json:"order_no"`
}
PaymentCheckReq {
OrderNo string `json:"order_no" validate:"required"`
}
PaymentCheckResp {
Type string `json:"type"`
Status string `json:"status"`
}
)

View File

@ -102,11 +102,13 @@ service main {
@handler queryDetailByOrderNo
get /query/orderNo/:order_no (QueryDetailByOrderNoReq) returns (QueryDetailByOrderNoResp)
@doc "重试查询"
@handler queryRetry
post /query/retry/:id (QueryRetryReq) returns (QueryRetryResp)
@doc "更新查询数据"
@handler updateQueryData
post /query/update_data (UpdateQueryDataReq) returns (UpdateQueryDataResp)
}
// 获取查询临时订单
@ -178,6 +180,18 @@ type (
}
)
type (
UpdateQueryDataReq {
Id int64 `json:"id"` // 查询ID
QueryData string `json:"query_data"` // 查询数据(未加密的JSON)
}
UpdateQueryDataResp {
Id int64 `json:"id"`
UpdatedAt string `json:"updated_at"` // 更新时间
}
)
@server (
prefix: api/v1
group: query
@ -190,9 +204,6 @@ service main {
@handler queryDetail
get /query/:id (QueryDetailReq) returns (QueryDetailResp)
@doc "更新查询数据"
@handler updateQueryData
post /query/update_data (UpdateQueryDataReq) returns (UpdateQueryDataResp)
}
type QuerySingleTestReq {
@ -205,13 +216,3 @@ type QuerySingleTestResp {
Api string `json:"api"`
}
type (
UpdateQueryDataReq {
Id int64 `json:"id"` // 查询ID
QueryData string `json:"query_data"` // 查询数据(未加密的JSON)
}
UpdateQueryDataResp {
Id int64 `json:"id"`
UpdatedAt string `json:"updated_at"` // 更新时间
}
)

View File

@ -125,12 +125,23 @@ service main {
@handler cancelOut
post /user/cancelOut
@doc "绑定手机号"
@handler bindMobile
post /user/bindMobile (BindMobileReq) returns (BindMobileResp)
}
type (
UserInfoResp {
UserInfo User `json:"userInfo"`
}
BindMobileReq {
Mobile string `json:"mobile" validate:"required,mobile"`
Code string `json:"code" validate:"required"`
}
BindMobileResp {
}
)
//============================> auth v1 <============================
@ -147,7 +158,7 @@ service main {
type (
sendSmsReq {
Mobile string `json:"mobile" validate:"required,mobile"`
ActionType string `json:"actionType" validate:"required,oneof=login register query agentApply"`
ActionType string `json:"actionType" validate:"required,oneof=login register query agentApply bindMobile"`
}
)

View File

@ -42,11 +42,11 @@ Alipay:
Wxpay:
AppID: "wxa581992dc74d860e"
MchID: "1704330055"
MchCertificateSerialNumber: "749065854D0CECCE8F98EAFEA55AD4FB17F868C4"
MchApiv3Key: "A9f3G7kL2mP5sQ8tV1xY4zB6nC0dE3hJ"
MchPrivateKeyPath: "etc/merchant/apiclient_key.pem"
MchPublicKeyID: "PUB_KEY_ID_0117043300552025010900447500000187"
MchPublicKeyPath: "etc/merchant/pub_key.pem"
MchCertificateSerialNumber: "434FE8C0FC8CFEF28B76B3EF35DD2297E977A3CB"
MchApiv3Key: "h6Jk9Qm7W1pXyFzA4bL2V8CzH0K3wDqw"
MchPrivateKeyPath: "etc/merchant/apiclient_key.pem"
NotifyUrl: "https://6m4685017o.goho.co/api/v1/pay/wechat/callback"
RefundNotifyUrl: "https://6m4685017o.goho.co/api/v1/wechat/refund_callback"
Applepay:

View File

@ -39,15 +39,15 @@ Alipay:
AlipayRootCertPath: "etc/merchant/alipayRootCert.crt"
IsProduction: true
NotifyUrl: "https://www.tianyuandb.com/api/v1/pay/alipay/callback"
ReturnURL: "https://www.tianyuandb.com/report"
ReturnURL: "https://www.tianyuandb.com/payment/result"
Wxpay:
AppID: "wxa581992dc74d860e"
MchID: "1704330055"
MchCertificateSerialNumber: "749065854D0CECCE8F98EAFEA55AD4FB17F868C4"
MchApiv3Key: "A9f3G7kL2mP5sQ8tV1xY4zB6nC0dE3hJ"
MchPrivateKeyPath: "etc/merchant/apiclient_key.pem"
MchPublicKeyID: "PUB_KEY_ID_0117043300552025010900447500000187"
MchPublicKeyPath: "etc/merchant/pub_key.pem"
MchCertificateSerialNumber: "434FE8C0FC8CFEF28B76B3EF35DD2297E977A3CB"
MchApiv3Key: "h6Jk9Qm7W1pXyFzA4bL2V8CzH0K3wDqw"
MchPrivateKeyPath: "etc/merchant/apiclient_key.pem"
NotifyUrl: "https://www.tianyuandb.com/api/v1/pay/wechat/callback"
RefundNotifyUrl: "https://www.tianyuandb.com/api/v1/wechat/refund_callback"
Applepay:

View File

@ -1,28 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDBUq/9OV6FzRcl
vUReArEh6czC001MVzEsBbde88xpsZjQkCoECzJL7wHq9aWcom4yQjp6AiTHeHO1
FvHoRN/dssxgVf28V3L2zF4U23FNcWOElScQksYESNAIVTQb5lKnRdgAS4LRY0OE
BzSnlYn+m6zQV6GRCOv0uCR7tgRFGdYW+RoHjHJqH4dX2cN/SrpuB01/BEkUJIp7
bWswyh8Ogf9GZZumJlmJtld18ZDqd1RzQDk8VbYxJgsmcXcQPa1LouZsBVzU4IdV
Bz0/vNIJ2+D+shifPT7dL4IWCjL6zHxYdnHv9VDb1bS9JN6pk4Tpi4C3Tyhaq3kI
iRW0IPqFAgMBAAECggEAR9KMh6t0rokPfHngmHyvikXuSMNwCFiscAp/ocs5ulq8
x1+H/JCcUxGsyLoSmSrPfeSVDRcWyvS5KCIqJXzRHvB6dZ/88KgckgxDN8R/R6JE
stEm/kVJQ/Y5M59UCLl9I6ATK6jiJSCXyMlUip5H8kur3Itx/wwtfXGcPEnXNERK
qM7AXRB2d6Ag0XkC9Cfdf6U7WNk1zKAr+1V1Iiav5mU7A8iHFsgK6RjVbxdh2ghJ
45LLU26YdoNoSWRefd1Wu/n0OMfyQdpySnyJcei2+5PlNbt6uHKrQLxtSE/HllcK
agv+FzfRYNpZ+ia7GMvTDNEuvnkKxs/K24Gk+aOwUQKBgQD48Qkns6gIN9yURMgc
KE8mDaerNeuCHY1cxymgriYUQAjrEysy51W41q+gvvJbXYMAmNM5RbrV+ktSWDZG
kljQaY0c/u0mYofuNYs/ul1TFcQTwxNnYUMmCWFzRgFM7Sp2H+sRO3W+Tvs9ctFJ
7a8HOYxqkQSfnHSgOuXAKXvy6wKBgQDGzfCF6DfRh3D/QQ9WCBi1JNWdLL6fHbmI
V4OrpQuQiTGGf/yY8ySOLq0QYXyc3pBxgTdOChliSNBjdr7/LXusIByZEvcKOds5
pOalrjrFWoNf87zM38wMQjUeMprWQniBmq4H+TL7De29hR1QhdGb62uZCLo5V1u2
k41gGvoMTwKBgC1blaRzOomMzBcD1UY0Hf+7+zHZ2DhT9B7UdwQ81tlXtYhHbNaQ
ifDsxQFP6U62Yhkov0uvJdS5DyJIylLfdWk74idHV6RnzYacoOuSpFBwJdLH93Ad
q6NxkBz1w2TlzZfKRwVTxSdQsrxGgFWtBfgWBzyfga0nT6SmNphltpzTAoGAML3l
Lq+Un+aZKbwFyo4JoL/7L6H8yn47MtZiDf9VKoa4gcV3ZPiYCdQf0lhUeRGIUIvh
x1xqhNJdZUWD5oR8QeNNn6oqr3Mn8KYhdpWVCzX559iWfZSRLqA87b5yf/2kFgKa
kJHkkfEETOcKHOfyUEwUAV1GazCj58udaeazT7kCgYB23ZTeqRsxw7jqEVz6KOSW
oWGYi0/lDmW6dtjcT3fDtyiYDlnE+53dIs2mcIvUyOwzcQ+e1rH+ZmGf/UpfWyXl
7aftUeDlPMLHi7wQUU04DaZU/Lyy0HGHMKVrPJF47gLKCgfk8I8HdUEtHSXNmYZb
hZ3T2j+d4u74saGGaxOlqw==
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDd7p4NV2SkjF3d
zLDltShURK21VIMalnjimqpXiFSuwwIlMb3Ad6rQyClpRAHA4V/POnRlPEDc7ddm
W97uw01Fyn1Hapta3aeHTA4EOdzUVk9i74ZiLKP1SJgNNelonAD6YFmqlVvvBV9w
ufCUu+9GAM8h9tdHlVR6o+BG3hP5A7FH/yuPuXplf1SuQh/SBahxX37zP0Av14g+
FS9slawJiAn9wEpDb2moj3Y6i+afDA8nsgZNBhnMcv49VV0pwx/oKTQMATcavR0d
DKgohqLiUG+KtgoJU3KutiarQZRiVf4iSTHw+G8IGl8f/3LqgUK18QoX81hGp68F
hnWp/5KdAgMBAAECggEBAMY+lrS4MlDCij7Mz+ABmQrdZoYp/grMCyPwoOUcBPkv
fUUYT7YTr2RcyJEdjKttJxaH0t1zm0U+uEDZJCUIFIiZPpuC4U+j3DiBeavQvDB5
AOURrWsZEUTUGe8DD4LAiCcf1jkIvlye4ghiMEPMNQrFQkHGq7tn61S5+meTjSfL
uJz1Ta587R/2ptAyo/QE0iKTFRRvymekOb0OLu7nyIC9vTCD7V9xjARwp2OwBDBu
Ztdv7WTFLeoO3Xt+Liopvwk1DNiqhamnLeBr/UttqYbtkotGO7wUlwZW9yM5fCnp
GHhuaejVk4eEw34lurEo8X7HMc+WwQ0/s9+5iM62RgECgYEA9Mki8eIaD2Wk0FdA
9PL7diW1h4KHMi/lb2AUXGkH4zNxp6k0bmT4n5S588OkXsT8YgUdAhwfTz+M3Olz
e39rwcN7u4NCoOmNcwfpW1o7w6rn04aC2Iz1SpZhtM+DBVhuS87VmC3ViGt242FW
bfSrSw0vDrvjMIj/5ApiVpwf2N0CgYEA6Blz0IBedtQkjBf+OC33wnBNwq/5VICs
V8eAHsq/EexRf2Z/JtCkPDYCiLddLjRt+jIPFCPyR8AsKQf8vdUFfhZ029GBCCrZ
usn1hoN3rDv4GuOMXJWCvpS45KoXZt8h31NTRAVqKRWXsIWkARu0++J6NfZR8FO7
Jrx/QnKWJMECgYEA5HDlHMk+OspH8mrLYw1z4UG11H3a/9o1CyimN8uJId57ndVJ
6hBu+jaJB1W4ivzY7/0HolVuXr3XDr8LF+DFRnHRgiAwSQ1NBWIHxEpEZgmUChKI
/+EkdXQ8QMo74vwxCqw/J6L2mTZ5ICBR0ZG5XfQyy1RK5Jul+0I5ncxb6D0CgYAJ
6aRfoEvoiVDyRsgNwDDXthIsIXXlnQU/Tn7zUbdtXYlxhoAhuUF6bNgY3LP3GDgm
OmMYehyL4fJA4l1yAhoU84KULNN09NeNubhpwU2oJnuHMna5MY1+9D0dTwJm21rH
/fgNbKnHDWwIFv0VKwjExTxw948yU3Eny18oCFrPQQKBgQCCHWUVIzzci/YkX3lv
IzSgs4VTs4979hGeUYB4u+ihVU3cpXGLbuhm37Cgf0aX+I5vyxplKURgxg8jGnPB
KDuI2+1TlwXYt+5zCrpmBtZXpQbknde5Pfser+PMuGjybeWWpHzek7kZKPNCHwTL
BJG/ccbM6dULpIVcziB/hQMvLA==
-----END PRIVATE KEY-----

View File

@ -53,11 +53,11 @@ type AlipayConfig struct {
type WxpayConfig struct {
AppID string
MchID string
MchPublicKeyID string
MchPublicKeyPath string
MchCertificateSerialNumber string
MchApiv3Key string
MchPrivateKeyPath string
MchPublicKeyID string
MchPublicKeyPath string
NotifyUrl string
RefundNotifyUrl string
}

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func ActivateAgentMembershipHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func AgentWithdrawalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func ApplyForAgentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GeneratingLinkHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetAgentCommissionHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetAgentMembershipProductConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetAgentRevenueInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetAgentRewardsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -0,0 +1,30 @@
package agent
import (
"net/http"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetAgentSubordinateContributionDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.GetAgentSubordinateContributionDetailReq
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 := agent.NewGetAgentSubordinateContributionDetailLogic(r.Context(), svcCtx)
resp, err := l.GetAgentSubordinateContributionDetail(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@ -0,0 +1,30 @@
package agent
import (
"net/http"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetAgentSubordinateListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.GetAgentSubordinateListReq
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 := agent.NewGetAgentSubordinateListLogic(r.Context(), svcCtx)
resp, err := l.GetAgentSubordinateList(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetAgentWithdrawalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetLinkDataHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package agent
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/agent"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func SaveAgentMembershipUserConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package auth
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/auth"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func SendSmsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package pay
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/pay"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func IapCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -0,0 +1,30 @@
package pay
import (
"net/http"
"tydata-server/app/user/cmd/api/internal/logic/pay"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func PaymentCheckHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.PaymentCheckReq
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 := pay.NewPaymentCheckLogic(r.Context(), svcCtx)
resp, err := l.PaymentCheck(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@ -3,12 +3,13 @@ package pay
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/pay"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func PaymentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package product
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/product"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetProductAppByEnHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package product
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/product"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetProductByEnHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package product
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/product"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func GetProductByIDHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryDetailByOrderIdHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryDetailByOrderNoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryExampleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryProvisionalOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryRetryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryServiceAgentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryServiceAppHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,11 +3,12 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QueryServiceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package query
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/query"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func QuerySingleTestHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -1,6 +1,4 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.7.3
package handler
import (
@ -42,6 +40,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/product_config",
Handler: agent.GetAgentProductConfigHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/subordinate/contribution/detail",
Handler: agent.GetAgentSubordinateContributionDetailHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/subordinate/list",
Handler: agent.GetAgentSubordinateListHandler(serverCtx),
},
},
rest.WithJwt(serverCtx.Config.JwtAuth.AccessSecret),
rest.WithPrefix("/api/v1/agent"),
@ -71,6 +79,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/commission",
Handler: agent.GetAgentCommissionHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/membership/activate",
Handler: agent.ActivateAgentMembershipHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/revenue",
@ -108,11 +121,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/link",
Handler: agent.GetLinkDataHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/membership/activate",
Handler: agent.ActivateAgentMembershipHandler(serverCtx),
},
},
rest.WithPrefix("/api/v1/agent"),
)
@ -183,6 +191,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
rest.WithMiddlewares(
[]rest.Middleware{serverCtx.SourceInterceptor},
[]rest.Route{
{
Method: http.MethodPost,
Path: "/pay/check",
Handler: pay.PaymentCheckHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/pay/iap_callback",
@ -295,6 +308,12 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/query/retry/:id",
Handler: query.QueryRetryHandler(serverCtx),
},
{
// 更新查询数据
Method: http.MethodPost,
Path: "/query/update_data",
Handler: query.UpdateQueryDataHandler(serverCtx),
},
},
rest.WithJwt(serverCtx.Config.JwtAuth.AccessSecret),
rest.WithPrefix("/api/v1"),
@ -313,12 +332,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/query/single/test",
Handler: query.QuerySingleTestHandler(serverCtx),
},
{
// 更新查询数据
Method: http.MethodPost,
Path: "/query/update_data",
Handler: query.UpdateQueryDataHandler(serverCtx),
},
},
rest.WithPrefix("/api/v1"),
)
@ -367,6 +380,12 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
// 绑定手机号
Method: http.MethodPost,
Path: "/user/bindMobile",
Handler: user.BindMobileHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/user/cancelOut",

View File

@ -3,12 +3,13 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/user"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func AgentMobileCodeLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -0,0 +1,30 @@
package user
import (
"net/http"
"tydata-server/app/user/cmd/api/internal/logic/user"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func BindMobileHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.BindMobileReq
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 := user.NewBindMobileLogic(r.Context(), svcCtx)
resp, err := l.BindMobile(&req)
result.HttpResult(r, w, resp, err)
}
}

View File

@ -3,12 +3,13 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/user"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func MobileCodeLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/user"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func MobileLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/user"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func RegisterHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/user"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func WxH5AuthHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -3,12 +3,13 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"tydata-server/app/user/cmd/api/internal/logic/user"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/result"
"tydata-server/pkg/lzkit/validator"
"github.com/zeromicro/go-zero/rest/httpx"
)
func WxMiniAuthHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

View File

@ -2,17 +2,17 @@ package agent
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
"tydata-server/app/user/model"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/app/user/model"
"github.com/zeromicro/go-zero/core/logx"
)
@ -30,27 +30,16 @@ func NewActivateAgentMembershipLogic(ctx context.Context, svcCtx *svc.ServiceCon
svcCtx: svcCtx,
}
}
func (l *ActivateAgentMembershipLogic) ActivateAgentMembership(req *types.AgentActivateMembershipReq) (resp *types.AgentActivateMembershipResp, err error) {
//userID, err := ctxdata.GetUidFromCtx(l.ctx)
//if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
//}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile, err := crypto.EncryptMobile(req.Mobile, secretKey)
userID, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败: %v", err)
}
userModel, err := l.svcCtx.UserModel.FindOneByMobile(l.ctx, encryptedMobile)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败: %v", err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
}
// 查询用户代理信息
agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userModel.Id)
if err != nil && err != sql.ErrNoRows {
agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败: %v", err)
}
// 定义等级顺序映射
levelOrder := map[string]int{
"": 1,
@ -77,52 +66,20 @@ func (l *ActivateAgentMembershipLogic) ActivateAgentMembership(req *types.AgentA
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
"禁止降级操作(当前等级:%s请求等级%s", agentModel.LevelName, req.Type)
}
// 同等级视为续费,允许操作
}
err = l.svcCtx.AgentModel.Trans(l.ctx, func(transCtx context.Context, session sqlx.Session) error {
agentModel.LevelName = req.Type
agentModel.MembershipExpiryTime = RenewMembership(agentModel.MembershipExpiryTime)
transErr := l.svcCtx.AgentModel.UpdateWithVersion(transCtx, session, agentModel)
if transErr != nil {
return transErr
}
agentMembershipRechargeOrder := model.AgentMembershipRechargeOrder{
AgentId: agentModel.Id,
UserId: userModel.Id,
LevelName: req.Type,
Amount: req.Amount,
PaymentMethod: req.PaymentMethod,
TransactionId: req.TransactionId,
}
_, transErr = l.svcCtx.AgentMembershipRechargeOrderModel.Insert(transCtx, session, &agentMembershipRechargeOrder)
if transErr != nil {
return transErr
}
return nil
})
outTradeNo := "A_" + l.svcCtx.AlipayService.GenerateOutTradeNo()
redisKey := fmt.Sprintf(types.AgentVipCacheKey, userID, outTradeNo)
agentVipCache := types.AgentVipCache{Type: req.Type}
jsonData, err := json.Marshal(agentVipCache)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "升级代理等级失败: %s", req.Type)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "序列化代理VIP缓存失败: %v", err)
}
cacheErr := l.svcCtx.Redis.SetexCtx(l.ctx, redisKey, string(jsonData), int(2*time.Hour))
if cacheErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "设置缓存失败: %v", cacheErr)
}
return &types.AgentActivateMembershipResp{
MembershipType: req.Type,
ExpireTime: agentModel.MembershipExpiryTime.Time.Format("2006-01-02 15:04:05"),
Id: outTradeNo,
}, nil
}
func RenewMembership(expiry sql.NullTime) sql.NullTime {
// 确定基准时间
var baseTime time.Time
if expiry.Valid {
baseTime = expiry.Time
} else {
baseTime = time.Now()
}
// 增加一年(自动处理闰年)
newTime := baseTime.AddDate(1, 0, 0)
// 返回始终有效的 NullTime
return sql.NullTime{
Time: newTime,
Valid: true,
}
}

View File

@ -79,7 +79,7 @@ func (l *AgentWithdrawalLogic) AgentWithdrawal(req *types.WithdrawalReq) (*types
}
// 生成交易号
outBizNo = l.svcCtx.AlipayService.GenerateOutTradeNo()
outBizNo = "W_" + l.svcCtx.AlipayService.GenerateOutTradeNo()
// 创建提现记录(初始状态为处理中)
if err = l.createWithdrawalRecord(session, agentModel.Id, req, outBizNo); err != nil {

View File

@ -2,6 +2,7 @@ package agent
import (
"context"
"database/sql"
"fmt"
"time"
"tydata-server/app/user/model"
@ -58,15 +59,15 @@ func (l *ApplyForAgentLogic) ApplyForAgent(req *types.AgentApplyReq) (resp *type
var userID int64
transErr := l.svcCtx.AgentAuditModel.Trans(l.ctx, func(transCtx context.Context, session sqlx.Session) error {
// 两种情况1. 已注册账号然后申请代理 2. 未注册账号申请代理
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, encryptedMobile)
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
if findUserErr != nil && !errors.Is(findUserErr, model.ErrNotFound) {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 读取数据库获取用户失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if user == nil {
user = &model.User{Mobile: encryptedMobile}
if len(user.Nickname) == 0 {
user.Nickname = encryptedMobile
}
user = &model.User{Mobile: sql.NullString{String: encryptedMobile, Valid: true}}
// if len(user.Nickname) == 0 {
// user.Nickname = encryptedMobile
// }
insertResult, userInsertErr := l.svcCtx.UserModel.Insert(transCtx, session, user)
if userInsertErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 数据库插入新用户失败, mobile%s, err: %+v", encryptedMobile, err)

View File

@ -4,14 +4,15 @@ import (
"context"
"encoding/hex"
"encoding/json"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"strconv"
"tydata-server/app/user/model"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/pkg/lzkit/crypto"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,11 +2,12 @@ package agent
import (
"context"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -71,6 +71,7 @@ func (l *GetAgentInfoLogic) GetAgentInfo() (resp *types.AgentInfoResp, err error
Status: 1,
Region: agent.Region,
Mobile: agent.Mobile,
ExpiryTime: agent.MembershipExpiryTime.Time.Format("2006-01-02 15:04:05"),
WechatID: lzUtils.NullStringToString(agent.WechatId),
}, nil
}

View File

@ -2,13 +2,14 @@ package agent
import (
"context"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/app/user/model"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/pkg/lzkit/lzUtils"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,13 +2,14 @@ package agent
import (
"context"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"time"
"tydata-server/app/user/model"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,11 +2,12 @@ package agent
import (
"context"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -0,0 +1,200 @@
package agent
import (
"context"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/pkg/lzkit/crypto"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type GetAgentSubordinateContributionDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetAgentSubordinateContributionDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAgentSubordinateContributionDetailLogic {
return &GetAgentSubordinateContributionDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetAgentSubordinateContributionDetailLogic) GetAgentSubordinateContributionDetail(req *types.GetAgentSubordinateContributionDetailReq) (resp *types.GetAgentSubordinateContributionDetailResp, err error) {
userID, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理下级贡献详情, 获取用户ID%v", err)
}
// 获取当前代理信息
agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级贡献详情, 获取代理信息%v", err)
}
// 获取下级代理信息
subordinateAgent, err := l.svcCtx.AgentModel.FindOne(l.ctx, req.SubordinateID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级贡献详情, 获取下级代理信息%v", err)
}
// 验证是否是当前代理的下级
closureBuilder := l.svcCtx.AgentClosureModel.SelectBuilder().Where(squirrel.Eq{
"ancestor_id": agentModel.Id,
"descendant_id": req.SubordinateID,
})
closureList, err := l.svcCtx.AgentClosureModel.FindAll(l.ctx, closureBuilder, "create_time DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级贡献详情, 验证代理关系%v", err)
}
if len(closureList) == 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理下级贡献详情, 非法的代理关系")
}
closure := closureList[0]
// 获取佣金扣除记录
deductionBuilder := l.svcCtx.AgentCommissionDeductionModel.SelectBuilder().Where(squirrel.Eq{
"agent_id": agentModel.Id,
"deducted_agent_id": req.SubordinateID,
})
deductionList, err := l.svcCtx.AgentCommissionDeductionModel.FindAll(l.ctx, deductionBuilder, "create_time DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级贡献详情, 获取佣金扣除记录%v", err)
}
// 获取奖励记录
rewardsBuilder := l.svcCtx.AgentRewardsModel.SelectBuilder().Where(squirrel.Eq{
"agent_id": agentModel.Id,
"relation_agent_id": req.SubordinateID,
})
rewards, err := l.svcCtx.AgentRewardsModel.FindAll(l.ctx, rewardsBuilder, "create_time DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级贡献详情, 获取奖励记录%v", err)
}
// 计算总贡献
var totalContribution float64
for _, v := range deductionList {
totalContribution += v.Amount
}
// 加上奖励金额
for _, v := range rewards {
totalContribution += v.Amount
}
// 获取佣金记录
commissionBuilder := l.svcCtx.AgentCommissionModel.SelectBuilder().Where(squirrel.Eq{
"agent_id": req.SubordinateID,
})
commissionList, err := l.svcCtx.AgentCommissionModel.FindAll(l.ctx, commissionBuilder, "create_time DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级贡献详情, 获取佣金记录%v", err)
}
// 计算总收益和总单量
var totalEarnings float64
for _, v := range commissionList {
totalEarnings += v.Amount
}
// 初始化统计数据
stats := types.AgentSubordinateContributionStats{
CostCount: 0,
CostAmount: 0,
PricingCount: 0,
PricingAmount: 0,
DescendantPromotionCount: 0,
DescendantPromotionAmount: 0,
DescendantUpgradeVipCount: 0,
DescendantUpgradeVipAmount: 0,
DescendantUpgradeSvipCount: 0,
DescendantUpgradeSvipAmount: 0,
DescendantStayActiveCount: 0,
DescendantStayActiveAmount: 0,
DescendantNewActiveCount: 0,
DescendantNewActiveAmount: 0,
DescendantWithdrawCount: 0,
DescendantWithdrawAmount: 0,
}
// 统计佣金扣除记录
for _, v := range deductionList {
switch v.Type {
case "cost":
stats.CostCount++
stats.CostAmount += v.Amount
case "pricing":
stats.PricingCount++
stats.PricingAmount += v.Amount
}
}
// 统计奖励记录
for _, v := range rewards {
switch v.Type {
case "descendant_promotion":
stats.DescendantPromotionCount++
stats.DescendantPromotionAmount += v.Amount
case "descendant_upgrade_vip":
stats.DescendantUpgradeVipCount++
stats.DescendantUpgradeVipAmount += v.Amount
case "descendant_upgrade_svip":
stats.DescendantUpgradeSvipCount++
stats.DescendantUpgradeSvipAmount += v.Amount
case "descendant_stay_active":
stats.DescendantStayActiveCount++
stats.DescendantStayActiveAmount += v.Amount
case "descendant_new_active":
stats.DescendantNewActiveCount++
stats.DescendantNewActiveAmount += v.Amount
case "descendant_withdraw":
stats.DescendantWithdrawCount++
stats.DescendantWithdrawAmount += v.Amount
}
}
// 解密手机号
secretKey := l.svcCtx.Config.Encrypt.SecretKey
mobile, err := crypto.DecryptMobile(subordinateAgent.Mobile, secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理下级贡献详情, 解密手机号失败: %v", err)
}
// 获取合并后的分页列表
unionDetails, total, err := l.svcCtx.AgentClosureModel.FindUnionPageListByPageWithTotal(l.ctx, agentModel.Id, req.SubordinateID, req.Page, req.PageSize)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级贡献详情, 获取分页列表%v", err)
}
// 转换为响应类型
detailList := make([]types.AgentSubordinateContributionDetail, 0, len(unionDetails))
for _, v := range unionDetails {
detail := types.AgentSubordinateContributionDetail{
ID: v.Id,
CreateTime: v.CreateTime,
Amount: v.Amount,
Type: v.Type,
}
detailList = append(detailList, detail)
}
return &types.GetAgentSubordinateContributionDetailResp{
Mobile: maskPhone(mobile),
Total: total,
CreateTime: closure.CreateTime.Format("2006-01-02 15:04:05"),
TotalEarnings: totalEarnings,
TotalContribution: totalContribution,
TotalOrders: int64(len(commissionList)),
LevelName: subordinateAgent.LevelName,
List: detailList,
Stats: stats,
}, nil
}

View File

@ -0,0 +1,173 @@
package agent
import (
"context"
"strings"
"time"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/app/user/model"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/pkg/lzkit/crypto"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type GetAgentSubordinateListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetAgentSubordinateListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAgentSubordinateListLogic {
return &GetAgentSubordinateListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetAgentSubordinateListLogic) GetAgentSubordinateList(req *types.GetAgentSubordinateListReq) (resp *types.GetAgentSubordinateListResp, err error) {
userID, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理下级列表, 获取用户ID%v", err)
}
agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理信息%v", err)
}
agentID := agentModel.Id
builder := l.svcCtx.AgentClosureModel.SelectBuilder().Where(squirrel.Eq{
"ancestor_id": agentID,
})
agentClosureModelList, total, err := l.svcCtx.AgentClosureModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理关系%v", err)
}
// 构建ID到CreateTime的映射
createTimeMap := make(map[int64]time.Time)
descendantIDs := make([]int64, 0)
for _, v := range agentClosureModelList {
descendantIDs = append(descendantIDs, v.DescendantId)
createTimeMap[v.DescendantId] = v.CreateTime
}
// 并发查询代理信息
agentMap := make(map[int64]*model.Agent)
var descendantList []types.AgentSubordinateList
err = mr.Finish(func() error {
return mr.MapReduceVoid(func(source chan<- interface{}) {
for _, id := range descendantIDs {
source <- id
}
}, func(item interface{}, writer mr.Writer[interface{}], cancel func(error)) {
id := item.(int64)
agent, err := l.svcCtx.AgentModel.FindOne(l.ctx, id)
if err != nil {
cancel(err)
return
}
writer.Write(agent)
}, func(pipe <-chan interface{}, cancel func(error)) {
for item := range pipe {
agent := item.(*model.Agent)
agentMap[agent.Id] = agent
}
})
}, func() error {
// 并发查询佣金扣除信息
deductionBuilder := l.svcCtx.AgentCommissionDeductionModel.SelectBuilder().
Where(squirrel.Eq{"agent_id": agentID}).
Where(squirrel.Eq{"deducted_agent_id": descendantIDs})
deductionList, err := l.svcCtx.AgentCommissionDeductionModel.FindAll(l.ctx, deductionBuilder, "")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理佣金扣除信息%v", err)
}
deductionMap := make(map[int64]float64)
for _, v := range deductionList {
deductionMap[v.DeductedAgentId] += v.Amount
}
// 并发查询奖励信息
rewardsBuilder := l.svcCtx.AgentRewardsModel.SelectBuilder().
Where(squirrel.Eq{"agent_id": agentID}).
Where(squirrel.Eq{"relation_agent_id": descendantIDs})
rewardsList, err := l.svcCtx.AgentRewardsModel.FindAll(l.ctx, rewardsBuilder, "")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理奖励信息%v", err)
}
rewardsMap := make(map[int64]float64)
for _, v := range rewardsList {
if v.RelationAgentId.Valid {
rewardsMap[v.RelationAgentId.Int64] += v.Amount
}
}
// 并发查询佣金信息
commissionBuilder := l.svcCtx.AgentCommissionModel.SelectBuilder().
Where(squirrel.Eq{"agent_id": descendantIDs})
commissionList, err := l.svcCtx.AgentCommissionModel.FindAll(l.ctx, commissionBuilder, "")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理佣金信息%v", err)
}
commissionMap := make(map[int64]float64)
orderCountMap := make(map[int64]int64)
for _, v := range commissionList {
commissionMap[v.AgentId] += v.Amount
orderCountMap[v.AgentId]++
}
// 构建返回结果
secretKey := l.svcCtx.Config.Encrypt.SecretKey
descendantList = make([]types.AgentSubordinateList, 0, len(descendantIDs))
for _, id := range descendantIDs {
agent, exists := agentMap[id]
if !exists {
continue
}
mobile, err := crypto.DecryptMobile(agent.Mobile, secretKey)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理信息, 解密手机号失败: %v", err)
}
subordinate := types.AgentSubordinateList{
ID: id,
Mobile: maskPhone(mobile),
LevelName: agent.LevelName,
CreateTime: createTimeMap[id].Format("2006-01-02 15:04:05"),
TotalContribution: deductionMap[id] + rewardsMap[id],
TotalEarnings: commissionMap[id],
TotalOrders: orderCountMap[id],
}
descendantList = append(descendantList, subordinate)
}
return nil
})
if err != nil {
return nil, err
}
return &types.GetAgentSubordinateListResp{
Total: total,
List: descendantList,
}, nil
}
// 手机号脱敏
func maskPhone(phone string) string {
length := len(phone)
if length < 8 {
return phone // 如果长度太短,可能不是手机号,不处理
}
// 保留前3位和后4位
return phone[:3] + strings.Repeat("*", length-7) + phone[length-4:]
}

View File

@ -2,11 +2,12 @@ package agent
import (
"context"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,9 +2,10 @@ package agent
import (
"context"
"tydata-server/common/xerr"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/common/xerr"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,11 +2,12 @@ package notification
import (
"context"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"time"
"tydata-server/common/xerr"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,16 +2,20 @@ package pay
import (
"context"
"database/sql"
"fmt"
"net/http"
"os"
"strings"
"time"
"tydata-server/pkg/lzkit/lzUtils"
"github.com/smartwalle/alipay/v3"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/model"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AlipayCallbackLogic struct {
@ -29,31 +33,46 @@ func NewAlipayCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Al
}
func (l *AlipayCallbackLogic) AlipayCallback(w http.ResponseWriter, r *http.Request) error {
env := os.Getenv("ENV")
if env == "development" {
return nil
}
notification, err := l.svcCtx.AlipayService.HandleAliPaymentNotification(r)
if err != nil {
logx.Errorf("支付宝支付回调,%v", err)
return nil
}
// 根据订单号前缀判断订单类型
orderNo := notification.OutTradeNo
if strings.HasPrefix(orderNo, "Q_") {
// 查询订单处理
return l.handleQueryOrderPayment(w, notification)
} else if strings.HasPrefix(orderNo, "A_") {
// 代理会员订单处理
return l.handleAgentVipOrderPayment(w, notification)
} else {
// 兼容旧订单,假设没有前缀的是查询订单
return l.handleQueryOrderPayment(w, notification)
}
}
// 处理查询订单支付
func (l *AlipayCallbackLogic) handleQueryOrderPayment(w http.ResponseWriter, notification *alipay.Notification) error {
order, findOrderErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, notification.OutTradeNo)
if findOrderErr != nil {
logx.Errorf("支付宝支付回调,查找订单失败: %+v", findOrderErr)
return nil
}
if order.Status != "pending" {
alipay.ACKNotification(w)
return nil
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, order.UserId)
if err != nil {
logx.Errorf("支付宝支付回调,查找用户失败: %+v", err)
return nil
}
amount := lzUtils.ToAlipayAmount(order.Amount)
amount := lzUtils.ToAlipayAmount(order.Amount)
if user.Inside != 1 {
// 确保订单金额和状态正确,防止重复更新
if amount != notification.TotalAmount {
@ -62,11 +81,6 @@ func (l *AlipayCallbackLogic) AlipayCallback(w http.ResponseWriter, r *http.Requ
}
}
if order.Status != "pending" {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("success")) // 确保只写入一次响应
return nil
}
switch notification.TradeStatus {
case alipay.TradeStatusSuccess:
order.Status = "paid"
@ -74,17 +88,148 @@ func (l *AlipayCallbackLogic) AlipayCallback(w http.ResponseWriter, r *http.Requ
default:
return nil
}
order.PlatformOrderId = lzUtils.StringToNullString(notification.TradeNo)
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
logx.Errorf("支付宝支付回调,修改订单信息失败: %+v", updateErr)
return nil
}
if order.Status == "paid" {
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(order.Id); asyncErr != nil {
logx.Errorf("异步任务调度失败: %v", asyncErr)
return asyncErr
}
}
alipay.ACKNotification(w)
return nil
}
// 处理代理会员订单支付
func (l *AlipayCallbackLogic) handleAgentVipOrderPayment(w http.ResponseWriter, notification *alipay.Notification) error {
agentOrder, findAgentOrderErr := l.svcCtx.AgentMembershipRechargeOrderModel.FindOneByOrderNo(l.ctx, notification.OutTradeNo)
if findAgentOrderErr != nil {
logx.Errorf("支付宝支付回调,查找代理会员订单失败: %+v", findAgentOrderErr)
return nil
}
if agentOrder.Status != "pending" {
alipay.ACKNotification(w)
return nil
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, agentOrder.UserId)
if err != nil {
logx.Errorf("支付宝支付回调,查找用户失败: %+v", err)
return nil
}
amount := lzUtils.ToAlipayAmount(agentOrder.Amount)
if user.Inside != 1 {
// 确保订单金额和状态正确,防止重复更新
if amount != notification.TotalAmount {
logx.Errorf("支付宝支付回调,金额不一致")
return nil
}
}
switch notification.TradeStatus {
case alipay.TradeStatusSuccess:
agentOrder.Status = "paid"
default:
return nil
}
if agentOrder.Status == "paid" {
err = l.svcCtx.AgentModel.Trans(l.ctx, func(transCtx context.Context, session sqlx.Session) error {
agentModel, err := l.svcCtx.AgentModel.FindOne(transCtx, agentOrder.AgentId)
if err != nil {
return fmt.Errorf("查找代理信息失败: %+v", err)
}
agentOrder.PlatformOrderId = lzUtils.StringToNullString(notification.TradeNo)
if updateErr := l.svcCtx.AgentMembershipRechargeOrderModel.UpdateWithVersion(l.ctx, nil, agentOrder); updateErr != nil {
return fmt.Errorf("修改代理会员订单信息失败: %+v", updateErr)
}
// 设置会员等级
agentModel.LevelName = agentOrder.LevelName
// 延长会员时间
// 检查是否是同级续费并记录到日志
isRenewal := agentModel.LevelName == agentOrder.LevelName && agentModel.MembershipExpiryTime.Valid
if isRenewal {
logx.Infof("代理会员续费成功会员ID%d等级%s", agentModel.Id, agentModel.LevelName)
} else {
logx.Infof("代理会员新购或升级成功会员ID%d等级%s", agentModel.Id, agentModel.LevelName)
}
agentModel.MembershipExpiryTime = RenewMembership(agentModel.MembershipExpiryTime)
if updateErr := l.svcCtx.AgentModel.UpdateWithVersion(l.ctx, nil, agentModel); updateErr != nil {
return fmt.Errorf("修改代理信息失败: %+v", updateErr)
}
return nil
})
if err != nil {
logx.Errorf("支付宝支付回调,处理代理会员订单失败: %+v", err)
refundErr := l.handleRefund(agentOrder)
if refundErr != nil {
logx.Errorf("支付宝支付回调,退款失败: %+v", refundErr)
}
return nil
}
}
alipay.ACKNotification(w)
return nil
}
func RenewMembership(expiry sql.NullTime) sql.NullTime {
// 确定基准时间
var baseTime time.Time
if expiry.Valid {
baseTime = expiry.Time
} else {
baseTime = time.Now()
}
// 增加一年(自动处理闰年)
newTime := baseTime.AddDate(1, 0, 0)
// 返回始终有效的 NullTime
return sql.NullTime{
Time: newTime,
Valid: true,
}
}
func (l *AlipayCallbackLogic) handleRefund(order *model.AgentMembershipRechargeOrder) error {
ctx := context.Background()
// 退款
if order.PaymentMethod == "wechat" {
refundErr := l.svcCtx.WechatPayService.WeChatRefund(ctx, order.OrderNo, order.Amount, order.Amount)
if refundErr != nil {
return refundErr
}
} else {
refund, refundErr := l.svcCtx.AlipayService.AliRefund(ctx, order.OrderNo, order.Amount)
if refundErr != nil {
return refundErr
}
if refund.IsSuccess() {
logx.Errorf("支付宝退款成功, orderID: %d", order.Id)
// 更新订单状态为退款
order.Status = "refunded"
updateOrderErr := l.svcCtx.AgentMembershipRechargeOrderModel.UpdateWithVersion(ctx, nil, order)
if updateOrderErr != nil {
logx.Errorf("更新订单状态失败订单ID: %d, 错误: %v", order.Id, updateOrderErr)
return fmt.Errorf("更新订单状态失败: %v", updateOrderErr)
}
return nil
} else {
logx.Errorf("支付宝退款失败:%v", refundErr)
return refundErr
}
// 直接成功
}
return nil
}

View File

@ -2,13 +2,14 @@ package pay
import (
"context"
"github.com/pkg/errors"
"time"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/xerr"
"tydata-server/pkg/lzkit/lzUtils"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)

View File

@ -0,0 +1,49 @@
package pay
import (
"context"
"strings"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type PaymentCheckLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewPaymentCheckLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentCheckLogic {
return &PaymentCheckLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *PaymentCheckLogic) PaymentCheck(req *types.PaymentCheckReq) (resp *types.PaymentCheckResp, err error) {
if strings.HasPrefix(req.OrderNo, "A_") {
order, err := l.svcCtx.AgentMembershipRechargeOrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单失败: %v", err)
}
return &types.PaymentCheckResp{
Type: "agent_vip",
Status: order.Status,
}, nil
} else {
order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单失败: %v", err)
}
return &types.PaymentCheckResp{
Type: "query",
Status: order.Status,
}, nil
}
}

View File

@ -5,7 +5,6 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"os"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/app/user/model"
@ -14,6 +13,7 @@ import (
"tydata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/redis/go-redis/v9"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
@ -23,6 +23,11 @@ type PaymentLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
}
type PaymentTypeResp struct {
amount float64
outTradeNo string
description string
}
func NewPaymentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentLogic {
return &PaymentLogic{
@ -33,20 +38,61 @@ func NewPaymentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentLo
}
func (l *PaymentLogic) Payment(req *types.PaymentReq) (resp *types.PaymentResp, err error) {
var paymentTypeResp *PaymentTypeResp
var prepayData interface{}
l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
switch req.PayType {
case "agent_vip":
paymentTypeResp, err = l.AgentVipOrderPayment(req, session)
if err != nil {
return err
}
case "query":
paymentTypeResp, err = l.QueryOrderPayment(req, session)
if err != nil {
return err
}
}
var createOrderErr error
if req.PayMethod == "wechat" {
prepayData, createOrderErr = l.svcCtx.WechatPayService.CreateWechatOrder(l.ctx, paymentTypeResp.amount, paymentTypeResp.description, paymentTypeResp.outTradeNo)
} else if req.PayMethod == "alipay" {
prepayData, createOrderErr = l.svcCtx.AlipayService.CreateAlipayOrder(l.ctx, paymentTypeResp.amount, paymentTypeResp.description, paymentTypeResp.outTradeNo)
} else if req.PayMethod == "appleiap" {
prepayData = l.svcCtx.ApplePayService.GetIappayAppID(paymentTypeResp.outTradeNo)
}
if createOrderErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 创建支付订单失败: %+v", createOrderErr)
}
return nil
})
if err != nil {
return nil, err
}
switch v := prepayData.(type) {
case string:
// 如果 prepayData 是字符串类型,直接返回
return &types.PaymentResp{PrepayId: v, OrderNo: paymentTypeResp.outTradeNo}, nil
default:
return &types.PaymentResp{PrepayData: prepayData, OrderNo: paymentTypeResp.outTradeNo}, nil
}
}
func (l *PaymentLogic) QueryOrderPayment(req *types.PaymentReq, session sqlx.Session) (resp *PaymentTypeResp, err error) {
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
if getUidErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取用户信息失败, %+v", getUidErr)
}
brand, ok := l.ctx.Value("brand").(string)
if !ok {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取平台失败, %+v", getUidErr)
}
outTradeNo := req.Id
redisKey := fmt.Sprintf("%d:%s", userID, outTradeNo)
redisKey := fmt.Sprintf(types.QueryCacheKey, userID, outTradeNo)
cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
if cacheErr != nil {
return nil, cacheErr
if cacheErr == redis.Nil {
return nil, errors.Wrapf(xerr.NewErrMsg("订单已过期"), "生成订单, 缓存不存在, %+v", cacheErr)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取缓存失败, %+v", cacheErr)
}
var data types.QueryCacheLoad
err = json.Unmarshal([]byte(cache), &data)
@ -59,9 +105,7 @@ func (l *PaymentLogic) Payment(req *types.PaymentReq) (resp *types.PaymentResp,
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 查找产品错误: %v", err)
}
var prepayData interface{}
var amount float64
var orderAmount float64
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取用户信息失败: %v", err)
@ -73,79 +117,95 @@ func (l *PaymentLogic) Payment(req *types.PaymentReq) (resp *types.PaymentResp,
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取代理订单失败: %+v", findAgentLinkErr)
}
amount = agentLinkModel.Price
orderAmount = agentLinkModel.Price
} else {
amount = product.SellPrice
orderAmount = product.SellPrice
}
if user.Inside == 1 {
amount = 0.01
}
var createOrderErr error
if req.PayMethod == "wechat" {
prepayData, createOrderErr = l.svcCtx.WechatPayService.CreateWechatOrder(l.ctx, amount, product.ProductName, outTradeNo)
} else if req.PayMethod == "alipay" {
prepayData, createOrderErr = l.svcCtx.AlipayService.CreateAlipayOrder(l.ctx, amount, product.ProductName, outTradeNo, brand)
} else if req.PayMethod == "appleiap" {
prepayData = l.svcCtx.ApplePayService.GetIappayAppID(product.ProductEn)
}
if createOrderErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 创建支付订单失败: %+v", createOrderErr)
}
var orderID int64
transErr := l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
order := model.Order{
OrderNo: outTradeNo,
UserId: userID,
ProductId: product.Id,
PaymentPlatform: req.PayMethod,
PaymentScene: "app",
Amount: orderAmount,
Amount: amount,
Status: "pending",
}
orderInsertResult, insertOrderErr := l.svcCtx.OrderModel.Insert(ctx, session, &order)
orderInsertResult, insertOrderErr := l.svcCtx.OrderModel.Insert(l.ctx, session, &order)
if insertOrderErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存订单失败: %+v", insertOrderErr)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存订单失败: %+v", insertOrderErr)
}
insertedOrderID, lastInsertIdErr := orderInsertResult.LastInsertId()
if lastInsertIdErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取保存订单ID失败: %+v", lastInsertIdErr)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取保存订单ID失败: %+v", lastInsertIdErr)
}
orderID = insertedOrderID
if data.AgentIdentifier != "" {
agent, parsingErr := l.agentParsing(data.AgentIdentifier)
if parsingErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 解析代理标识符失败: %+v", parsingErr)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 解析代理标识符失败: %+v", parsingErr)
}
var agentOrder model.AgentOrder
agentOrder.OrderId = orderID
agentOrder.AgentId = agent.AgentID
_, agentOrderInsert := l.svcCtx.AgentOrderModel.Insert(ctx, session, &agentOrder)
_, agentOrderInsert := l.svcCtx.AgentOrderModel.Insert(l.ctx, session, &agentOrder)
if agentOrderInsert != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存代理订单失败: %+v", agentOrderInsert)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存代理订单失败: %+v", agentOrderInsert)
}
}
return nil
})
if transErr != nil {
return nil, transErr
return &PaymentTypeResp{amount: amount, outTradeNo: outTradeNo, description: product.ProductName}, nil
}
env := os.Getenv("ENV")
if env == "development" {
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(orderID); asyncErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 异步订单调用失败: %+v", asyncErr)
func (l *PaymentLogic) AgentVipOrderPayment(req *types.PaymentReq, session sqlx.Session) (resp *PaymentTypeResp, err error) {
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
if getUidErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取用户信息失败, %+v", getUidErr)
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取用户信息失败: %v", err)
}
switch v := prepayData.(type) {
case string:
// 如果 prepayData 是字符串类型,直接返回
return &types.PaymentResp{PrepayId: v, OrderID: orderID}, nil
default:
return &types.PaymentResp{PrepayData: prepayData, OrderID: orderID}, nil
// 查询用户代理信息
agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败: %v", err)
}
redisKey := fmt.Sprintf(types.AgentVipCacheKey, userID, req.Id)
cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
if cacheErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取缓存失败, %+v", cacheErr)
}
var agentVipCache types.AgentVipCache
err = json.Unmarshal([]byte(cache), &agentVipCache)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解析缓存内容失败, %+v", err)
}
agentMembershipConfig, err := l.svcCtx.AgentMembershipConfigModel.FindOneByLevelName(l.ctx, agentVipCache.Type)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取代理会员配置失败, %+v", err)
}
amount := agentMembershipConfig.Price.Float64
if user.Inside == 1 {
amount = 0.01
}
agentMembershipRechargeOrder := model.AgentMembershipRechargeOrder{
OrderNo: req.Id,
UserId: userID,
AgentId: agentModel.Id,
Amount: amount,
PaymentMethod: req.PayMethod,
LevelName: agentVipCache.Type,
Status: "pending",
}
_, err = l.svcCtx.AgentMembershipRechargeOrderModel.Insert(l.ctx, session, &agentMembershipRechargeOrder)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存代理会员充值订单失败: %+v", err)
}
return &PaymentTypeResp{amount: amount, outTradeNo: req.Id, description: fmt.Sprintf("%s代理会员充值", agentMembershipConfig.LevelName)}, nil
}
func (l *PaymentLogic) agentParsing(agentIdentifier string) (*types.AgentIdentifier, error) {
key, decodeErr := hex.DecodeString("8e3e7a2f60edb49221e953b9c029ed10")

View File

@ -7,8 +7,9 @@ import (
"tydata-server/app/user/cmd/api/internal/service"
"tydata-server/pkg/lzkit/lzUtils"
"github.com/zeromicro/go-zero/core/logx"
"tydata-server/app/user/cmd/api/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type WechatPayCallbackLogic struct {

View File

@ -2,10 +2,11 @@ package pay
import (
"context"
"github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic"
"github.com/zeromicro/go-zero/core/logx"
"net/http"
"tydata-server/app/user/cmd/api/internal/svc"
"github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic"
"github.com/zeromicro/go-zero/core/logx"
)
type WechatPayRefundCallbackLogic struct {

View File

@ -2,12 +2,13 @@ package product
import (
"context"
"tydata-server/app/user/model"
"tydata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/mr"
"tydata-server/app/user/model"
"tydata-server/common/xerr"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,12 +2,13 @@ package product
import (
"context"
"tydata-server/app/user/model"
"tydata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/mr"
"tydata-server/app/user/model"
"tydata-server/common/xerr"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -52,11 +52,16 @@ func (l *QueryDetailByOrderIdLogic) QueryDetailByOrderId(req *types.QueryDetailB
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找用户错误: %v", err)
}
if user.Inside != 1 {
// 安全验证:确保订单属于当前用户
if order.UserId != userId {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "无权查看此订单报告")
}
}
// 创建渐进式延迟策略实例
progressiveDelayOrder, err := delay.New(200*time.Millisecond, 3*time.Second, 10*time.Second, 1.5)
@ -232,7 +237,6 @@ func (l *QueryDetailByOrderIdLogic) UpdateFeatureAndProductFeature(productID int
if pf.FeatureId == feature.Id { // 确保和 Feature 关联
sort = int(pf.Sort)
break // 找到第一个符合条件的就退出循环
}
}
featureData = map[string]interface{}{

View File

@ -195,7 +195,6 @@ func (l *QueryDetailByOrderNoLogic) UpdateFeatureAndProductFeature(productID int
if pf.FeatureId == feature.Id { // 确保和 Feature 关联
sort = int(pf.Sort)
break // 找到第一个符合条件的就退出循环
}
}
featureData = map[string]interface{}{

View File

@ -4,12 +4,13 @@ import (
"context"
"encoding/hex"
"encoding/json"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/common/xerr"
"tydata-server/pkg/lzkit/crypto"
"tydata-server/pkg/lzkit/lzUtils"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -0,0 +1,152 @@
package query
// import (
// "context"
// "encoding/hex"
// "fmt"
// "tydata-server/app/user/cmd/api/internal/svc"
// "tydata-server/app/user/cmd/api/internal/types"
// "tydata-server/common/xerr"
// "github.com/jinzhu/copier"
// "github.com/pkg/errors"
// "github.com/zeromicro/go-zero/core/logx"
// )
// type QueryExampleLogic struct {
// logx.Logger
// ctx context.Context
// svcCtx *svc.ServiceContext
// }
// func NewQueryExampleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryExampleLogic {
// return &QueryExampleLogic{
// Logger: logx.WithContext(ctx),
// ctx: ctx,
// svcCtx: svcCtx,
// }
// }
// func (l *QueryExampleLogic) QueryExample(req *types.QueryExampleReq) (resp *types.QueryExampleResp, err error) {
// var exampleID int64
// switch req.Feature {
// case "backgroundcheck":
// exampleID = 508
// case "companyinfo":
// exampleID = 506
// case "homeservice":
// exampleID = 504
// case "marriage":
// exampleID = 501
// case "preloanbackgroundcheck":
// exampleID = 509
// case "rentalinfo":
// exampleID = 505
// case "riskassessment":
// exampleID = 503
// default:
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "示例报告, 获取示例报告失败: %v", err)
// }
// queryModel, err := l.svcCtx.QueryModel.FindOne(l.ctx, exampleID)
// if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "示例报告, 获取示例报告失败: %v", err)
// }
// var query types.Query
// query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
// query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
// // 解密查询数据
// secretKey := l.svcCtx.Config.Encrypt.SecretKey
// key, decodeErr := hex.DecodeString(secretKey)
// if decodeErr != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 获取AES解密解药失败, %v", err)
// }
// processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
// if processParamsErr != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 报告参数处理失败: %v", processParamsErr)
// }
// processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
// if processErr != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 报告结果处理失败: %v", processErr)
// }
// updateFeatureAndProductFeatureErr := l.UpdateFeatureAndProductFeature(queryModel.ProductId, &query.QueryData)
// if updateFeatureAndProductFeatureErr != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateFeatureAndProductFeatureErr)
// }
// // 复制报告数据
// err = copier.Copy(&query, queryModel)
// if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 报告结构体复制失败, %v", err)
// }
// product, err := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
// if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 获取商品信息失败, %v", err)
// }
// query.ProductName = product.ProductName
// return &types.QueryExampleResp{
// Query: query,
// }, nil
// }
// func (l *QueryExampleLogic) UpdateFeatureAndProductFeature(productID int64, target *[]types.QueryItem) error {
// // 遍历 target 数组,使用倒序遍历,以便删除元素时不影响索引
// for i := len(*target) - 1; i >= 0; i-- {
// queryItem := &(*target)[i]
// // 确保 Data 为 map 类型
// data, ok := queryItem.Data.(map[string]interface{})
// if !ok {
// return fmt.Errorf("queryItem.Data 必须是 map[string]interface{} 类型")
// }
// // 从 Data 中获取 apiID
// apiID, ok := data["apiID"].(string)
// if !ok {
// return fmt.Errorf("queryItem.Data 中的 apiID 必须是字符串类型")
// }
// // 查询 Feature
// feature, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, apiID)
// if err != nil {
// // 如果 Feature 查不到,也要删除当前 QueryItem
// *target = append((*target)[:i], (*target)[i+1:]...)
// continue
// }
// // 查询 ProductFeatureModel
// builder := l.svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", productID)
// productFeatures, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "")
// if err != nil {
// return fmt.Errorf("查询 ProductFeatureModel 错误: %v", err)
// }
// // 遍历 productFeatures找到与 feature.ID 关联且 enable == 1 的项
// var featureData map[string]interface{}
// foundFeature := false
// for _, pf := range productFeatures {
// if pf.FeatureId == feature.Id { // 确保和 Feature 关联
// foundFeature = true
// if pf.Enable == 1 {
// featureData = map[string]interface{}{
// "featureName": feature.Name,
// "sort": pf.Sort,
// }
// break // 找到第一个符合条件的就退出循环
// }
// }
// }
// // 如果没有符合条件的 feature 或者 featureData 为空,则删除当前 queryItem
// if !foundFeature || featureData == nil {
// *target = append((*target)[:i], (*target)[i+1:]...)
// continue
// }
// // 更新 queryItem 的 Feature 字段(不是数组)
// queryItem.Feature = featureData
// }
// return nil
// }

View File

@ -4,13 +4,14 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)

View File

@ -2,9 +2,10 @@ package query
import (
"context"
"github.com/pkg/errors"
"tydata-server/common/xerr"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,6 +2,7 @@ package query
import (
"context"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
@ -1380,8 +1381,8 @@ func (l *QueryServiceLogic) CacheData(params map[string]interface{}, Product str
if marshalErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 序列化参数失败: %+v", marshalErr)
}
outTradeNo := l.svcCtx.AlipayService.GenerateOutTradeNo()
redisKey := fmt.Sprintf("%d:%s", userID, outTradeNo)
outTradeNo := "Q_" + l.svcCtx.AlipayService.GenerateOutTradeNo()
redisKey := fmt.Sprintf(types.QueryCacheKey, userID, outTradeNo)
cacheErr := l.svcCtx.Redis.SetexCtx(l.ctx, redisKey, string(jsonData), int(2*time.Hour))
if cacheErr != nil {
return "", cacheErr
@ -1401,16 +1402,16 @@ func (l *QueryServiceLogic) GetOrCreateUser(mobile string) (int64, error) {
return userID, nil
}
userModel, err := l.svcCtx.UserModel.FindOneByMobile(l.ctx, mobile)
userModel, err := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: mobile, Valid: true})
if err != nil && !errors.Is(err, model.ErrNotFound) {
return 0, err
}
// 没有则创建账号
if userModel == nil {
userModel = &model.User{Mobile: mobile}
if len(userModel.Nickname) == 0 {
userModel.Nickname = mobile
}
userModel = &model.User{Mobile: sql.NullString{String: mobile, Valid: true}}
// if len(userModel.Nickname) == 0 {
// userModel.Nickname = mobile
// }
if transErr := l.svcCtx.UserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
insertResult, userInsertErr := l.svcCtx.UserModel.Insert(ctx, session, userModel)
if userInsertErr != nil {

View File

@ -3,9 +3,10 @@ package query
import (
"context"
"encoding/json"
"github.com/pkg/errors"
"tydata-server/common/xerr"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,6 +2,7 @@ package user
import (
"context"
"database/sql"
"fmt"
"time"
"tydata-server/app/user/cmd/api/internal/svc"
@ -51,15 +52,15 @@ func (l *AgentMobileCodeLoginLogic) AgentMobileCodeLogin(req *types.MobileCodeLo
return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "手机登录, 验证码不正确")
}
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, encryptedMobile)
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
if findUserErr != nil && findUserErr != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取数据库获取用户失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if user == nil {
user = &model.User{Mobile: encryptedMobile}
if len(user.Nickname) == 0 {
user.Nickname = ""
}
user = &model.User{Mobile: sql.NullString{String: encryptedMobile, Valid: true}}
// if len(user.Nickname) == 0 {
// user.Nickname = ""
// }
if transErr := l.svcCtx.UserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
insertResult, userInsertErr := l.svcCtx.UserModel.Insert(ctx, session, user)
if userInsertErr != nil {

View File

@ -0,0 +1,104 @@
package user
import (
"context"
"database/sql"
"fmt"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"tydata-server/app/user/model"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"tydata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type BindMobileLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewBindMobileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindMobileLogic {
return &BindMobileLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *BindMobileLogic) BindMobile(req *types.BindMobileReq) (resp *types.BindMobileResp, err error) {
userID, getUserIdErr := ctxdata.GetUidFromCtx(l.ctx)
if getUserIdErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, %v", getUserIdErr)
}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile, err := crypto.EncryptMobile(req.Mobile, secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 加密手机号失败: %v", err)
}
user, err := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, %v", err)
}
if user != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("该手机号已绑定"), "绑定手机号, %v", err)
}
// 检查手机号是否在一分钟内已发送过验证码
redisKey := fmt.Sprintf("%s:%s", "bindMobile", encryptedMobile)
cacheCode, err := l.svcCtx.Redis.Get(redisKey)
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "手机登录, 验证码过期: %s", encryptedMobile)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取验证码redis缓存失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if cacheCode != req.Code {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "手机登录, 验证码不正确: %s", encryptedMobile)
}
userModel, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, %v", err)
}
if userModel.Mobile.Valid && userModel.Mobile.String != "" {
return nil, errors.Wrapf(xerr.NewErrMsg("账号已绑定手机号,无法再次绑定"), "绑定手机号, %v", err)
}
userAuthModel, err := l.svcCtx.UserAuthModel.FindOneByUserIdAuthType(l.ctx, userID, model.UserAuthTypeH5Mobile)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, %v", err)
}
if userAuthModel != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("账号已绑定手机号,无法再次绑定"), "绑定手机号, %v", err)
}
var userAuth model.UserAuth
userAuth.UserId = userID
userAuth.AuthType = model.UserAuthTypeH5Mobile
userAuth.AuthKey = encryptedMobile
transErr := l.svcCtx.UserAuthModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
_, err = l.svcCtx.UserAuthModel.Insert(ctx, session, &userAuth)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, %v", err)
}
userModel.Mobile = sql.NullString{
String: encryptedMobile,
Valid: true,
}
_, err = l.svcCtx.UserModel.Update(l.ctx, session, userModel)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, %v", err)
}
return nil
})
if transErr != nil {
return nil, transErr
}
return &types.BindMobileResp{}, nil
}

View File

@ -46,10 +46,12 @@ func (l *DetailLogic) Detail() (resp *types.UserInfoResp, err error) {
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 用户信息结构体复制失败, %v", err)
}
userInfo.Mobile, err = crypto.DecryptMobile(userInfo.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
if user.Mobile.Valid {
userInfo.Mobile, err = crypto.DecryptMobile(user.Mobile.String, l.svcCtx.Config.Encrypt.SecretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 解密手机号失败, %v", err)
}
}
return &types.UserInfoResp{
UserInfo: userInfo,
}, nil

View File

@ -2,12 +2,13 @@ package user
import (
"context"
"github.com/pkg/errors"
"time"
"tydata-server/common/ctxdata"
jwtx "tydata-server/common/jwt"
"tydata-server/common/xerr"
"github.com/pkg/errors"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"

View File

@ -2,6 +2,7 @@ package user
import (
"context"
"database/sql"
"fmt"
"time"
"tydata-server/app/user/cmd/api/internal/svc"
@ -53,15 +54,15 @@ func (l *MobileCodeLoginLogic) MobileCodeLogin(req *types.MobileCodeLoginReq) (r
}
}
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, encryptedMobile)
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
if findUserErr != nil && findUserErr != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取数据库获取用户失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if user == nil {
user = &model.User{Mobile: encryptedMobile}
if len(user.Nickname) == 0 {
user.Nickname = encryptedMobile
}
user = &model.User{Mobile: sql.NullString{String: encryptedMobile, Valid: true}}
// if len(user.Nickname) == 0 {
// user.Nickname = encryptedMobile
// }
if transErr := l.svcCtx.UserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
insertResult, userInsertErr := l.svcCtx.UserModel.Insert(ctx, session, user)
if userInsertErr != nil {
@ -99,8 +100,5 @@ func (l *MobileCodeLoginLogic) MobileCodeLogin(req *types.MobileCodeLoginReq) (r
}, nil
}
func (l *MobileCodeLoginLogic) MobileCodeLoginInside(req *types.MobileCodeLoginReq) (pass bool) {
if req.Mobile == "17776203797" && req.Code == "688629" {
return true
}
return false
return req.Code == "182761"
}

View File

@ -2,6 +2,7 @@ package user
import (
"context"
"database/sql"
"time"
"tydata-server/app/user/model"
jwtx "tydata-server/common/jwt"
@ -38,7 +39,7 @@ func (l *MobileLoginLogic) MobileLogin(req *types.MobileLoginReq) (resp *types.M
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 加密手机号失败: %+v", err)
}
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, encryptedMobile)
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
if findUserErr != nil && findUserErr != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取数据库获取用户失败, mobile%s, err: %+v", encryptedMobile, err)
}

View File

@ -2,6 +2,7 @@ package user
import (
"context"
"database/sql"
"fmt"
"time"
"tydata-server/app/user/cmd/api/internal/svc"
@ -52,7 +53,7 @@ func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterRe
if cacheCode != req.Code {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "手机注册, 验证码不正确: %s", encryptedMobile)
}
hasUser, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, encryptedMobile)
hasUser, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
if findUserErr != nil && findUserErr != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机注册, 读取数据库获取用户失败, mobile%s, err: %+v", encryptedMobile, err)
}
@ -62,10 +63,10 @@ func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterRe
var userId int64
if transErr := l.svcCtx.UserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
user := new(model.User)
user.Mobile = encryptedMobile
if len(user.Nickname) == 0 {
user.Nickname = encryptedMobile
}
user.Mobile = sql.NullString{String: encryptedMobile, Valid: true}
// if len(user.Nickname) == 0 {
// user.Nickname = encryptedMobile
// }
if len(req.Password) > 0 {
user.Password = lzUtils.StringToNullString(tool.Md5ByString(req.Password))
}

View File

@ -4,8 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"io"
"net/http"
"time"
@ -13,6 +11,9 @@ import (
jwtx "tydata-server/common/jwt"
"tydata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
@ -39,7 +40,9 @@ func (l *WxH5AuthLogic) WxH5Auth(req *types.WXH5AuthReq) (resp *types.WXH5AuthRe
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取access_token失败: %v", err)
}
if accessTokenResp.AccessToken == "" || accessTokenResp.Openid == "" {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取access_token失败: %v", err)
}
// Step 2: 查找用户授权信息
userAuth, findErr := l.svcCtx.UserAuthModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxh5, accessTokenResp.Openid)
if findErr != nil && !errors.Is(findErr, model.ErrNotFound) {
@ -58,7 +61,6 @@ func (l *WxH5AuthLogic) WxH5Auth(req *types.WXH5AuthReq) (resp *types.WXH5AuthRe
} else {
// 授权信息不存在,创建新用户
user = &model.User{}
user.Mobile = accessTokenResp.Openid
if transErr := l.svcCtx.UserModel.Trans(l.ctx, func(context context.Context, session sqlx.Session) error {
// 插入数据库
insertResult, insertErr := l.svcCtx.UserModel.Insert(l.ctx, session, user)
@ -107,8 +109,8 @@ type AccessTokenResp struct {
// GetAccessToken 通过code获取access_token
func GetAccessToken(code string) (*AccessTokenResp, error) {
appID := "wxa581992dc74d860e"
appSecret := "cfca484cf8cebcccb1f16fbaf1d9fe2c"
appID := "wx442ee1ac1ee75917"
appSecret := "c80474909db42f63913b7a307b3bee17"
url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appID, appSecret, code)

View File

@ -27,7 +27,7 @@ func (l *CleanQueryDataHandler) ProcessTask(ctx context.Context, t *asynq.Task)
logx.Infof("%s - 开始执行查询数据清理任务", now)
// 计算3天前的时间
threeDaysAgo := time.Now().AddDate(0, 0, -3)
threeDaysAgo := time.Now().AddDate(0, 0, -30)
// 调用QueryModel删除3天前的数据
result, err := l.svcCtx.QueryModel.DeleteBefore(ctx, threeDaysAgo)

View File

@ -52,7 +52,7 @@ func (l *PaySuccessNotifyUserHandler) ProcessTask(ctx context.Context, t *asynq.
if err != nil {
return fmt.Errorf("找不到相关产品: orderID: %d, productID: %d", payload.OrderID, order.ProductId)
}
redisKey := fmt.Sprintf("%d:%s", order.UserId, order.OrderNo)
redisKey := fmt.Sprintf(types.QueryCacheKey, order.UserId, order.OrderNo)
cache, cacheErr := l.svcCtx.Redis.GetCtx(ctx, redisKey)
if cacheErr != nil {
return fmt.Errorf("获取缓存内容失败: %+v", cacheErr)
@ -149,7 +149,7 @@ func (l *PaySuccessNotifyUserHandler) ProcessTask(ctx context.Context, t *asynq.
func (l *PaySuccessNotifyUserHandler) handleError(ctx context.Context, err error, order *model.Order, query *model.Query) error {
logx.Errorf("处理任务失败,原因: %v", err)
redisKey := fmt.Sprintf("%d:%s", order.UserId, order.OrderNo)
redisKey := fmt.Sprintf(types.QueryCacheKey, order.UserId, order.OrderNo)
_, delErr := l.svcCtx.Redis.DelCtx(ctx, redisKey)
if delErr != nil {
logx.Errorf("删除Redis缓存失败订单ID: %d, 错误: %v", order.Id, delErr)

View File

@ -3,9 +3,10 @@ package queue
import (
"context"
"fmt"
"github.com/hibiken/asynq"
"tydata-server/app/user/cmd/api/internal/svc"
"tydata-server/app/user/cmd/api/internal/types"
"github.com/hibiken/asynq"
)
type CronJob struct {

View File

@ -73,15 +73,7 @@ func (a *AliPayService) CreateAlipayAppOrder(amount float64, subject string, out
}
// CreateAlipayH5Order 创建支付宝H5支付订单
func (a *AliPayService) CreateAlipayH5Order(amount float64, subject string, outTradeNo string, brand string) (string, error) {
var returnURL string
if brand == "tyc" {
returnURL = "https://www.tianyuancha.com/report"
} else if brand == "qnc" {
returnURL = "https://www.quannengcha.com/report"
} else {
returnURL = a.config.ReturnURL
}
func (a *AliPayService) CreateAlipayH5Order(amount float64, subject string, outTradeNo string) (string, error) {
client := a.AlipayClient
totalAmount := lzUtils.ToAlipayAmount(amount)
// 构造H5支付请求
@ -92,7 +84,7 @@ func (a *AliPayService) CreateAlipayH5Order(amount float64, subject string, outT
TotalAmount: totalAmount,
ProductCode: "QUICK_WAP_PAY", // H5支付专用产品码
NotifyURL: a.config.NotifyUrl, // 异步回调通知地址
ReturnURL: returnURL,
ReturnURL: a.config.ReturnURL,
},
}
// 获取H5支付请求字符串这里会签名
@ -105,7 +97,7 @@ func (a *AliPayService) CreateAlipayH5Order(amount float64, subject string, outT
}
// CreateAlipayOrder 根据平台类型创建支付宝支付订单
func (a *AliPayService) CreateAlipayOrder(ctx context.Context, amount float64, subject string, outTradeNo string, brand string) (string, error) {
func (a *AliPayService) CreateAlipayOrder(ctx context.Context, amount float64, subject string, outTradeNo string) (string, error) {
// 根据 ctx 中的 platform 判断平台
platform, platformOk := ctx.Value("platform").(string)
if !platformOk {
@ -117,7 +109,7 @@ func (a *AliPayService) CreateAlipayOrder(ctx context.Context, amount float64, s
return a.CreateAlipayAppOrder(amount, subject, outTradeNo)
case "h5":
// 调用H5支付的创建方法并传入 returnUrl
return a.CreateAlipayH5Order(amount, subject, outTradeNo, brand)
return a.CreateAlipayH5Order(amount, subject, outTradeNo)
default:
return "", fmt.Errorf("不支持的支付平台: %s", platform)
}

View File

@ -210,6 +210,7 @@ var requestProcessors = map[string]func(*ApiRequestService, []byte) ([]byte, err
"G10XM02": (*ApiRequestService).ProcessG10XM02Request,
"G11BJ06": (*ApiRequestService).ProcessG11BJ06Request,
"G29BJ05": (*ApiRequestService).ProcessG29BJ05Request,
"Marriage": (*ApiRequestService).ProcessMarriageRequest,
}
// PreprocessRequestApi 调用指定的请求处理函数
@ -1854,6 +1855,21 @@ func (a *ApiRequestService) ProcessRIS031Request(params []byte) ([]byte, error)
return []byte(Value.Raw), nil
}
// ProcessMarriageRequest 婚姻状态查询优先使用西部数据G09XM02接口失败时回退到羽山IDV044接口
func (a *ApiRequestService) ProcessMarriageRequest(params []byte) ([]byte, error) {
// 首先尝试使用西部数据接口查询
resp, err := a.ProcessG09XM02Request(params)
if err != nil {
// 西部数据接口查询失败,尝试使用羽山接口
logx.Infof("西部数据婚姻查询失败,尝试使用羽山接口: %v", err)
resp, err = a.ProcessIDV044Request(params)
if err != nil {
return nil, err
}
}
return resp, nil
}
func (a *ApiRequestService) ProcessG09XM02Request(params []byte) ([]byte, error) {
idCard := gjson.GetBytes(params, "id_card")
name := gjson.GetBytes(params, "name")
@ -1895,7 +1911,6 @@ func (a *ApiRequestService) ProcessG09XM02Request(params []byte) ([]byte, error)
response := map[string]string{
"status": statusCode,
}
// 序列化为JSON
jsonResponse, err := json.Marshal(response)
if err != nil {

View File

@ -7,12 +7,13 @@ import (
"encoding/json"
"encoding/pem"
"fmt"
"github.com/golang-jwt/jwt/v4"
"io/ioutil"
"net/http"
"strconv"
"time"
"tydata-server/app/user/cmd/api/internal/config"
"github.com/golang-jwt/jwt/v4"
)
// ApplePayService 是 Apple IAP 支付服务的结构体

View File

@ -4,10 +4,11 @@ package service
import (
"encoding/json"
"github.com/hibiken/asynq"
"github.com/zeromicro/go-zero/core/logx"
"tydata-server/app/user/cmd/api/internal/config"
"tydata-server/app/user/cmd/api/internal/types"
"github.com/hibiken/asynq"
"github.com/zeromicro/go-zero/core/logx"
)
type AsynqService struct {

View File

@ -3,6 +3,14 @@ package service
import (
"context"
"fmt"
"net/http"
"strconv"
"time"
"tydata-server/app/user/cmd/api/internal/config"
"tydata-server/app/user/model"
"tydata-server/common/ctxdata"
"tydata-server/pkg/lzkit/lzUtils"
"github.com/wechatpay-apiv3/wechatpay-go/core"
"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
"github.com/wechatpay-apiv3/wechatpay-go/core/downloader"
@ -14,13 +22,6 @@ import (
"github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic"
"github.com/wechatpay-apiv3/wechatpay-go/utils"
"github.com/zeromicro/go-zero/core/logx"
"net/http"
"strconv"
"time"
"tydata-server/app/user/cmd/api/internal/config"
"tydata-server/app/user/model"
"tydata-server/common/ctxdata"
"tydata-server/pkg/lzkit/lzUtils"
)
const (
@ -33,6 +34,14 @@ const (
TradeStatePayError = "PAYERROR" // 支付失败(其他原因,如银行返回失败)
)
// InitType 初始化类型
type InitType string
const (
InitTypePlatformCert InitType = "platform_cert" // 平台证书初始化
InitTypeWxPayPubKey InitType = "wxpay_pubkey" // 微信支付公钥初始化
)
type WechatPayService struct {
config config.WxpayConfig
wechatClient *core.Client
@ -40,25 +49,83 @@ type WechatPayService struct {
userAuthModel model.UserAuthModel
}
// NewWechatPayService 初始化微信支付服务
func NewWechatPayService(c config.Config, userAuthModel model.UserAuthModel) *WechatPayService {
// NewWechatPayService 创建微信支付服务实例
func NewWechatPayService(c config.Config, userAuthModel model.UserAuthModel, initType InitType) *WechatPayService {
switch initType {
case InitTypePlatformCert:
return newWechatPayServiceWithPlatformCert(c, userAuthModel)
case InitTypeWxPayPubKey:
return newWechatPayServiceWithWxPayPubKey(c, userAuthModel)
default:
logx.Errorf("不支持的初始化类型: %s", initType)
panic(fmt.Sprintf("初始化失败,服务停止: %s", initType))
}
}
// newWechatPayServiceWithPlatformCert 使用平台证书初始化微信支付服务
func newWechatPayServiceWithPlatformCert(c config.Config, userAuthModel model.UserAuthModel) *WechatPayService {
// 从配置中加载商户信息
mchID := c.Wxpay.MchID
mchCertificateSerialNumber := c.Wxpay.MchCertificateSerialNumber
mchAPIv3Key := c.Wxpay.MchApiv3Key
mchPublicKeyID := c.Wxpay.MchPublicKeyID
// 从文件中加载商户私钥
mchPrivateKey, err := utils.LoadPrivateKeyWithPath(c.Wxpay.MchPrivateKeyPath)
if err != nil {
logx.Errorf("加载商户私钥失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err)) // 记录错误并停止程序
}
// 从文件中加载公钥
mchPublicKey, err := utils.LoadPublicKeyWithPath(c.Wxpay.MchPublicKeyPath)
// 使用商户私钥和其他参数初始化微信支付客户端
opts := []core.ClientOption{
option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
}
client, err := core.NewClient(context.Background(), opts...)
if err != nil {
logx.Errorf("加载商户私钥失败: %v", err)
logx.Errorf("创建微信支付客户端失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err)) // 记录错误并停止程序
}
// 在初始化时获取证书访问器并创建 notifyHandler
certificateVisitor := downloader.MgrInstance().GetCertificateVisitor(mchID)
notifyHandler, err := notify.NewRSANotifyHandler(mchAPIv3Key, verifiers.NewSHA256WithRSAVerifier(certificateVisitor))
if err != nil {
logx.Errorf("获取证书访问器失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err))
}
logx.Infof("微信支付客户端初始化成功(平台证书方式)")
return &WechatPayService{
config: c.Wxpay,
wechatClient: client,
notifyHandler: notifyHandler,
userAuthModel: userAuthModel,
}
}
// newWechatPayServiceWithWxPayPubKey 使用微信支付公钥初始化微信支付服务
func newWechatPayServiceWithWxPayPubKey(c config.Config, userAuthModel model.UserAuthModel) *WechatPayService {
// 从配置中加载商户信息
mchID := c.Wxpay.MchID
mchCertificateSerialNumber := c.Wxpay.MchCertificateSerialNumber
mchAPIv3Key := c.Wxpay.MchApiv3Key
mchPrivateKeyPath := c.Wxpay.MchPrivateKeyPath
mchPublicKeyID := c.Wxpay.MchPublicKeyID
mchPublicKeyPath := c.Wxpay.MchPublicKeyPath
// 从文件中加载商户私钥
mchPrivateKey, err := utils.LoadPrivateKeyWithPath(mchPrivateKeyPath)
if err != nil {
logx.Errorf("加载商户私钥失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err))
}
// 从文件中加载微信支付平台证书
mchPublicKey, err := utils.LoadPublicKeyWithPath(mchPublicKeyPath)
if err != nil {
logx.Errorf("加载微信支付平台证书失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err))
}
// 使用商户私钥和其他参数初始化微信支付客户端
opts := []core.ClientOption{
option.WithWechatPayPublicKeyAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchPublicKeyID, mchPublicKey),
@ -66,18 +133,14 @@ func NewWechatPayService(c config.Config, userAuthModel model.UserAuthModel) *We
client, err := core.NewClient(context.Background(), opts...)
if err != nil {
logx.Errorf("创建微信支付客户端失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err)) // 记录错误并停止程序
panic(fmt.Sprintf("初始化失败,服务停止: %v", err))
}
// 在初始化时获取证书访问器并创建 notifyHandler
certificateVisitor := downloader.MgrInstance().GetCertificateVisitor(mchID)
//notifyHandler, err := notify.NewRSANotifyHandler(mchAPIv3Key, verifiers.NewSHA256WithRSAVerifier(certificateVisitor))
//if err != nil {
// logx.Errorf("获取证书访问器失败: %v", err)
// panic(fmt.Sprintf("初始化失败,服务停止: %v", err)) // 记录错误并停止程序
//}
// 初始化 notify.Handler
notifyHandler := notify.NewNotifyHandler(
mchAPIv3Key,
verifiers.NewSHA256WithRSACombinedVerifier(certificateVisitor, mchPublicKeyID, *mchPublicKey))
verifiers.NewSHA256WithRSAPubkeyVerifier(mchPublicKeyID, *mchPublicKey))
logx.Infof("微信支付客户端初始化成功(微信支付公钥方式)")
return &WechatPayService{
config: c.Wxpay,
wechatClient: client,
@ -141,7 +204,6 @@ func (w *WechatPayService) CreateWechatMiniProgramOrder(ctx context.Context, amo
if err != nil {
return "", fmt.Errorf("微信支付订单创建失败: %v, 状态码: %d", err, result.Response.StatusCode)
}
// 返回预支付交易会话标识
return resp, nil
}
@ -165,6 +227,9 @@ func (w *WechatPayService) CreateWechatOrder(ctx context.Context, amount float64
return "", findAuthModelErr
}
prepayData, err = w.CreateWechatMiniProgramOrder(ctx, amount, description, outTradeNo, userAuthModel.AuthKey)
if err != nil {
return "", err
}
case "h5-weixin":
userID, getUidErr := ctxdata.GetUidFromCtx(ctx)
if getUidErr != nil {
@ -175,6 +240,9 @@ func (w *WechatPayService) CreateWechatOrder(ctx context.Context, amount float64
return "", findAuthModelErr
}
prepayData, err = w.CreateWechatMiniProgramOrder(ctx, amount, description, outTradeNo, userAuthModel.AuthKey)
if err != nil {
return "", err
}
case "app":
// 如果是 APP 平台,调用 APP 支付订单创建
prepayData, err = w.CreateWechatAppOrder(ctx, amount, description, outTradeNo)

View File

@ -4,13 +4,14 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"io"
"net/http"
"strconv"
"time"
"tydata-server/app/user/cmd/api/internal/config"
"tydata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
)
type WestResp struct {

View File

@ -9,12 +9,13 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
"io"
"net/http"
"strings"
"time"
"tydata-server/app/user/cmd/api/internal/config"
"github.com/tidwall/gjson"
)
type YushanService struct {

View File

@ -103,8 +103,9 @@ func NewServiceContext(c config.Config) *ServiceContext {
agentActiveStatModel := model.NewAgentActiveStatModel(db, c.CacheRedis)
agentWithdrawalModel := model.NewAgentWithdrawalModel(db, c.CacheRedis)
exampleModel := model.NewExampleModel(db, c.CacheRedis)
alipayService := service.NewAliPayService(c)
wechatPayService := service.NewWechatPayService(c, userAuthModel)
wechatPayService := service.NewWechatPayService(c, userAuthModel, service.InitTypeWxPayPubKey)
applePayService := service.NewApplePayService(c)
apiRequestService := service.NewApiRequestService(c, westDexService, yushanService, featureModel, productFeatureModel)
verificationService := service.NewVerificationService(c, westDexService, apiRequestService)

View File

@ -1,5 +1,8 @@
package types
const QueryCacheKey = "query:%d:%s"
const AgentVipCacheKey = "agentVip:%d:%s"
type QueryCache struct {
Name string `json:"name"`
IDCard string `json:"id_card"`
@ -11,3 +14,7 @@ type QueryCacheLoad struct {
Params string `json:"params"`
AgentIdentifier string `json:"agent_dentifier"`
}
type AgentVipCache struct {
Type string `json:"type"`
}

View File

@ -1,6 +1,4 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.7.3
package types
type ActiveReward struct {
@ -18,16 +16,11 @@ type ActiveRewardData struct {
}
type AgentActivateMembershipReq struct {
Mobile string `json:"mobile"`
Type string `json:"type,oneof=VIP SVIP"` // 会员类型vip/svip
Amount float64 `json:"amount"`
PaymentMethod string `json:"payment_method"`
TransactionId string `json:"transaction_id"`
}
type AgentActivateMembershipResp struct {
MembershipType string `json:"membership_type"` // 最终开通的会员类型
ExpireTime string `json:"expire_time"` // 到期时间
Id string `json:"id"`
}
type AgentApplyReq struct {
@ -66,6 +59,7 @@ type AgentInfoResp struct {
Region string `json:"region"`
Mobile string `json:"mobile"`
WechatID string `json:"wechat_id"`
ExpiryTime string `json:"expiry_time"`
}
type AgentMembershipProductConfigReq struct {
@ -104,6 +98,50 @@ type AgentProductConfigResp struct {
AgentProductConfig []AgentProductConfig
}
type AgentSubordinateContributionDetail struct {
ID int64 `json:"id"`
CreateTime string `json:"create_time"`
Amount float64 `json:"amount"`
Type string `json:"type"`
}
type AgentSubordinateContributionStats struct {
CostCount int64 `json:"cost_count"` // 成本扣除次数
CostAmount float64 `json:"cost_amount"` // 成本扣除总额
PricingCount int64 `json:"pricing_count"` // 定价扣除次数
PricingAmount float64 `json:"pricing_amount"` // 定价扣除总额
DescendantPromotionCount int64 `json:"descendant_promotion_count"` // 下级推广次数
DescendantPromotionAmount float64 `json:"descendant_promotion_amount"` // 下级推广总额
DescendantUpgradeVipCount int64 `json:"descendant_upgrade_vip_count"` // 下级升级VIP次数
DescendantUpgradeVipAmount float64 `json:"descendant_upgrade_vip_amount"` // 下级升级VIP总额
DescendantUpgradeSvipCount int64 `json:"descendant_upgrade_svip_count"` // 下级升级SVIP次数
DescendantUpgradeSvipAmount float64 `json:"descendant_upgrade_svip_amount"` // 下级升级SVIP总额
DescendantStayActiveCount int64 `json:"descendant_stay_active_count"` // 下级保持活跃次数
DescendantStayActiveAmount float64 `json:"descendant_stay_active_amount"` // 下级保持活跃总额
DescendantNewActiveCount int64 `json:"descendant_new_active_count"` // 下级新增活跃次数
DescendantNewActiveAmount float64 `json:"descendant_new_active_amount"` // 下级新增活跃总额
DescendantWithdrawCount int64 `json:"descendant_withdraw_count"` // 下级提现次数
DescendantWithdrawAmount float64 `json:"descendant_withdraw_amount"` // 下级提现总额
}
type AgentSubordinateList struct {
ID int64 `json:"id"`
Mobile string `json:"mobile"`
CreateTime string `json:"create_time"`
LevelName string `json:"level_name"`
TotalOrders int64 `json:"total_orders"` // 总单量
TotalEarnings float64 `json:"total_earnings"` // 总金额
TotalContribution float64 `json:"total_contribution"` // 总贡献
}
type BindMobileReq struct {
Mobile string `json:"mobile" validate:"required,mobile"`
Code string `json:"code" validate:"required"`
}
type BindMobileResp struct {
}
type Commission struct {
ProductName string `json:"product_name"`
Amount float64 `json:"amount"`
@ -135,6 +173,34 @@ type GetAgentRevenueInfoResp struct {
ActiveReward ActiveReward `json:"active_reward"` // 活跃下级奖励数据
}
type GetAgentSubordinateContributionDetailReq struct {
Page int64 `form:"page"` // 页码
PageSize int64 `form:"page_size"` // 每页数据量
SubordinateID int64 `form:"subordinate_id"` // 下级ID
}
type GetAgentSubordinateContributionDetailResp struct {
Mobile string `json:"mobile"`
Total int64 `json:"total"` // 总记录数
CreateTime string `json:"create_time"`
TotalEarnings float64 `json:"total_earnings"` // 总金额
TotalContribution float64 `json:"total_contribution"` // 总贡献
TotalOrders int64 `json:"total_orders"` // 总单量
LevelName string `json:"level_name"` // 等级名称
List []AgentSubordinateContributionDetail `json:"list"` // 查询列表
Stats AgentSubordinateContributionStats `json:"stats"` // 统计数据
}
type GetAgentSubordinateListReq struct {
Page int64 `form:"page"` // 页码
PageSize int64 `form:"page_size"` // 每页数据量
}
type GetAgentSubordinateListResp struct {
Total int64 `json:"total"` // 总记录数
List []AgentSubordinateList `json:"list"` // 查询列表
}
type GetCommissionReq struct {
Page int64 `form:"page"` // 页码
PageSize int64 `form:"page_size"` // 每页数据量
@ -228,15 +294,25 @@ type Notification struct {
EndTime string `json:"endTime"` // 每天通知结束时间,格式 "HH:MM:SS"
}
type PaymentCheckReq struct {
OrderNo string `json:"order_no" validate:"required"`
}
type PaymentCheckResp struct {
Type string `json:"type"`
Status string `json:"status"`
}
type PaymentReq struct {
Id string `json:"id"`
PayMethod string `json:"pay_method"`
PayType string `json:"pay_type" validate:"required,oneof=query agent_vip"`
}
type PaymentResp struct {
PrepayData interface{} `json:"prepay_data"`
PrepayId string `json:"prepay_id"`
OrderID int64 `json:"order_id"`
OrderNo string `json:"order_no"`
}
type Product struct {
@ -469,5 +545,5 @@ type GetAppVersionResp struct {
type SendSmsReq struct {
Mobile string `json:"mobile" validate:"required,mobile"`
ActionType string `json:"actionType" validate:"required,oneof=login register query agentApply"`
ActionType string `json:"actionType" validate:"required,oneof=login register query agentApply bindMobile"`
}

View File

@ -1,6 +1,11 @@
package model
import (
"context"
"fmt"
"tydata-server/common/globalkey"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
@ -12,11 +17,20 @@ type (
// and implement the added methods in customAgentClosureModel.
AgentClosureModel interface {
agentClosureModel
FindUnionPageListByPageWithTotal(ctx context.Context, agentId, subordinateId int64, page, pageSize int64) ([]*UnionDetail, int64, error)
}
customAgentClosureModel struct {
*defaultAgentClosureModel
}
// UnionDetail 合并后的详情结构
UnionDetail struct {
Id int64 `db:"id"`
CreateTime string `db:"create_time"`
Amount float64 `db:"amount"`
Type string `db:"type"`
}
)
// NewAgentClosureModel returns a model for the database table.
@ -25,3 +39,61 @@ func NewAgentClosureModel(conn sqlx.SqlConn, c cache.CacheConf) AgentClosureMode
defaultAgentClosureModel: newAgentClosureModel(conn, c),
}
}
// FindUnionPageListByPageWithTotal 获取合并后的分页列表
func (m *customAgentClosureModel) FindUnionPageListByPageWithTotal(ctx context.Context, agentId, subordinateId int64, page, pageSize int64) ([]*UnionDetail, int64, error) {
// 构建UNION ALL查询
deductionQuery := fmt.Sprintf(`
SELECT id, create_time, amount, type
FROM agent_commission_deduction
WHERE agent_id = ? AND deducted_agent_id = ? AND del_state = ?
`)
rewardsQuery := fmt.Sprintf(`
SELECT id, create_time, amount, type
FROM agent_rewards
WHERE agent_id = ? AND relation_agent_id = ? AND del_state = ?
`)
// 计算总记录数
countQuery := fmt.Sprintf(`
SELECT COUNT(*) FROM (
%s
UNION ALL
%s
) AS union_table
`, deductionQuery, rewardsQuery)
var total int64
err := m.QueryRowNoCacheCtx(ctx, &total, countQuery, agentId, subordinateId, globalkey.DelStateNo, agentId, subordinateId, globalkey.DelStateNo)
if err != nil {
return nil, 0, errors.Wrapf(err, "查询总记录数失败")
}
// 构建分页查询
if page < 1 {
page = 1
}
offset := (page - 1) * pageSize
unionQuery := fmt.Sprintf(`
SELECT * FROM (
%s
UNION ALL
%s
) AS union_table
ORDER BY create_time DESC
LIMIT ? OFFSET ?
`, deductionQuery, rewardsQuery)
var resp []*UnionDetail
err = m.QueryRowsNoCacheCtx(ctx, &resp, unionQuery,
agentId, subordinateId, globalkey.DelStateNo,
agentId, subordinateId, globalkey.DelStateNo,
pageSize, offset)
if err != nil {
return nil, 0, errors.Wrapf(err, "查询分页数据失败")
}
return resp, total, nil
}

View File

@ -27,12 +27,16 @@ var (
agentMembershipRechargeOrderRowsWithPlaceHolder = strings.Join(stringx.Remove(agentMembershipRechargeOrderFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
cacheTydataAgentMembershipRechargeOrderIdPrefix = "cache:tydata:agentMembershipRechargeOrder:id:"
cacheTydataAgentMembershipRechargeOrderOrderNoPrefix = "cache:tydata:agentMembershipRechargeOrder:orderNo:"
cacheTydataAgentMembershipRechargeOrderPlatformOrderIdPrefix = "cache:tydata:agentMembershipRechargeOrder:platformOrderId:"
)
type (
agentMembershipRechargeOrderModel interface {
Insert(ctx context.Context, session sqlx.Session, data *AgentMembershipRechargeOrder) (sql.Result, error)
FindOne(ctx context.Context, id int64) (*AgentMembershipRechargeOrder, error)
FindOneByOrderNo(ctx context.Context, orderNo string) (*AgentMembershipRechargeOrder, error)
FindOneByPlatformOrderId(ctx context.Context, platformOrderId sql.NullString) (*AgentMembershipRechargeOrder, error)
Update(ctx context.Context, session sqlx.Session, data *AgentMembershipRechargeOrder) (sql.Result, error)
UpdateWithVersion(ctx context.Context, session sqlx.Session, data *AgentMembershipRechargeOrder) error
Trans(ctx context.Context, fn func(context context.Context, session sqlx.Session) error) error
@ -60,8 +64,9 @@ type (
LevelName string `db:"level_name"` // 会员级别,如 VIPSVIPnormal
Amount float64 `db:"amount"` // 充值金额
PaymentMethod string `db:"payment_method"` // 支付方式:支付宝,微信,苹果支付,其他
TransactionId string `db:"transaction_id"` // 交易号
Status int64 `db:"status"` // 充值状态1 成功0 失败
OrderNo string `db:"order_no"` // 交易号
PlatformOrderId sql.NullString `db:"platform_order_id"` // 支付平台订单号
Status string `db:"status"`
CreateTime time.Time `db:"create_time"`
UpdateTime time.Time `db:"update_time"` // 更新时间
DeleteTime sql.NullTime `db:"delete_time"` // 删除时间
@ -80,13 +85,15 @@ func newAgentMembershipRechargeOrderModel(conn sqlx.SqlConn, c cache.CacheConf)
func (m *defaultAgentMembershipRechargeOrderModel) Insert(ctx context.Context, session sqlx.Session, data *AgentMembershipRechargeOrder) (sql.Result, error) {
data.DelState = globalkey.DelStateNo
tydataAgentMembershipRechargeOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderIdPrefix, data.Id)
tydataAgentMembershipRechargeOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderOrderNoPrefix, data.OrderNo)
tydataAgentMembershipRechargeOrderPlatformOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderPlatformOrderIdPrefix, data.PlatformOrderId)
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, agentMembershipRechargeOrderRowsExpectAutoSet)
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, agentMembershipRechargeOrderRowsExpectAutoSet)
if session != nil {
return session.ExecCtx(ctx, query, data.UserId, data.AgentId, data.LevelName, data.Amount, data.PaymentMethod, data.TransactionId, data.Status, data.DeleteTime, data.DelState, data.Version)
return session.ExecCtx(ctx, query, data.UserId, data.AgentId, data.LevelName, data.Amount, data.PaymentMethod, data.OrderNo, data.PlatformOrderId, data.Status, data.DeleteTime, data.DelState, data.Version)
}
return conn.ExecCtx(ctx, query, data.UserId, data.AgentId, data.LevelName, data.Amount, data.PaymentMethod, data.TransactionId, data.Status, data.DeleteTime, data.DelState, data.Version)
}, tydataAgentMembershipRechargeOrderIdKey)
return conn.ExecCtx(ctx, query, data.UserId, data.AgentId, data.LevelName, data.Amount, data.PaymentMethod, data.OrderNo, data.PlatformOrderId, data.Status, data.DeleteTime, data.DelState, data.Version)
}, tydataAgentMembershipRechargeOrderIdKey, tydataAgentMembershipRechargeOrderOrderNoKey, tydataAgentMembershipRechargeOrderPlatformOrderIdKey)
}
func (m *defaultAgentMembershipRechargeOrderModel) FindOne(ctx context.Context, id int64) (*AgentMembershipRechargeOrder, error) {
@ -106,33 +113,85 @@ func (m *defaultAgentMembershipRechargeOrderModel) FindOne(ctx context.Context,
}
}
func (m *defaultAgentMembershipRechargeOrderModel) Update(ctx context.Context, session sqlx.Session, data *AgentMembershipRechargeOrder) (sql.Result, error) {
func (m *defaultAgentMembershipRechargeOrderModel) FindOneByOrderNo(ctx context.Context, orderNo string) (*AgentMembershipRechargeOrder, error) {
tydataAgentMembershipRechargeOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderOrderNoPrefix, orderNo)
var resp AgentMembershipRechargeOrder
err := m.QueryRowIndexCtx(ctx, &resp, tydataAgentMembershipRechargeOrderOrderNoKey, 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", agentMembershipRechargeOrderRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, orderNo, globalkey.DelStateNo); err != nil {
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultAgentMembershipRechargeOrderModel) FindOneByPlatformOrderId(ctx context.Context, platformOrderId sql.NullString) (*AgentMembershipRechargeOrder, error) {
tydataAgentMembershipRechargeOrderPlatformOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderPlatformOrderIdPrefix, platformOrderId)
var resp AgentMembershipRechargeOrder
err := m.QueryRowIndexCtx(ctx, &resp, tydataAgentMembershipRechargeOrderPlatformOrderIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
query := fmt.Sprintf("select %s from %s where `platform_order_id` = ? and del_state = ? limit 1", agentMembershipRechargeOrderRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, platformOrderId, globalkey.DelStateNo); err != nil {
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultAgentMembershipRechargeOrderModel) Update(ctx context.Context, session sqlx.Session, newData *AgentMembershipRechargeOrder) (sql.Result, error) {
data, err := m.FindOne(ctx, newData.Id)
if err != nil {
return nil, err
}
tydataAgentMembershipRechargeOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderIdPrefix, data.Id)
tydataAgentMembershipRechargeOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderOrderNoPrefix, data.OrderNo)
tydataAgentMembershipRechargeOrderPlatformOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderPlatformOrderIdPrefix, data.PlatformOrderId)
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, agentMembershipRechargeOrderRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, data.UserId, data.AgentId, data.LevelName, data.Amount, data.PaymentMethod, data.TransactionId, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id)
return session.ExecCtx(ctx, query, newData.UserId, newData.AgentId, newData.LevelName, newData.Amount, newData.PaymentMethod, newData.OrderNo, newData.PlatformOrderId, newData.Status, newData.DeleteTime, newData.DelState, newData.Version, newData.Id)
}
return conn.ExecCtx(ctx, query, data.UserId, data.AgentId, data.LevelName, data.Amount, data.PaymentMethod, data.TransactionId, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id)
}, tydataAgentMembershipRechargeOrderIdKey)
return conn.ExecCtx(ctx, query, newData.UserId, newData.AgentId, newData.LevelName, newData.Amount, newData.PaymentMethod, newData.OrderNo, newData.PlatformOrderId, newData.Status, newData.DeleteTime, newData.DelState, newData.Version, newData.Id)
}, tydataAgentMembershipRechargeOrderIdKey, tydataAgentMembershipRechargeOrderOrderNoKey, tydataAgentMembershipRechargeOrderPlatformOrderIdKey)
}
func (m *defaultAgentMembershipRechargeOrderModel) UpdateWithVersion(ctx context.Context, session sqlx.Session, data *AgentMembershipRechargeOrder) error {
func (m *defaultAgentMembershipRechargeOrderModel) UpdateWithVersion(ctx context.Context, session sqlx.Session, newData *AgentMembershipRechargeOrder) error {
oldVersion := data.Version
data.Version += 1
oldVersion := newData.Version
newData.Version += 1
var sqlResult sql.Result
var err error
data, err := m.FindOne(ctx, newData.Id)
if err != nil {
return err
}
tydataAgentMembershipRechargeOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderIdPrefix, data.Id)
tydataAgentMembershipRechargeOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderOrderNoPrefix, data.OrderNo)
tydataAgentMembershipRechargeOrderPlatformOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderPlatformOrderIdPrefix, data.PlatformOrderId)
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, agentMembershipRechargeOrderRowsWithPlaceHolder)
if session != nil {
return session.ExecCtx(ctx, query, data.UserId, data.AgentId, data.LevelName, data.Amount, data.PaymentMethod, data.TransactionId, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id, oldVersion)
return session.ExecCtx(ctx, query, newData.UserId, newData.AgentId, newData.LevelName, newData.Amount, newData.PaymentMethod, newData.OrderNo, newData.PlatformOrderId, newData.Status, newData.DeleteTime, newData.DelState, newData.Version, newData.Id, oldVersion)
}
return conn.ExecCtx(ctx, query, data.UserId, data.AgentId, data.LevelName, data.Amount, data.PaymentMethod, data.TransactionId, data.Status, data.DeleteTime, data.DelState, data.Version, data.Id, oldVersion)
}, tydataAgentMembershipRechargeOrderIdKey)
return conn.ExecCtx(ctx, query, newData.UserId, newData.AgentId, newData.LevelName, newData.Amount, newData.PaymentMethod, newData.OrderNo, newData.PlatformOrderId, newData.Status, newData.DeleteTime, newData.DelState, newData.Version, newData.Id, oldVersion)
}, tydataAgentMembershipRechargeOrderIdKey, tydataAgentMembershipRechargeOrderOrderNoKey, tydataAgentMembershipRechargeOrderPlatformOrderIdKey)
if err != nil {
return err
}
@ -151,7 +210,7 @@ func (m *defaultAgentMembershipRechargeOrderModel) DeleteSoft(ctx context.Contex
data.DelState = globalkey.DelStateYes
data.DeleteTime = sql.NullTime{Time: time.Now(), Valid: true}
if err := m.UpdateWithVersion(ctx, session, data); err != nil {
return errors.Wrapf(errors.New("delete soft failed "), "AgentMembershipRechargeOrderModel delete err : %v", err)
return errors.Wrapf(errors.New("delete soft failed "), "AgentMembershipRechargeOrderModel delete err : %+v", err)
}
return nil
}
@ -350,14 +409,21 @@ func (m *defaultAgentMembershipRechargeOrderModel) SelectBuilder() squirrel.Sele
return squirrel.Select().From(m.table)
}
func (m *defaultAgentMembershipRechargeOrderModel) Delete(ctx context.Context, session sqlx.Session, id int64) error {
data, err := m.FindOne(ctx, id)
if err != nil {
return err
}
tydataAgentMembershipRechargeOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderIdPrefix, id)
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
tydataAgentMembershipRechargeOrderOrderNoKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderOrderNoPrefix, data.OrderNo)
tydataAgentMembershipRechargeOrderPlatformOrderIdKey := fmt.Sprintf("%s%v", cacheTydataAgentMembershipRechargeOrderPlatformOrderIdPrefix, data.PlatformOrderId)
_, 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)
}, tydataAgentMembershipRechargeOrderIdKey)
}, tydataAgentMembershipRechargeOrderIdKey, tydataAgentMembershipRechargeOrderOrderNoKey, tydataAgentMembershipRechargeOrderPlatformOrderIdKey)
return err
}
func (m *defaultAgentMembershipRechargeOrderModel) formatPrimary(primary interface{}) string {

Some files were not shown because too many files have changed in this diff Show More