ai_scheduler/internal/tools/zltx_product.go

341 lines
11 KiB
Go

package tools
import (
"ai_scheduler/internal/config"
"ai_scheduler/internal/entitys"
"encoding/json"
"fmt"
"strconv"
"strings"
"gitea.cdlsxd.cn/self-tools/l_request"
"github.com/gofiber/websocket/v2"
)
type ZltxProductTool struct {
config config.ToolConfig
}
func (z ZltxProductTool) Name() string {
return "zltxProduct"
}
func (z ZltxProductTool) Description() string {
return "获取直连天下商品信息"
}
func (z ZltxProductTool) Definition() entitys.ToolDefinition {
return entitys.ToolDefinition{
Type: "function",
Function: entitys.FunctionDef{
Name: z.Name(),
Description: z.Description(),
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"id": map[string]interface{}{
"type": "string",
"description": "商品ID",
},
"name": map[string]interface{}{
"type": "string",
"description": "商品名称",
},
},
"required": []string{"id", "name"},
},
},
}
}
type ZltxProductRequest struct {
Id string `json:"id"`
Name string `json:"name"`
}
func (z ZltxProductTool) Execute(channel chan entitys.Response, c *websocket.Conn, args json.RawMessage, matchJson *entitys.Match) error {
var req ZltxProductRequest
if err := json.Unmarshal(args, &req); err != nil {
return fmt.Errorf("invalid zltxProduct request: %w", err)
}
return z.getZltxProduct(channel, c, req.Id, req.Name)
}
type ZltxProductResponse struct {
Code int `json:"code"`
Data struct {
DataCount int `json:"dataCount"`
List []ZltxProductData `json:"list"`
} `json:"data"`
Error string `json:"error"`
}
type ZltxProductDataById struct {
Code int `json:"code"`
Data ZltxProductData `json:"data"`
Error string `json:"error"`
}
type ZltxProductData struct {
ID int `json:"id"`
OursProductCategoryID int `json:"ours_product_category_id"`
OfficialProductID int `json:"official_product_id"`
Tag string `json:"tag"`
Name string `json:"name"`
Type int `json:"type"`
Discount string `json:"discount"`
Preview string `json:"preview"`
Describe string `json:"describe"`
Price string `json:"price"`
Status int `json:"status"`
CreateTime string `json:"create_time"`
UpdateTime string `json:"update_time"`
Extend string `json:"extend"`
Wight int `json:"wight"`
Property int `json:"property"`
AuthProductInfo []any `json:"auth_product_info"`
AuthProductIds string `json:"auth_product_ids"`
Category struct {
ID int `json:"id"`
Name string `json:"name"`
Status int `json:"status"`
CreateTime string `json:"create_time"`
Pid int `json:"pid"`
} `json:"category"`
OfficialProduct struct {
ID int `json:"id"`
OfficialID int `json:"official_id"`
Name string `json:"name"`
Describe string `json:"describe"`
Preview string `json:"preview"`
Price float64 `json:"price"`
Status int `json:"status"`
CreateTime string `json:"create_time"`
UpdateTime string `json:"update_time"`
Type int `json:"type"`
Daies int `json:"daies"`
PreviewURL string `json:"preview_url"`
Official struct {
ID int `json:"id"`
Name string `json:"name"`
Describe string `json:"describe"`
Num int `json:"num"`
Status int `json:"status"`
WebURL string `json:"web_url"`
RechargeURL string `json:"recharge_url"`
CreateTime string `json:"create_time"`
UpdateTime string `json:"update_time"`
Type int `json:"type"`
Tag string `json:"tag"`
} `json:"official"`
} `json:"official_product"`
Statistics interface{} `json:"statistics"`
PlatformProductList interface{} `json:"platform_product_list"`
}
func (z ZltxProductTool) getZltxProduct(channel chan entitys.Response, c *websocket.Conn, id string, name string) error {
var auth string
if c != nil {
auth = c.Query("x-authorization", "")
}
if len(auth) == 0 {
auth = z.config.APIKey
}
var Url string
var params map[string]string
if id != "" {
Url = fmt.Sprintf("%s/%s", z.config.BaseURL, id)
} else {
Url = fmt.Sprintf("%s?keyword=%s&limit=10&page=1", z.config.BaseURL, name)
params = map[string]string{
"keyword": name,
"limit": "10",
"page": "1",
}
}
req := l_request.Request{
//get /admin/oursProduct/{product_id} 通过商品id获取我们的商品信息
//get /admin/oursProduct?keyword={name}&limit=10&page=1 通过商品name获取我们的商品列表
//根据商品ID或名称走不同的接口查询
Url: Url,
Headers: map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", auth),
},
Params: params,
Method: "GET",
}
res, err := req.Send()
if err != nil {
return err
}
var resp ZltxProductResponse
if err := json.Unmarshal(res.Content, &resp); err != nil {
return fmt.Errorf("解析商品数据失败:%w", err)
}
if resp.Code != 200 {
return fmt.Errorf("商品查询失败:%s", resp.Error)
}
if resp.Data.List == nil || len(resp.Data.List) == 0 {
var respData ZltxProductDataById
if err := json.Unmarshal(res.Content, &respData); err != nil {
return fmt.Errorf("解析商品数据失败:%w", err)
}
if respData.Data.ID == 0 {
return fmt.Errorf("商品查询失败:暂无数据")
}
resp.Data.List = []ZltxProductData{respData.Data}
resp.Data.DataCount = 1
}
//调用 平台商品列表
if resp.Data.List != nil && len(resp.Data.List) > 0 {
for i := range resp.Data.List {
// 调用 平台商品列表
if resp.Data.List[i].AuthProductIds != "" {
platformProductList := z.ExecutePlatformProductList(auth, resp.Data.List[i].AuthProductIds, resp.Data.List[i].OfficialProductID)
resp.Data.List[i].PlatformProductList = platformProductList
}
}
}
marshal, err := json.Marshal(resp)
if err != nil {
return err
}
channel <- entitys.Response{
Index: z.Name(),
Content: string(marshal),
Type: entitys.ResponseJson,
}
return nil
}
type PlatformProductResponse struct {
Code int `json:"code"`
Data []struct {
ID int `json:"id"`
PlatformID int `json:"platform_id"`
OfficialProductID int `json:"official_product_id"`
Weight int `json:"weight"`
Code string `json:"code"`
Name string `json:"name"`
Discount string `json:"discount"`
Price string `json:"price"`
Extra string `json:"extra"`
AccountType []string `json:"account_type"`
Status int `json:"status"`
CreateTime string `json:"create_time"`
UpdateTime string `json:"update_time"`
RebatePrice string `json:"rebate_price"`
ExchangeType int `json:"exchange_type"`
IsReportInfo int `json:"is_report_info"`
Describe string `json:"describe"`
PlatformAliasID int `json:"platform_alias_id"`
Platform struct {
ID int `json:"id"`
Tag string `json:"tag"`
Name string `json:"name"`
Status int `json:"status"`
Weight int `json:"weight"`
UpdateTime string `json:"update_time"`
SearchTime string `json:"search_time"`
Balance string `json:"balance"`
BalanceWarning string `json:"balance_warning"`
StockType int `json:"stock_type"`
IsIndependent int `json:"is_independent"`
IndependentDeadline string `json:"independent_deadline"`
CreateTime string `json:"create_time"`
} `json:"platform"`
} `json:"data"`
Error string `json:"error"`
}
type PlatformData struct {
ID int `json:"id"`
PlatformID int `json:"platform_id"`
OfficialProductID int `json:"official_product_id"`
Weight int `json:"weight"`
Code string `json:"code"`
Name string `json:"name"`
Discount string `json:"discount"`
Price string `json:"price"`
Extra string `json:"extra"`
AccountType []string `json:"account_type"`
Status int `json:"status"`
CreateTime string `json:"create_time"`
UpdateTime string `json:"update_time"`
RebatePrice string `json:"rebate_price"`
ExchangeType int `json:"exchange_type"`
IsReportInfo int `json:"is_report_info"`
Describe string `json:"describe"`
PlatformAliasID int `json:"platform_alias_id"`
Platform struct {
ID int `json:"id"`
Tag string `json:"tag"`
Name string `json:"name"`
Status int `json:"status"`
Weight int `json:"weight"`
UpdateTime string `json:"update_time"`
SearchTime string `json:"search_time"`
Balance string `json:"balance"`
BalanceWarning string `json:"balance_warning"`
StockType int `json:"stock_type"`
IsIndependent int `json:"is_independent"`
IndependentDeadline string `json:"independent_deadline"`
CreateTime string `json:"create_time"`
} `json:"platform"`
}
func (z ZltxProductTool) ExecutePlatformProductList(auth string, authProductIds string, officialProductID int) []PlatformData {
if authProductIds == "" {
return nil
}
//authProductIds 以逗号分割
authProductIdList := strings.Split(authProductIds, ",")
for _, authProductId := range authProductIdList {
var platformProductResponse PlatformProductResponse
req := l_request.Request{
//https://gateway.dev.cdlsxd.cn/zltx_api/admin/platformProduct/getProductsByOfficialProductId?official_product_id=282&is_all=true
Url: fmt.Sprintf("%s?official_product_id=%d&is_all=true", z.config.AddURL, officialProductID),
Headers: map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", auth),
},
Method: "GET",
}
res, err := req.Send()
if err != nil {
// 可以考虑记录日志而不是直接跳过
continue
}
if err := json.Unmarshal(res.Content, &platformProductResponse); err != nil {
// 可以考虑记录日志而不是直接跳过
continue
}
authProductIdInt, err := strconv.Atoi(authProductId)
if err != nil {
// 可以考虑记录日志而不是直接跳过
continue
}
for _, platformProduct := range platformProductResponse.Data {
if platformProduct.ID == authProductIdInt {
return []PlatformData{platformProduct}
}
}
}
return nil
}
type ZltxProductPlatformProductList struct {
Code int `json:"code"`
Data map[string]any `json:"data"`
Error string `json:"error"`
}
func NewZltxProductTool(config config.ToolConfig) *ZltxProductTool {
return &ZltxProductTool{
config: config,
}
}