first commit

This commit is contained in:
2026-03-18 00:01:48 +08:00
commit a0c623fd81
425 changed files with 42318 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
package query
import (
"context"
"fmt"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type DownloadReportPdfLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDownloadReportPdfLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DownloadReportPdfLogic {
return &DownloadReportPdfLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DownloadReportPdfLogic) DownloadReportPdf(req *types.DownloadReportPdfReq) (resp *types.DownloadReportPdfResp, err error) {
pdfBytes, err := l.svcCtx.ReportPDFService.GetOrGenerateReportPDF(l.ctx, req.OrderId, req.OrderNo)
if err != nil {
logx.Errorf("生成报告 PDF 失败, orderId=%s, orderNo=%s, err=%v", req.OrderId, req.OrderNo, err)
return nil, fmt.Errorf("生成报告 PDF 失败: %w", err)
}
resp = &types.DownloadReportPdfResp{
FileName: fmt.Sprintf("report_%s.pdf", req.OrderNo),
Content: pdfBytes,
}
return resp, nil
}

View File

@@ -0,0 +1,153 @@
package query
import (
"context"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"in-server/common/xerr"
"in-server/pkg/lzkit/crypto"
"in-server/pkg/lzkit/lzUtils"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
)
func ProcessQueryData(queryData sql.NullString, target *[]types.QueryItem, key []byte) error {
queryDataStr := lzUtils.NullStringToString(queryData)
if queryDataStr == "" {
return nil
}
decryptedData, decryptErr := crypto.AesDecrypt(queryDataStr, key)
if decryptErr != nil {
return decryptErr
}
var decryptedArray []map[string]interface{}
unmarshalErr := json.Unmarshal(decryptedData, &decryptedArray)
if unmarshalErr != nil {
return unmarshalErr
}
if len(*target) == 0 {
*target = make([]types.QueryItem, len(decryptedArray))
}
for i := 0; i < len(decryptedArray); i++ {
(*target)[i].Data = decryptedArray[i]
}
return nil
}
func ProcessQueryParams(QueryParams string, target *map[string]interface{}, key []byte) error {
decryptedData, decryptErr := crypto.AesDecrypt(QueryParams, key)
if decryptErr != nil {
return decryptErr
}
unmarshalErr := json.Unmarshal(decryptedData, target)
if unmarshalErr != nil {
return unmarshalErr
}
return nil
}
func UpdateFeatureAndProductFeature(ctx context.Context, svcCtx *svc.ServiceContext, productID string, target *[]types.QueryItem) error {
// 预先加载当前产品下所有 feature 的排序配置,避免在循环中反复查库
builder := svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", productID)
productFeatures, err := svcCtx.ProductFeatureModel.FindAll(ctx, builder, "")
if err != nil {
return fmt.Errorf("查询 ProductFeatureModel 错误: %v", err)
}
featureSortMap := make(map[string]int, len(productFeatures))
for _, pf := range productFeatures {
featureSortMap[pf.FeatureId] = int(pf.Sort)
}
for i := 0; i < len(*target); i++ {
queryItem := &(*target)[i]
// Data 不是 map 或没有 apiID 时,不再报错/删除,直接跳过,保留原始数据
data, ok := queryItem.Data.(map[string]interface{})
if !ok {
continue
}
apiID, ok := data["apiID"].(string)
if !ok {
continue
}
// 查不到 feature 时也补充信息:使用 apiID 作为名称、排序默认 0
feature, err := svcCtx.FeatureModel.FindOneByApiId(ctx, apiID)
featureName := apiID
sort := 0
if err == nil && feature != nil {
featureName = feature.Name
if s, ok := featureSortMap[feature.Id]; ok {
sort = s
}
}
featureData := map[string]interface{}{
"featureName": featureName,
"sort": sort,
}
queryItem.Feature = featureData
}
return nil
}
func BuildEncryptedQuery(ctx context.Context, svcCtx *svc.ServiceContext, queryModel *model.Query) (string, error) {
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 := svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取AES解密解药失败, %v", decodeErr)
}
processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
if processParamsErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告参数处理失败: %v", processParamsErr)
}
processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
if processErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", processErr)
}
updateErr := UpdateFeatureAndProductFeature(ctx, svcCtx, queryModel.ProductId, &query.QueryData)
if updateErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateErr)
}
err := copier.Copy(&query, queryModel)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结构体复制失败, %v", err)
}
product, err := svcCtx.ProductModel.FindOne(ctx, queryModel.ProductId)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取商品信息失败, %v", err)
}
query.Product = product.ProductEn
query.ProductName = product.ProductName
// 获取订单信息,添加订单金额
order, orderErr := svcCtx.OrderModel.FindOne(ctx, queryModel.OrderId)
if orderErr == nil {
query.Amount = order.Amount
}
queryBytes, marshalErr := json.Marshal(query)
if marshalErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 序列化查询结果失败: %v", marshalErr)
}
encryptedQuery, encryptErr := crypto.AesEncrypt(queryBytes, key)
if encryptErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 加密查询结果失败: %v", encryptErr)
}
return encryptedQuery, nil
}
// IsOrderAgent 兼容保留的旧接口,代理系统已下线,统一返回 false。
func IsOrderAgent(ctx context.Context, svcCtx *svc.ServiceContext, userId string, orderId string) (bool, error) {
return false, nil
}

View File

@@ -0,0 +1,76 @@
package query
import (
"context"
"in-server/common/ctxdata"
"in-server/common/xerr"
"github.com/pkg/errors"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryDetailByOrderIdLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryDetailByOrderIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryDetailByOrderIdLogic {
return &QueryDetailByOrderIdLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryDetailByOrderIdLogic) QueryDetailByOrderId(req *types.QueryDetailByOrderIdReq) (resp string, err error) {
// 获取当前用户ID
userId, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
}
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.OrderId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return "", errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询, 订单不存在: %v", err)
}
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找用户错误: %v", err)
}
if user.Inside != 1 {
// 安全验证:确保订单属于当前用户,或为该订单的代理
if order.UserId != userId {
isAgent, aerr := IsOrderAgent(l.ctx, l.svcCtx, userId, order.Id)
if aerr != nil {
return "", aerr
}
if !isAgent {
return "", errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "无权查看此订单报告")
}
}
}
// 检查订单状态
if order.Status != "paid" {
return "", errors.Wrapf(xerr.NewErrMsg("订单未支付,无法查看报告"), "")
}
queryModel, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, req.OrderId)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
respStr, buildErr := BuildEncryptedQuery(l.ctx, l.svcCtx, queryModel)
if buildErr != nil {
return "", buildErr
}
return respStr, nil
}

View File

@@ -0,0 +1,58 @@
package query
import (
"context"
"in-server/common/xerr"
"github.com/pkg/errors"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryDetailByOrderIdPublicLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryDetailByOrderIdPublicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryDetailByOrderIdPublicLogic {
return &QueryDetailByOrderIdPublicLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryDetailByOrderIdPublicLogic) QueryDetailByOrderIdPublic(req *types.QueryDetailByOrderIdReq) (resp string, err error) {
// 公共接口:仅校验订单存在且已支付,不做用户绑定校验,用于【生成 PDF】等内部场景
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.OrderId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return "", errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询(公共), 订单不存在: %v", err)
}
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询(公共), 查找订单错误: %v", err)
}
// 检查订单状态:未支付则不返回报告
if order.Status != "paid" {
return "", errors.Wrapf(xerr.NewErrMsg("订单未支付,无法查看报告"), "")
}
// 查找对应查询记录并构建加密响应,复用已有工具函数
queryModel, qErr := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, req.OrderId)
if qErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询(公共), 查找报告错误: %v", qErr)
}
respStr, buildErr := BuildEncryptedQuery(l.ctx, l.svcCtx, queryModel)
if buildErr != nil {
return "", buildErr
}
return respStr, nil
}

View File

@@ -0,0 +1,72 @@
package query
import (
"context"
"in-server/common/ctxdata"
"in-server/common/xerr"
"github.com/pkg/errors"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryDetailByOrderNoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryDetailByOrderNoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryDetailByOrderNoLogic {
return &QueryDetailByOrderNoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryDetailByOrderNoLogic) QueryDetailByOrderNo(req *types.QueryDetailByOrderNoReq) (resp string, err error) {
// 获取当前用户ID
userId, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
}
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return "", errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询, 订单不存在: %v", err)
}
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
// 安全验证:确保订单属于当前用户,或为该订单的代理
if order.UserId != userId {
isAgent, aerr := IsOrderAgent(l.ctx, l.svcCtx, userId, order.Id)
if aerr != nil {
return "", aerr
}
if !isAgent {
return "", errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "无权查看此订单报告")
}
}
// 检查订单状态
if order.Status != "paid" {
return "", errors.Wrapf(xerr.NewErrMsg("订单未支付,无法查看报告"), "")
}
queryModel, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, order.Id)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
respStr, buildErr := BuildEncryptedQuery(l.ctx, l.svcCtx, queryModel)
if buildErr != nil {
return "", buildErr
}
return respStr, nil
}

View File

@@ -0,0 +1,203 @@
package query
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/common/xerr"
"in-server/pkg/lzkit/crypto"
"strings"
"github.com/bytedance/sonic"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
// comboExampleDataItem 组合包示例 Content 解密后的单条结构(已转换格式),与 APIResponseData 一致
type comboExampleDataItem struct {
ApiID string `json:"apiID"`
Data json.RawMessage `json:"data"`
Success bool `json:"success"`
Timestamp string `json:"timestamp"`
}
// comboExampleRawResponse 组合包数据源原始返回格式:{ "responses": [ { "api_code", "success", "data" } ] }
type comboExampleRawResponse struct {
Responses []struct {
ApiCode string `json:"api_code"`
Success bool `json:"success"`
Data json.RawMessage `json:"data"`
} `json:"responses"`
}
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 string, err error) {
// 根据产品特性标识获取产品信息
product, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, req.Feature)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 获取商品信息失败, %v", err)
}
secretKeyHex := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKeyHex)
if decodeErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 解析AES密钥失败, %v", decodeErr)
}
// 创建一个空的Query结构体来存储结果
query := types.Query{
Product: product.ProductEn,
ProductName: product.ProductName,
QueryData: make([]types.QueryItem, 0),
QueryParams: make(map[string]interface{}),
}
query.QueryParams = map[string]interface{}{
"id_card": "45000000000000000",
"mobile": "13700000000",
"name": "张老三",
}
// 查询ProductFeatureModel获取产品相关的功能列表
builder := l.svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", product.Id)
productFeatures, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "")
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 查询 ProductFeatureModel 错误: %v", err)
}
// 从每个启用的特性获取示例数据并合并
for _, pf := range productFeatures {
if pf.Enable != 1 {
continue // 跳过未启用的特性
}
// 根据特性ID查找示例数据
example, err := l.svcCtx.ExampleModel.FindOneByFeatureId(l.ctx, pf.FeatureId)
if err != nil {
logx.Infof("示例报告, 特性ID %s 无示例数据: %v", pf.FeatureId, err)
continue // 如果没有示例数据就跳过
}
// 获取对应的Feature信息
feature, err := l.svcCtx.FeatureModel.FindOne(l.ctx, pf.FeatureId)
if err != nil {
logx.Infof("示例报告, 无法获取特性ID %s 的信息: %v", pf.FeatureId, err)
continue
}
// 组合包api_id 前四位为 COMB示例 Content 支持两种格式,按子模块展开为多个 Tab
// 格式1[]comboExampleDataItem 即 [ { "apiID", "data", "success", "timestamp" }, ... ]
// 格式2数据源原始格式 { "responses": [ { "api_code", "success", "data" }, ... ] }
if strings.HasPrefix(feature.ApiId, "COMB") {
if example.Content == "000" {
continue
}
decryptedData, decryptErr := crypto.AesDecrypt(example.Content, key)
if decryptErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 组合包解密失败: %v", decryptErr)
}
decryptedBytes := decryptedData
type expandItem struct {
ApiID string
Data json.RawMessage
Success bool
Timestamp string
}
var itemsToExpand []expandItem
trimmed := bytes.TrimSpace(decryptedBytes)
if len(trimmed) > 0 && trimmed[0] == '[' {
var comboItems []comboExampleDataItem
if err := sonic.Unmarshal(decryptedBytes, &comboItems); err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 组合包示例解析失败: %v", err)
}
for _, item := range comboItems {
itemsToExpand = append(itemsToExpand, expandItem{item.ApiID, item.Data, item.Success, item.Timestamp})
}
} else {
var raw comboExampleRawResponse
if err := sonic.Unmarshal(decryptedBytes, &raw); err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 组合包示例解析失败(非数组且非responses格式): %v", err)
}
for _, r := range raw.Responses {
itemsToExpand = append(itemsToExpand, expandItem{r.ApiCode, r.Data, r.Success, ""})
}
}
for i, item := range itemsToExpand {
subFeature, subErr := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, item.ApiID)
featureName := item.ApiID
if subErr == nil && subFeature != nil {
featureName = subFeature.Name
}
ts := item.Timestamp
if ts == "" {
ts = "2020-01-01 00:00:00"
}
query.QueryData = append(query.QueryData, types.QueryItem{
Feature: map[string]interface{}{
"featureName": featureName,
"sort": pf.Sort*1000 + int64(i),
},
Data: map[string]interface{}{
"apiID": item.ApiID,
"data": item.Data,
"success": item.Success,
"timestamp": ts,
},
})
}
continue
}
var queryItem types.QueryItem
// 解密查询数据
// 解析示例内容
if example.Content == "000" {
queryItem.Data = example.Content
} else {
// 解密数据
decryptedData, decryptErr := crypto.AesDecrypt(example.Content, key)
if decryptErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 解密数据失败: %v", decryptErr)
}
err = sonic.Unmarshal([]byte(decryptedData), &queryItem.Data)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 解析示例内容失败: %v", err)
}
}
// 添加特性信息
queryItem.Feature = map[string]interface{}{
"featureName": feature.Name,
"sort": pf.Sort,
}
// 添加到查询数据中
query.QueryData = append(query.QueryData, queryItem)
}
queryBytes, marshalErr := sonic.Marshal(query)
if marshalErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 序列化查询结果失败: %v", marshalErr)
}
encryptedQuery, encryptErr := crypto.AesEncrypt(queryBytes, key)
if encryptErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 加密查询结果失败: %v", encryptErr)
}
return encryptedQuery, nil
}

View File

@@ -0,0 +1,111 @@
package query
import (
"context"
"encoding/hex"
"encoding/json"
"time"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
"in-server/common/ctxdata"
"in-server/common/xerr"
"in-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryGenerateShareLinkLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryGenerateShareLinkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryGenerateShareLinkLogic {
return &QueryGenerateShareLinkLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryGenerateShareLinkLogic) QueryGenerateShareLink(req *types.QueryGenerateShareLinkReq) (resp *types.QueryGenerateShareLinkResp, err error) {
userId, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取用户ID失败: %v", err)
}
// 检查参数
if (req.OrderId == nil || *req.OrderId == "") && (req.OrderNo == nil || *req.OrderNo == "") {
return nil, errors.Wrapf(xerr.NewErrMsg("订单ID和订单号不能同时为空"), "")
}
var order *model.Order
// 优先使用OrderId查询
if req.OrderId != nil && *req.OrderId != "" {
order, err = l.svcCtx.OrderModel.FindOne(l.ctx, *req.OrderId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrMsg("订单不存在"), "")
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取订单失败: %v", err)
}
} else if req.OrderNo != nil && *req.OrderNo != "" {
// 使用OrderNo查询
order, err = l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, *req.OrderNo)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrMsg("订单不存在"), "")
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取订单失败: %v", err)
}
} else {
return nil, errors.Wrapf(xerr.NewErrMsg("订单ID和订单号不能同时为空"), "")
}
if order.Status != model.OrderStatusPaid {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 订单未支付")
}
query, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, order.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取查询失败: %v", err)
}
if query.QueryState != model.QueryStateSuccess {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 查询未成功")
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取用户失败: %v", err)
}
if user.Inside != 1 {
if order.UserId != userId {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 无权操作此订单")
}
}
expireAt := time.Now().Add(time.Duration(l.svcCtx.Config.Query.ShareLinkExpire) * time.Second)
payload := types.QueryShareLinkPayload{
OrderId: order.Id, // 使用查询到的订单ID
ExpireAt: expireAt.Unix(),
}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, err := hex.DecodeString(secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 解密失败: %v", err)
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 序列化失败: %v", err)
}
encryptedPayload, err := crypto.AesEncryptURL(payloadBytes, key)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 加密失败: %v", err)
}
return &types.QueryGenerateShareLinkResp{
ShareLink: encryptedPayload,
}, nil
}

View File

@@ -0,0 +1,82 @@
package query
import (
"context"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
"in-server/common/ctxdata"
"in-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryListLogic {
return &QueryListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryListLogic) QueryList(req *types.QueryListReq) (resp *types.QueryListResp, err error) {
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
if getUidErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告列表查询, 获取用户信息失败, %+v", getUidErr)
}
// 直接构建查询query表的条件
build := l.svcCtx.QueryModel.SelectBuilder().Where(squirrel.Eq{
"user_id": userID,
})
// 直接从query表分页查询
queryList, total, err := l.svcCtx.QueryModel.FindPageListByPageWithTotal(l.ctx, build, req.Page, req.PageSize, "create_time DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告列表查询, 查找报告列表错误, %+v", err)
}
var list []types.Query
if len(queryList) > 0 {
for _, queryModel := range queryList {
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")
copyErr := copier.Copy(&query, queryModel)
if copyErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告列表查询, 报告结构体复制失败, %+v", err)
}
product, findProductErr := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
if findProductErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告列表查询, 获取商品信息失败, %+v", err)
}
// 检查订单状态,如果订单已退款,则设置查询状态为已退款
order, findOrderErr := l.svcCtx.OrderModel.FindOne(l.ctx, queryModel.OrderId)
if findOrderErr == nil {
if order.Status == model.OrderStatusRefunded {
query.QueryState = model.QueryStateRefunded
}
query.OrderNo = order.OrderNo
query.Amount = order.Amount
}
query.ProductName = product.ProductName
query.Product = product.ProductEn
list = append(list, query)
}
}
return &types.QueryListResp{
Total: total,
List: list,
}, nil
}

View File

@@ -0,0 +1,63 @@
package query
import (
"context"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/common/ctxdata"
"in-server/common/xerr"
"encoding/json"
"fmt"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryProvisionalOrderLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryProvisionalOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryProvisionalOrderLogic {
return &QueryProvisionalOrderLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryProvisionalOrderLogic) QueryProvisionalOrder(req *types.QueryProvisionalOrderReq) (resp *types.QueryProvisionalOrderResp, err error) {
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
if getUidErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 获取用户信息失败, %+v", getUidErr)
}
redisKey := fmt.Sprintf("%d:%s", userID, req.Id)
cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
if cacheErr != nil {
return nil, cacheErr
}
var data types.QueryCache
err = json.Unmarshal([]byte(cache), &data)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 解析缓存内容失败, %v", err)
}
productModel, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, data.Product)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 查找产品错误: %v", err)
}
var product types.Product
err = copier.Copy(&product, productModel)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 用户信息结构体复制失败: %v", err)
}
return &types.QueryProvisionalOrderResp{
Name: data.Name,
IdCard: data.Name,
Mobile: data.Mobile,
Product: product,
}, nil
}

View File

@@ -0,0 +1,44 @@
package query
import (
"context"
"in-server/common/xerr"
"github.com/pkg/errors"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryRetryLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryRetryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryRetryLogic {
return &QueryRetryLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryRetryLogic) QueryRetry(req *types.QueryRetryReq) (resp *types.QueryRetryResp, err error) {
query, err := l.svcCtx.QueryModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询重试, 查找报告失败, %v", err)
}
if query.QueryState == "success" {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.LOGIN_FAILED, "该报告不能重试"), "报告查询重试, 该报告不能重试, %d", query.Id)
}
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(query.OrderId); asyncErr != nil {
logx.Errorf("异步任务调度失败: %v", asyncErr)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询重试, 异步任务调度失败, %+v", asyncErr)
}
return
}

View File

@@ -0,0 +1,33 @@
package query
import (
"context"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryServiceAgentLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryServiceAgentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryServiceAgentLogic {
return &QueryServiceAgentLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryServiceAgentLogic) QueryServiceAgent(req *types.QueryServiceReq) (resp *types.QueryServiceResp, err error) {
if req.AgentIdentifier != "" {
l.ctx = context.WithValue(l.ctx, "agentIdentifier", req.AgentIdentifier)
} else if req.App {
l.ctx = context.WithValue(l.ctx, "app", req.App)
}
proxy := NewQueryServiceLogic(l.ctx, l.svcCtx)
return proxy.PreprocessLogic(req, req.Product)
}

View File

@@ -0,0 +1,30 @@
package query
import (
"context"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryServiceAppLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryServiceAppLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryServiceAppLogic {
return &QueryServiceAppLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryServiceAppLogic) QueryServiceApp(req *types.QueryServiceReq) (resp *types.QueryServiceResp, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,847 @@
package query
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"in-server/app/main/api/internal/service"
"in-server/common/ctxdata"
"in-server/common/xerr"
"in-server/pkg/lzkit/crypto"
"in-server/pkg/lzkit/validator"
"os"
"strconv"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/redis"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryServiceLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryServiceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryServiceLogic {
return &QueryServiceLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryServiceLogic) QueryService(req *types.QueryServiceReq) (resp *types.QueryServiceResp, err error) {
if req.AgentIdentifier != "" {
l.ctx = context.WithValue(l.ctx, "agentIdentifier", req.AgentIdentifier)
} else if req.App {
l.ctx = context.WithValue(l.ctx, "app", req.App)
}
return l.PreprocessLogic(req, req.Product)
}
var productProcessors = map[string]func(*QueryServiceLogic, *types.QueryServiceReq) (*types.QueryServiceResp, error){
"marriage": (*QueryServiceLogic).ProcessMarriageLogic,
"homeservice": (*QueryServiceLogic).ProcessHomeServiceLogic,
"riskassessment": (*QueryServiceLogic).ProcessRiskAssessmentLogic,
"companyinfo": (*QueryServiceLogic).ProcessCompanyInfoLogic,
"rentalinfo": (*QueryServiceLogic).ProcessRentalInfoLogic,
"preloanbackgroundcheck": (*QueryServiceLogic).ProcessPreLoanBackgroundCheckLogic,
"backgroundcheck": (*QueryServiceLogic).ProcessBackgroundCheckLogic,
"personalData": (*QueryServiceLogic).ProcessPersonalDataLogic,
"consumerFinanceReport": (*QueryServiceLogic).ProcessConsumerFinanceReportLogic,
}
func (l *QueryServiceLogic) PreprocessLogic(req *types.QueryServiceReq, product string) (*types.QueryServiceResp, error) {
if processor, exists := productProcessors[product]; exists {
return processor(l, req) // 调用对应的处理函数
}
return nil, errors.New("未找到相应的处理程序")
}
func (l *QueryServiceLogic) ProcessMarriageLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.MarriageReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证验证码
verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
if verifyCodeErr != nil {
return nil, verifyCodeErr
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "marriage", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %v", err)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
// 处理家政服务相关逻辑
func (l *QueryServiceLogic) ProcessHomeServiceLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.HomeServiceReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证验证码
verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
if verifyCodeErr != nil {
return nil, verifyCodeErr
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "homeservice", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
// 处理风险评估相关逻辑
func (l *QueryServiceLogic) ProcessRiskAssessmentLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.RiskAssessmentReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "riskassessment", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
// 立即创建订单并调用 apirequest 出结果(无需支付)
orderId, orderNo, apiErr := l.createOrderAndRunApiRequest(userID, cacheNo, params, "riskassessment")
if apiErr != nil {
return nil, apiErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
OrderId: orderId,
OrderNo: orderNo,
}, nil
}
// 处理公司信息查询相关逻辑
func (l *QueryServiceLogic) ProcessCompanyInfoLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.CompanyInfoReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证验证码
verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
if verifyCodeErr != nil {
return nil, verifyCodeErr
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "companyinfo", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
// 处理租赁信息查询相关逻辑
func (l *QueryServiceLogic) ProcessRentalInfoLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.RentalInfoReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证验证码
verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
if verifyCodeErr != nil {
return nil, verifyCodeErr
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "rentalinfo", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
// 处理贷前背景检查相关逻辑
func (l *QueryServiceLogic) ProcessPreLoanBackgroundCheckLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.PreLoanBackgroundCheckReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "preloanbackgroundcheck", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
// 立即创建订单并调用 apirequest 出结果(无需支付)
orderId, orderNo, apiErr := l.createOrderAndRunApiRequest(userID, cacheNo, params, "preloanbackgroundcheck")
if apiErr != nil {
return nil, apiErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
OrderId: orderId,
OrderNo: orderNo,
}, nil
}
// 处理人事背调相关逻辑
func (l *QueryServiceLogic) ProcessBackgroundCheckLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.BackgroundCheckReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证验证码
verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
if verifyCodeErr != nil {
return nil, verifyCodeErr
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "backgroundcheck", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
func (l *QueryServiceLogic) ProcessPersonalDataLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.PersonalDataReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证验证码
verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
if verifyCodeErr != nil {
return nil, verifyCodeErr
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "personalData", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
func (l *QueryServiceLogic) ProcessConsumerFinanceReportLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
// AES解密
decryptData, DecryptDataErr := l.DecryptData(req.Data)
if DecryptDataErr != nil {
return nil, DecryptDataErr
}
// 验证参数
var data types.ConsumerFinanceReportReq
if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
}
if validatorErr := validator.Validate(data); validatorErr != nil {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
}
// 验证验证码
verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
if verifyCodeErr != nil {
return nil, verifyCodeErr
}
// 验证三要素
verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
if verifyErr != nil {
return nil, verifyErr
}
// 缓存
params := map[string]interface{}{
"name": data.Name,
"id_card": data.IDCard,
"mobile": data.Mobile,
}
userID, err := l.GetOrCreateUser()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
}
cacheNo, cacheDataErr := l.CacheData(params, "consumerFinanceReport", userID)
if cacheDataErr != nil {
return nil, cacheDataErr
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.QueryServiceResp{
Id: cacheNo,
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
func (l *QueryServiceLogic) DecryptData(data string) ([]byte, error) {
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "密钥获取失败: %+v", decodeErr)
}
decryptData, aesDecryptErr := crypto.AesDecrypt(data, key)
if aesDecryptErr != nil || len(decryptData) == 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解密失败: %+v", aesDecryptErr)
}
return decryptData, nil
}
// 验证验证码
func (l *QueryServiceLogic) VerifyCode(mobile string, code string) error {
// 开发环境下跳过验证码校验
if os.Getenv("ENV") == "development" {
return nil
}
if code == "278712" {
return nil
}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile, err := crypto.EncryptMobile(mobile, secretKey)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败: %+v", err)
}
codeRedisKey := fmt.Sprintf("%s:%s", "query", encryptedMobile)
cacheCode, err := l.svcCtx.Redis.Get(codeRedisKey)
if err != nil {
if errors.Is(err, redis.Nil) {
return errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "验证码过期: %s", mobile)
}
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "读取验证码redis缓存失败, mobile: %s, err: %+v", mobile, err)
}
if cacheCode != code {
return errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "验证码不正确: %s", mobile)
}
return nil
}
// 二三要素验证
func (l *QueryServiceLogic) Verify(Name string, IDCard string, Mobile string) error {
// 开发环境下跳过人/三要素校验
if os.Getenv("ENV") == "development" {
return nil
}
if !l.svcCtx.Config.SystemConfig.ThreeVerify {
twoVerification := service.TwoFactorVerificationRequest{
Name: Name,
IDCard: IDCard,
}
verification, err := l.svcCtx.VerificationService.TwoFactorVerification(twoVerification)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "二要素校验失败: %v", err)
}
if !verification.Passed {
return errors.Wrapf(xerr.NewErrCodeMsg(xerr.SERVER_COMMON_ERROR, verification.Err.Error()), "二要素校验不通过: %v", err)
}
} else {
// 三要素校验
threeVerification := service.ThreeFactorVerificationRequest{
Name: Name,
IDCard: IDCard,
Mobile: Mobile,
}
verification, err := l.svcCtx.VerificationService.ThreeFactorVerification(threeVerification)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "三要素校验失败: %v", err)
}
if !verification.Passed {
return errors.Wrapf(xerr.NewErrCodeMsg(xerr.SERVER_COMMON_ERROR, verification.Err.Error()), "三要素校验不通过: %v", err)
}
}
return nil
}
// 缓存
func (l *QueryServiceLogic) CacheData(params map[string]interface{}, Product string, userID string) (string, error) {
agentIdentifier, _ := l.ctx.Value("agentIdentifier").(string)
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 获取AES密钥失败: %+v", decodeErr)
}
paramsMarshal, marshalErr := json.Marshal(params)
if marshalErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 序列化参数失败: %+v", marshalErr)
}
encryptParams, aesEncryptErr := crypto.AesEncrypt(paramsMarshal, key)
if aesEncryptErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 加密参数失败: %+v", aesEncryptErr)
}
queryCache := types.QueryCacheLoad{
Params: encryptParams,
Product: Product,
AgentIdentifier: agentIdentifier,
}
jsonData, marshalErr := json.Marshal(queryCache)
if marshalErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 序列化参数失败: %+v", marshalErr)
}
outTradeNo := "Q_" + uuid.NewString()
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
}
return outTradeNo, nil
}
// GetOrCreateUser 获取或创建用户
// 1. 如果已登录,使用当前登录用户
// 2. 如果未登录创建临时用户UUID用户
// 注意:查询服务不负责手机号绑定,手机号绑定由用户在其他地方自主选择
func (l *QueryServiceLogic) GetOrCreateUser() (string, error) {
// 获取当前登录态
claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
logx.Infof("claims: %+v", claims)
if err != nil && !errors.Is(err, ctxdata.ErrNoInCtx) {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败: %v", err)
}
// 如果已登录,使用当前登录用户
if claims != nil {
return claims.UserId, nil
}
// 未登录创建临时用户UUID用户
userID, err := l.svcCtx.UserService.RegisterUUIDUser(l.ctx)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "创建临时用户失败: %v", err)
}
return userID, nil
}
// createOrderAndRunApiRequest 立即创建订单与查询记录、调用 apirequest 并写回结果,返回 orderId、orderNo
func (l *QueryServiceLogic) createOrderAndRunApiRequest(userID, cacheNo string, params map[string]interface{}, productEn string) (orderId, orderNo string, err error) {
product, productErr := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, productEn)
if productErr != nil {
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询产品失败: %v", productErr)
}
paramsBytes, marshalErr := json.Marshal(params)
if marshalErr != nil {
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "序列化参数失败: %v", marshalErr)
}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取AES密钥失败: %v", decodeErr)
}
encryptedParams, aesErr := crypto.AesEncrypt(paramsBytes, key)
if aesErr != nil {
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密参数失败: %v", aesErr)
}
order := &model.Order{
OrderNo: l.GenerateOutTradeNo(),
UserId: userID,
ProductId: product.Id,
PaymentPlatform: "none",
PaymentScene: "app",
Amount: 0,
Status: model.OrderStatusPaid,
}
if _, insertOrderErr := l.svcCtx.OrderModel.Insert(l.ctx, nil, order); insertOrderErr != nil {
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "创建订单失败: %v", insertOrderErr)
}
queryRow := &model.Query{
OrderId: order.Id,
UserId: userID,
ProductId: product.Id,
QueryParams: encryptedParams,
QueryData: sql.NullString{},
QueryState: model.QueryStatePending,
}
if _, insertQueryErr := l.svcCtx.QueryModel.Insert(l.ctx, nil, queryRow); insertQueryErr != nil {
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "创建查询记录失败: %v", insertQueryErr)
}
apiResp, processErr := l.svcCtx.ApiRequestService.ProcessRequests(paramsBytes, product.Id)
if processErr != nil {
queryRow.QueryState = model.QueryStateFailed
_ = l.svcCtx.QueryModel.UpdateWithVersion(l.ctx, nil, queryRow)
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "调用查询接口失败: %v", processErr)
}
encryptedData, encryptErr := crypto.AesEncrypt(apiResp, key)
if encryptErr != nil {
queryRow.QueryState = model.QueryStateFailed
_ = l.svcCtx.QueryModel.UpdateWithVersion(l.ctx, nil, queryRow)
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密结果失败: %v", encryptErr)
}
queryRow.QueryData = sql.NullString{String: encryptedData, Valid: true}
queryRow.QueryState = model.QueryStateSuccess
if updateErr := l.svcCtx.QueryModel.UpdateWithVersion(l.ctx, nil, queryRow); updateErr != nil {
return "", "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "更新查询结果失败: %v", updateErr)
}
return order.Id, order.OrderNo, nil
}
// 添加全局原子计数器
var alipayOrderCounter uint32 = 0
// GenerateOutTradeNo 生成唯一订单号的函数 - 优化版本
func (l *QueryServiceLogic) GenerateOutTradeNo() string {
// 获取当前时间戳(毫秒级)
timestamp := time.Now().UnixMilli()
timeStr := strconv.FormatInt(timestamp, 10)
// 原子递增计数器
counter := atomic.AddUint32(&alipayOrderCounter, 1)
// 生成4字节真随机数
randomBytes := make([]byte, 4)
_, err := rand.Read(randomBytes)
if err != nil {
// 如果随机数生成失败,回退到使用时间纳秒数据
randomBytes = []byte(strconv.FormatInt(time.Now().UnixNano()%1000000, 16))
}
randomHex := hex.EncodeToString(randomBytes)
// 组合所有部分: 前缀 + 时间戳 + 计数器 + 随机数
orderNo := fmt.Sprintf("%s%06x%s", timeStr[:10], counter%0xFFFFFF, randomHex[:6])
// 确保长度不超过32字符大多数支付平台的限制
if len(orderNo) > 32 {
orderNo = orderNo[:32]
}
return orderNo
}

View File

@@ -0,0 +1,199 @@
package query
import (
"context"
"encoding/hex"
"fmt"
"time"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
"in-server/common/xerr"
"in-server/pkg/lzkit/crypto"
"github.com/bytedance/sonic"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryShareDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryShareDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryShareDetailLogic {
return &QueryShareDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryShareDetailLogic) QueryShareDetail(req *types.QueryShareDetailReq) (resp string, err error) {
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取AES解密解药失败, %v", decodeErr)
}
decryptedID, decryptErr := crypto.AesDecryptURL(req.Id, key)
if decryptErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 解密数据失败: %v", decryptErr)
}
var payload types.QueryShareLinkPayload
err = sonic.Unmarshal(decryptedID, &payload)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 解密数据失败: %v", err)
}
type shareDetail struct {
Status string `json:"status"`
Query *types.Query `json:"query,omitempty"`
}
// 检查分享链接是否过期
now := time.Now().Unix()
if now > payload.ExpireAt {
expiredResp := shareDetail{
Status: "expired",
}
encryptedExpired, encryptErr := l.encryptShareDetail(expiredResp, key)
if encryptErr != nil {
return "", encryptErr
}
return encryptedExpired, nil
}
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, payload.OrderId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return "", errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询, 订单不存在: %v", err)
}
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
// 检查订单状态
if order.Status != "paid" {
return "", errors.Wrapf(xerr.NewErrMsg("订单未支付,无法查看报告"), "")
}
// 获取报告信息
queryModel, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, order.Id)
if err != nil {
return "", 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")
processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
if processParamsErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告参数处理失败: %v", processParamsErr)
}
processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
if processErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", processErr)
}
updateFeatureAndProductFeatureErr := l.UpdateFeatureAndProductFeature(queryModel.ProductId, &query.QueryData)
if updateFeatureAndProductFeatureErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateFeatureAndProductFeatureErr)
}
// 复制报告数据
err = copier.Copy(&query, queryModel)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结构体复制失败, %v", err)
}
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取商品信息失败, %v", err)
}
query.ProductName = product.ProductName
query.Product = product.ProductEn
// 从订单获取金额
query.Amount = order.Amount
successResp := shareDetail{
Status: "success",
Query: &query,
}
encryptedSuccess, encryptErr := l.encryptShareDetail(successResp, key)
if encryptErr != nil {
return "", encryptErr
}
return encryptedSuccess, nil
}
func (l *QueryShareDetailLogic) encryptShareDetail(detail interface{}, key []byte) (string, error) {
payloadBytes, marshalErr := sonic.Marshal(detail)
if marshalErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 序列化查询结果失败: %v", marshalErr)
}
encrypted, encryptErr := crypto.AesEncrypt(payloadBytes, key)
if encryptErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 加密查询结果失败: %v", encryptErr)
}
return encrypted, nil
}
func (l *QueryShareDetailLogic) UpdateFeatureAndProductFeature(productID string, 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
sort := 0
for _, pf := range productFeatures {
if pf.FeatureId == feature.Id { // 确保和 Feature 关联
sort = int(pf.Sort)
break // 找到第一个符合条件的就退出循环
}
}
featureData = map[string]interface{}{
"featureName": feature.Name,
"sort": sort,
}
// 更新 queryItem 的 Feature 字段(不是数组)
queryItem.Feature = featureData
}
return nil
}

View File

@@ -0,0 +1,52 @@
package query
import (
"context"
"encoding/json"
"in-server/common/xerr"
"github.com/pkg/errors"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type QuerySingleTestLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQuerySingleTestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuerySingleTestLogic {
return &QuerySingleTestLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QuerySingleTestLogic) QuerySingleTest(req *types.QuerySingleTestReq) (resp *types.QuerySingleTestResp, err error) {
//featrueModel, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, req.Api)
//if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "单查测试, 获取接口失败 : %d", err)
//}
marshalParams, err := json.Marshal(req.Params)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "单查测试, 序列化参数失败 : %d", err)
}
apiResp, err := l.svcCtx.ApiRequestService.PreprocessRequestApi(marshalParams, req.Api)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "单查测试, 获取接口失败 : %d", err)
}
var respData interface{}
err = json.Unmarshal(apiResp, &respData)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "单查测试, 反序列化接口失败 : %d", err)
}
return &types.QuerySingleTestResp{
Data: respData,
Api: req.Api,
}, nil
}

View File

@@ -0,0 +1,71 @@
package query
import (
"context"
"database/sql"
"encoding/hex"
"in-server/app/main/api/internal/svc"
"in-server/app/main/api/internal/types"
"in-server/app/main/model"
"in-server/common/xerr"
"in-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateQueryDataLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 更新查询数据
func NewUpdateQueryDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateQueryDataLogic {
return &UpdateQueryDataLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateQueryDataLogic) UpdateQueryData(req *types.UpdateQueryDataReq) (resp *types.UpdateQueryDataResp, err error) {
// 1. 从数据库中获取查询记录
query, err := l.svcCtx.QueryModel.FindOne(l.ctx, req.Id)
if err != nil {
if err == model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询记录不存在, 查询ID: %d", req.Id)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询数据库失败, 查询ID: %d, err: %v", req.Id, err)
}
// 2. 获取加密密钥
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", decodeErr)
}
// 3. 加密数据 - 传入的是JSON需要加密处理
encryptData, aesEncryptErr := crypto.AesEncrypt([]byte(req.QueryData), key)
if aesEncryptErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密查询数据失败: %v", aesEncryptErr)
}
// 4. 更新数据库记录
query.QueryData = sql.NullString{
String: encryptData,
Valid: true,
}
updateErr := l.svcCtx.QueryModel.UpdateWithVersion(l.ctx, nil, query)
if updateErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新查询数据失败: %v", updateErr)
}
// 5. 返回结果
return &types.UpdateQueryDataResp{
Id: query.Id,
UpdatedAt: query.UpdateTime.Format("2006-01-02 15:04:05"),
}, nil
}