Version: 0.9.80.dev.260506
后端: 1. LLM 独立服务与统一计费出口落地:新增 `cmd/llm`、`client/llm` 与 `services/llm/rpc`,补齐 BillingContext、CreditBalanceGuard、价格规则解析、stream usage 归集与 `credit.charge.requested` outbox 发布,active-scheduler / agent / course / memory / gateway fallback 全部改走 llm zrpc,不再各自本地初始化模型。 2. TokenStore 收口为 Credit 权威账本:新增 credit account / ledger / product / order / price-rule / reward-rule 能力与 Redis 快照缓存,扩展 tokenstore rpc/client 支撑余额快照、消耗看板、商品、订单、流水、价格规则和奖励规则,并接入 LLM charge 事件消费完成 Credit 扣费落账。 3. 计费旧链路下线与网关切口切换:`/token-store` 语义整体切到 `/credit-store`,agent chat 移除旧 TokenQuotaGuard,userauth 的 CheckTokenQuota / AdjustTokenUsage 改为废弃,聊天历史落库不再同步旧 token 额度账本,course 图片解析请求补 user_id 进入新计费口径。 前端: 4. 计划广场从 mock 数据切到真实接口:新增 forum api/types,首页支持真实列表、标签、搜索、防抖、点赞、导入和发布计划,详情页补齐帖子详情、评论树、回复和删除评论链路,同时补上“至少一个标签”的前后端约束与默认标签兜底。 5. 商店页切到 Credit 体系并重做展示:顶部改为余额 + Credit/Token 消耗看板,支持 24h/7d/30d/all 周期切换;套餐区展示原价与当前价;历史区改为当前用户 Credit 流水并支持查看更多,整体视觉和交互同步收口。 仓库: 6. 配置与本地启动体系补齐 llm / outbox 编排:`config.example.yaml` 增加 llm rpc 和统一 outbox service 配置,`dev-common.ps1` 把 llm 纳入多服务依赖并自动建 Kafka topic,`docker-compose.yml` 同步初始化 agent/task/memory/active-scheduler/notification/taskclass-forum/llm/token-store 全量 outbox topic。
This commit is contained in:
@@ -92,6 +92,7 @@ func (c *Client) ImportCourses(ctx context.Context, req coursecontracts.UserImpo
|
||||
|
||||
func (c *Client) ParseCourseTableImage(ctx context.Context, req coursecontracts.CourseImageParseRequest) (json.RawMessage, error) {
|
||||
resp, err := c.rpc.ParseCourseImage(ctx, &coursepb.CourseImageRequest{
|
||||
UserId: uint64(req.UserID),
|
||||
Filename: req.Filename,
|
||||
MimeType: req.MIMEType,
|
||||
ImageBytes: req.ImageBytes,
|
||||
|
||||
301
backend/client/llm/client.go
Normal file
301
backend/client/llm/client.go
Normal file
@@ -0,0 +1,301 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
llmservice "github.com/LoveLosita/smartflow/backend/services/llm"
|
||||
llmrpc "github.com/LoveLosita/smartflow/backend/services/llm/rpc"
|
||||
llmcontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/llm"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9096"
|
||||
defaultTimeout = 0
|
||||
defaultPingTimeout = 2 * time.Second
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
type ServiceConfig struct {
|
||||
ClientConfig
|
||||
CourseVisionModel string
|
||||
}
|
||||
|
||||
// Client 是业务进程访问独立 LLM 服务的最小 RPC 适配层。
|
||||
type Client struct {
|
||||
rpc llmrpc.LLMClient
|
||||
}
|
||||
|
||||
func NewClient(cfg ClientConfig) (*Client, error) {
|
||||
timeout := cfg.Timeout
|
||||
if timeout < 0 {
|
||||
timeout = defaultTimeout
|
||||
}
|
||||
endpoints := normalizeEndpoints(cfg.Endpoints)
|
||||
target := strings.TrimSpace(cfg.Target)
|
||||
if len(endpoints) == 0 && target == "" {
|
||||
endpoints = []string{defaultEndpoint}
|
||||
}
|
||||
|
||||
zclient, err := zrpc.NewClient(zrpc.RpcClientConf{
|
||||
Endpoints: endpoints,
|
||||
Target: target,
|
||||
NonBlock: true,
|
||||
Timeout: int64(timeout / time.Millisecond),
|
||||
}, zrpc.WithDialOption(llmrpc.JSONCodecDialOption()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client := &Client{rpc: llmrpc.NewLLMClient(zclient.Conn())}
|
||||
if err = client.ping(resolvePingTimeout(timeout)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// NewService 一次性把远端 LLM RPC 包装回旧的 *llmservice.Service 门面。
|
||||
func NewService(cfg ServiceConfig) (*llmservice.Service, error) {
|
||||
client, err := NewClient(cfg.ClientConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.BuildService(cfg.CourseVisionModel), nil
|
||||
}
|
||||
|
||||
func (c *Client) BuildService(courseVisionModel string) *llmservice.Service {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return llmservice.NewWithClients(llmservice.StaticClients{
|
||||
Lite: buildTextClient(c, llmcontracts.ModelAliasLite),
|
||||
Pro: buildTextClient(c, llmcontracts.ModelAliasPro),
|
||||
Max: buildTextClient(c, llmcontracts.ModelAliasMax),
|
||||
CourseImageResponses: llmservice.NewArkResponsesClientWithFunc(courseVisionModel, func(ctx context.Context, messages []llmservice.ArkResponsesMessage, options llmservice.ArkResponsesOptions) (*llmservice.ArkResponsesResult, error) {
|
||||
return c.GenerateResponsesText(ctx, llmcontracts.ModelAliasCourseImageResponses, messages, options)
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := c.rpc.Ping(ctx, &llmcontracts.PingRequest{})
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
|
||||
func (c *Client) GenerateText(ctx context.Context, modelAlias string, messages []*schema.Message, options llmservice.GenerateOptions) (*llmservice.TextResult, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := c.rpc.GenerateText(ctx, &llmcontracts.TextRequest{
|
||||
ModelAlias: modelAlias,
|
||||
Messages: messages,
|
||||
Options: toContractGenerateOptions(options),
|
||||
Billing: billingFromContext(ctx, modelAlias),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil || resp.Result == nil {
|
||||
return nil, errors.New("llm zrpc service returned empty text response")
|
||||
}
|
||||
return &llmservice.TextResult{
|
||||
Text: resp.Result.Text,
|
||||
Usage: llmservice.CloneUsage(resp.Result.Usage),
|
||||
FinishReason: resp.Result.FinishReason,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) StreamText(ctx context.Context, modelAlias string, messages []*schema.Message, options llmservice.GenerateOptions) (llmservice.StreamReader, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stream, err := c.rpc.StreamText(ctx, &llmcontracts.StreamTextRequest{
|
||||
ModelAlias: modelAlias,
|
||||
Messages: messages,
|
||||
Options: toContractGenerateOptions(options),
|
||||
Billing: billingFromContext(ctx, modelAlias),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return &streamReader{stream: stream}, nil
|
||||
}
|
||||
|
||||
func (c *Client) GenerateResponsesText(ctx context.Context, modelAlias string, messages []llmservice.ArkResponsesMessage, options llmservice.ArkResponsesOptions) (*llmservice.ArkResponsesResult, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := c.rpc.GenerateResponsesText(ctx, &llmcontracts.ResponsesRequest{
|
||||
ModelAlias: modelAlias,
|
||||
Messages: toContractResponsesMessages(messages),
|
||||
Options: toContractResponsesOptions(options),
|
||||
Billing: billingFromContext(ctx, modelAlias),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil || resp.Result == nil {
|
||||
return nil, errors.New("llm zrpc service returned empty responses response")
|
||||
}
|
||||
return toServiceResponsesResult(resp.Result), nil
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("llm zrpc client is not initialized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) ping(timeout time.Duration) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
return c.Ping(ctx)
|
||||
}
|
||||
|
||||
type streamReader struct {
|
||||
stream llmrpc.LLM_StreamTextClient
|
||||
}
|
||||
|
||||
func (r *streamReader) Recv() (*schema.Message, error) {
|
||||
if r == nil || r.stream == nil {
|
||||
return nil, errors.New("llm zrpc stream is not initialized")
|
||||
}
|
||||
|
||||
chunk, err := r.stream.Recv()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil, io.EOF
|
||||
}
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if chunk == nil {
|
||||
return nil, errors.New("llm zrpc service returned empty stream chunk")
|
||||
}
|
||||
return chunk.Message, nil
|
||||
}
|
||||
|
||||
func (r *streamReader) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildTextClient(remote *Client, modelAlias string) *llmservice.Client {
|
||||
return llmservice.NewClient(
|
||||
func(ctx context.Context, messages []*schema.Message, options llmservice.GenerateOptions) (*llmservice.TextResult, error) {
|
||||
return remote.GenerateText(ctx, modelAlias, messages, options)
|
||||
},
|
||||
func(ctx context.Context, messages []*schema.Message, options llmservice.GenerateOptions) (llmservice.StreamReader, error) {
|
||||
return remote.StreamText(ctx, modelAlias, messages, options)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func billingFromContext(ctx context.Context, modelAlias string) *llmcontracts.BillingContext {
|
||||
billing, ok := llmservice.BillingContextFromContext(ctx)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(billing.ModelAlias) == "" {
|
||||
billing.ModelAlias = strings.TrimSpace(modelAlias)
|
||||
}
|
||||
return &llmcontracts.BillingContext{
|
||||
UserID: billing.UserID,
|
||||
EventID: billing.EventID,
|
||||
Scene: billing.Scene,
|
||||
RequestID: billing.RequestID,
|
||||
ConversationID: billing.ConversationID,
|
||||
ModelAlias: billing.ModelAlias,
|
||||
SkipCharge: billing.SkipCharge,
|
||||
}
|
||||
}
|
||||
|
||||
func toContractGenerateOptions(input llmservice.GenerateOptions) llmcontracts.GenerateOptions {
|
||||
return llmcontracts.GenerateOptions{
|
||||
Temperature: input.Temperature,
|
||||
MaxTokens: input.MaxTokens,
|
||||
Thinking: string(input.Thinking),
|
||||
Metadata: input.Metadata,
|
||||
}
|
||||
}
|
||||
|
||||
func toContractResponsesMessages(input []llmservice.ArkResponsesMessage) []llmcontracts.ResponsesMessage {
|
||||
if len(input) == 0 {
|
||||
return nil
|
||||
}
|
||||
output := make([]llmcontracts.ResponsesMessage, 0, len(input))
|
||||
for _, item := range input {
|
||||
output = append(output, llmcontracts.ResponsesMessage{
|
||||
Role: item.Role,
|
||||
Text: item.Text,
|
||||
ImageURL: item.ImageURL,
|
||||
ImageDetail: item.ImageDetail,
|
||||
})
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
func toContractResponsesOptions(input llmservice.ArkResponsesOptions) llmcontracts.ResponsesOptions {
|
||||
return llmcontracts.ResponsesOptions{
|
||||
Model: input.Model,
|
||||
Temperature: input.Temperature,
|
||||
MaxOutputTokens: input.MaxOutputTokens,
|
||||
Thinking: string(input.Thinking),
|
||||
TextFormat: input.TextFormat,
|
||||
}
|
||||
}
|
||||
|
||||
func toServiceResponsesResult(result *llmcontracts.ResponsesResult) *llmservice.ArkResponsesResult {
|
||||
if result == nil {
|
||||
return nil
|
||||
}
|
||||
output := &llmservice.ArkResponsesResult{
|
||||
Text: result.Text,
|
||||
Status: result.Status,
|
||||
IncompleteReason: result.IncompleteReason,
|
||||
ErrorCode: result.ErrorCode,
|
||||
ErrorMessage: result.ErrorMessage,
|
||||
}
|
||||
if result.Usage != nil {
|
||||
output.Usage = &llmservice.ArkResponsesUsage{
|
||||
InputTokens: result.Usage.InputTokens,
|
||||
OutputTokens: result.Usage.OutputTokens,
|
||||
TotalTokens: result.Usage.TotalTokens,
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
func normalizeEndpoints(values []string) []string {
|
||||
endpoints := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
if trimmed != "" {
|
||||
endpoints = append(endpoints, trimmed)
|
||||
}
|
||||
}
|
||||
return endpoints
|
||||
}
|
||||
|
||||
func resolvePingTimeout(timeout time.Duration) time.Duration {
|
||||
if timeout > 0 && timeout < defaultPingTimeout {
|
||||
return timeout
|
||||
}
|
||||
return defaultPingTimeout
|
||||
}
|
||||
73
backend/client/llm/errors.go
Normal file
73
backend/client/llm/errors.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func responseFromRPCError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return wrapRPCError(err)
|
||||
}
|
||||
if message, ok := messageFromStatus(st); ok {
|
||||
switch st.Code() {
|
||||
case codes.InvalidArgument, codes.ResourceExhausted, codes.FailedPrecondition:
|
||||
return errors.New(message)
|
||||
}
|
||||
}
|
||||
|
||||
switch st.Code() {
|
||||
case codes.InvalidArgument, codes.ResourceExhausted, codes.FailedPrecondition:
|
||||
return errors.New(strings.TrimSpace(st.Message()))
|
||||
case codes.Internal, codes.Unknown, codes.Unavailable, codes.DeadlineExceeded, codes.DataLoss, codes.Unimplemented:
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "llm zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
default:
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "llm zrpc service rejected request"
|
||||
}
|
||||
return errors.New(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func messageFromStatus(st *status.Status) (string, bool) {
|
||||
if st == nil {
|
||||
return "", false
|
||||
}
|
||||
for _, detail := range st.Details() {
|
||||
info, ok := detail.(*errdetails.ErrorInfo)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
message := strings.TrimSpace(st.Message())
|
||||
if message == "" && info.Metadata != nil {
|
||||
message = strings.TrimSpace(info.Metadata["info"])
|
||||
}
|
||||
if message == "" {
|
||||
message = strings.TrimSpace(info.Reason)
|
||||
}
|
||||
return message, message != ""
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func wrapRPCError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("调用 llm zrpc 服务失败: %w", err)
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
package tokenstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/services/tokenstore/rpc/pb"
|
||||
tokencontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/tokenstore"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
)
|
||||
|
||||
@@ -23,48 +20,12 @@ type ClientConfig struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// ProductSnapshot 是订单详情里内嵌的商品快照。
|
||||
// Client 是 gateway 访问 tokenstore zrpc 的统一 Credit 语义适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只承载 HTTP gateway 当前需要透出的商品摘要;
|
||||
// 2. 不补充 description、price 等商品列表字段,避免把详情快照扩成第二份商品实体;
|
||||
// 3. 若下游 proto/contract 还未合入对应字段,这里允许保持 nil/零值兜底。
|
||||
type ProductSnapshot struct {
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Name string `json:"name"`
|
||||
TokenAmount int64 `json:"token_amount"`
|
||||
}
|
||||
|
||||
// OrderView 是 gateway 侧订单展示结构。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 复用 token-store contract 里已稳定的订单字段;
|
||||
// 2. 为前端 P0 额外承载 product_snapshot / product_name / quantity 三个 HTTP 所需字段;
|
||||
// 3. 不反向影响 shared/contracts,等并行 worker 合入正式字段后可再收敛。
|
||||
type OrderView struct {
|
||||
OrderID uint64 `json:"order_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
Status string `json:"status"`
|
||||
ProductSnapshot *ProductSnapshot `json:"product_snapshot,omitempty"`
|
||||
ProductName string `json:"product_name,omitempty"`
|
||||
Quantity int `json:"quantity"`
|
||||
TokenAmount int64 `json:"token_amount"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
PriceText string `json:"price_text"`
|
||||
Currency string `json:"currency"`
|
||||
PaymentMode string `json:"payment_mode"`
|
||||
Grant *tokencontracts.TokenGrantView `json:"grant"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
PaidAt *string `json:"paid_at"`
|
||||
GrantedAt *string `json:"granted_at"`
|
||||
}
|
||||
|
||||
// Client 是 gateway 侧访问 token-store zrpc 的适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责 HTTP gateway 与 token-store zrpc 之间的协议转译;
|
||||
// 2. 不直连 token_* 表,也不承载订单/支付业务规则;
|
||||
// 3. gRPC 业务错误会在这里反解回 respond.Response,便于 HTTP 层统一返回。
|
||||
// 1. 只负责 HTTP gateway 与 tokenstore zrpc 之间的协议转译;
|
||||
// 2. 不直连底层 credit_* 表,也不承载订单/充值/扣费业务规则;
|
||||
// 3. gRPC 业务错误会在这里反解成普通 error / respond.Response,交给 HTTP 层统一处理。
|
||||
type Client struct {
|
||||
rpc pb.TokenStoreServiceClient
|
||||
}
|
||||
@@ -92,150 +53,6 @@ func NewClient(cfg ClientConfig) (*Client, error) {
|
||||
return &Client{rpc: pb.NewTokenStoreServiceClient(zclient.Conn())}, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetSummary(ctx context.Context, actorUserID uint64) (*tokencontracts.TokenSummary, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetSummary(ctx, &pb.GetTokenSummaryRequest{ActorUserId: actorUserID})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty get summary response")
|
||||
}
|
||||
summary := tokenSummaryFromPB(resp.Summary)
|
||||
return &summary, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListProducts(ctx context.Context, actorUserID uint64) ([]tokencontracts.TokenProductView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.ListProducts(ctx, &pb.ListTokenProductsRequest{ActorUserId: actorUserID})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty list products response")
|
||||
}
|
||||
return tokenProductsFromPB(resp.Items), nil
|
||||
}
|
||||
|
||||
func (c *Client) CreateOrder(ctx context.Context, req tokencontracts.CreateTokenOrderRequest) (*OrderView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.CreateOrder(ctx, &pb.CreateTokenOrderRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
ProductId: req.ProductID,
|
||||
Quantity: int32(req.Quantity),
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty create order response")
|
||||
}
|
||||
order := tokenOrderFromPB(resp.Order)
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListOrders(ctx context.Context, req tokencontracts.ListTokenOrdersRequest) ([]OrderView, tokencontracts.PageResult, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, tokencontracts.PageResult{}, err
|
||||
}
|
||||
resp, err := c.rpc.ListOrders(ctx, &pb.ListTokenOrdersRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
Page: int32(req.Page),
|
||||
PageSize: int32(req.PageSize),
|
||||
Status: req.Status,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, tokencontracts.PageResult{}, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, tokencontracts.PageResult{}, errors.New("tokenstore zrpc service returned empty list orders response")
|
||||
}
|
||||
return tokenOrdersFromPB(resp.Items), pageFromPB(resp.Page), nil
|
||||
}
|
||||
|
||||
func (c *Client) GetOrder(ctx context.Context, actorUserID uint64, orderID uint64) (*OrderView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetOrder(ctx, &pb.GetTokenOrderRequest{
|
||||
ActorUserId: actorUserID,
|
||||
OrderId: orderID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty get order response")
|
||||
}
|
||||
order := tokenOrderFromPB(resp.Order)
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (c *Client) MockPaidOrder(ctx context.Context, req tokencontracts.MockPaidOrderRequest) (*OrderView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.MockPaidOrder(ctx, &pb.MockPaidOrderRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
OrderId: req.OrderID,
|
||||
MockChannel: req.MockChannel,
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty mock paid response")
|
||||
}
|
||||
order := tokenOrderFromPB(resp.Order)
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListGrants(ctx context.Context, req tokencontracts.ListTokenGrantsRequest) ([]tokencontracts.TokenGrantView, tokencontracts.PageResult, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, tokencontracts.PageResult{}, err
|
||||
}
|
||||
resp, err := c.rpc.ListGrants(ctx, &pb.ListTokenGrantsRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
Page: int32(req.Page),
|
||||
PageSize: int32(req.PageSize),
|
||||
Source: req.Source,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, tokencontracts.PageResult{}, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, tokencontracts.PageResult{}, errors.New("tokenstore zrpc service returned empty list grants response")
|
||||
}
|
||||
return tokenGrantsFromPB(resp.Items), pageFromPB(resp.Page), nil
|
||||
}
|
||||
|
||||
func (c *Client) RecordForumRewardGrant(ctx context.Context, req tokencontracts.RecordForumRewardGrantRequest) (*tokencontracts.TokenGrantView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.RecordForumRewardGrant(ctx, &pb.RecordForumRewardGrantRequest{
|
||||
EventId: req.EventID,
|
||||
ReceiverUserId: req.ReceiverUserID,
|
||||
Source: req.Source,
|
||||
SourceRefId: req.SourceRefID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty record forum reward grant response")
|
||||
}
|
||||
return tokenGrantFromPB(resp.Grant), nil
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("tokenstore zrpc client is not initialized")
|
||||
@@ -254,150 +71,6 @@ func normalizeEndpoints(values []string) []string {
|
||||
return endpoints
|
||||
}
|
||||
|
||||
func pageFromPB(page *pb.PageResponse) tokencontracts.PageResult {
|
||||
if page == nil {
|
||||
return tokencontracts.PageResult{}
|
||||
}
|
||||
return tokencontracts.PageResult{
|
||||
Page: int(page.Page),
|
||||
PageSize: int(page.PageSize),
|
||||
Total: int(page.Total),
|
||||
HasMore: page.HasMore,
|
||||
}
|
||||
}
|
||||
|
||||
func tokenSummaryFromPB(summary *pb.TokenSummary) tokencontracts.TokenSummary {
|
||||
if summary == nil {
|
||||
return tokencontracts.TokenSummary{}
|
||||
}
|
||||
return tokencontracts.TokenSummary{
|
||||
RecordedTokenTotal: summary.RecordedTokenTotal,
|
||||
AppliedTokenTotal: summary.AppliedTokenTotal,
|
||||
PendingApplyTokenTotal: summary.PendingApplyTokenTotal,
|
||||
QuotaSyncStatus: summary.QuotaSyncStatus,
|
||||
Tip: summary.Tip,
|
||||
}
|
||||
}
|
||||
|
||||
func tokenProductFromPB(product *pb.TokenProductView) tokencontracts.TokenProductView {
|
||||
if product == nil {
|
||||
return tokencontracts.TokenProductView{}
|
||||
}
|
||||
return tokencontracts.TokenProductView{
|
||||
ProductID: product.ProductId,
|
||||
Name: product.Name,
|
||||
Description: product.Description,
|
||||
TokenAmount: product.TokenAmount,
|
||||
PriceCent: product.PriceCent,
|
||||
PriceText: product.PriceText,
|
||||
Currency: product.Currency,
|
||||
Badge: product.Badge,
|
||||
Status: product.Status,
|
||||
SortOrder: int(product.SortOrder),
|
||||
}
|
||||
}
|
||||
|
||||
func tokenProductsFromPB(items []*pb.TokenProductView) []tokencontracts.TokenProductView {
|
||||
if len(items) == 0 {
|
||||
return []tokencontracts.TokenProductView{}
|
||||
}
|
||||
result := make([]tokencontracts.TokenProductView, 0, len(items))
|
||||
for _, item := range items {
|
||||
result = append(result, tokenProductFromPB(item))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func tokenGrantFromPB(grant *pb.TokenGrantView) *tokencontracts.TokenGrantView {
|
||||
if grant == nil {
|
||||
return nil
|
||||
}
|
||||
return &tokencontracts.TokenGrantView{
|
||||
GrantID: grant.GrantId,
|
||||
EventID: grant.EventId,
|
||||
Source: grant.Source,
|
||||
SourceLabel: grant.SourceLabel,
|
||||
Amount: grant.Amount,
|
||||
Status: grant.Status,
|
||||
QuotaApplied: grant.QuotaApplied,
|
||||
Description: grant.Description,
|
||||
CreatedAt: grant.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func tokenGrantsFromPB(items []*pb.TokenGrantView) []tokencontracts.TokenGrantView {
|
||||
if len(items) == 0 {
|
||||
return []tokencontracts.TokenGrantView{}
|
||||
}
|
||||
result := make([]tokencontracts.TokenGrantView, 0, len(items))
|
||||
for _, item := range items {
|
||||
if grant := tokenGrantFromPB(item); grant != nil {
|
||||
result = append(result, *grant)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func tokenOrderFromPB(order *pb.TokenOrderView) OrderView {
|
||||
if order == nil {
|
||||
return OrderView{}
|
||||
}
|
||||
productSnapshot := tokenProductSnapshotFromJSON(order.ProductSnapshot)
|
||||
productName := strings.TrimSpace(order.ProductName)
|
||||
if productName == "" && productSnapshot != nil {
|
||||
productName = productSnapshot.Name
|
||||
}
|
||||
return OrderView{
|
||||
OrderID: order.OrderId,
|
||||
OrderNo: order.OrderNo,
|
||||
Status: order.Status,
|
||||
ProductSnapshot: productSnapshot,
|
||||
ProductName: productName,
|
||||
Quantity: int(order.Quantity),
|
||||
TokenAmount: order.TokenAmount,
|
||||
AmountCent: order.AmountCent,
|
||||
PriceText: order.PriceText,
|
||||
Currency: order.Currency,
|
||||
PaymentMode: order.PaymentMode,
|
||||
Grant: tokenGrantFromPB(order.Grant),
|
||||
CreatedAt: order.CreatedAt,
|
||||
PaidAt: stringPtrFromNonEmpty(order.PaidAt),
|
||||
GrantedAt: stringPtrFromNonEmpty(order.GrantedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func tokenOrdersFromPB(items []*pb.TokenOrderView) []OrderView {
|
||||
if len(items) == 0 {
|
||||
return []OrderView{}
|
||||
}
|
||||
result := make([]OrderView, 0, len(items))
|
||||
for _, item := range items {
|
||||
result = append(result, tokenOrderFromPB(item))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// tokenProductSnapshotFromJSON 负责把 RPC 内部快照字符串转成 HTTP 展示对象。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只解析 product_id / name / token_amount 三个前端需要的字段;
|
||||
// 2. 不把解析失败暴露成接口错误,避免历史脏快照影响订单主流程展示;
|
||||
// 3. 不反查商品表,订单详情必须以当时下单快照为准。
|
||||
func tokenProductSnapshotFromJSON(raw string) *ProductSnapshot {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" {
|
||||
return nil
|
||||
}
|
||||
var snapshot ProductSnapshot
|
||||
if err := json.Unmarshal([]byte(trimmed), &snapshot); err != nil {
|
||||
return nil
|
||||
}
|
||||
if snapshot.ProductID == 0 && snapshot.Name == "" && snapshot.TokenAmount == 0 {
|
||||
return nil
|
||||
}
|
||||
return &snapshot
|
||||
}
|
||||
|
||||
func stringPtrFromNonEmpty(value string) *string {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
if trimmed == "" {
|
||||
|
||||
383
backend/client/tokenstore/credit.go
Normal file
383
backend/client/tokenstore/credit.go
Normal file
@@ -0,0 +1,383 @@
|
||||
package tokenstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/services/tokenstore/rpc/pb"
|
||||
creditcontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/creditstore"
|
||||
)
|
||||
|
||||
func (c *Client) GetCreditBalanceSnapshot(ctx context.Context, userID uint64) (*creditcontracts.CreditBalanceSnapshot, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetCreditBalanceSnapshot(ctx, &pb.GetCreditBalanceSnapshotRequest{UserId: userID})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty get credit balance snapshot response")
|
||||
}
|
||||
snapshot := creditBalanceSnapshotFromPB(resp.Snapshot)
|
||||
return &snapshot, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetCreditConsumptionDashboard(ctx context.Context, req creditcontracts.GetCreditConsumptionDashboardRequest) (*creditcontracts.CreditConsumptionDashboardView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetCreditConsumptionDashboard(ctx, &pb.GetCreditConsumptionDashboardRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
Period: req.Period,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty get credit consumption dashboard response")
|
||||
}
|
||||
dashboard := creditConsumptionDashboardFromPB(resp.Dashboard)
|
||||
return &dashboard, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListCreditProducts(ctx context.Context, actorUserID uint64) ([]creditcontracts.CreditProductView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.ListCreditProducts(ctx, &pb.ListCreditProductsRequest{ActorUserId: actorUserID})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty list credit products response")
|
||||
}
|
||||
return creditProductsFromPB(resp.Items), nil
|
||||
}
|
||||
|
||||
func (c *Client) CreateCreditOrder(ctx context.Context, req creditcontracts.CreateCreditOrderRequest) (*creditcontracts.CreditOrderView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.CreateCreditOrder(ctx, &pb.CreateCreditOrderRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
ProductId: req.ProductID,
|
||||
Quantity: int32(req.Quantity),
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty create credit order response")
|
||||
}
|
||||
order := creditOrderFromPB(resp.Order)
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListCreditOrders(ctx context.Context, req creditcontracts.ListCreditOrdersRequest) ([]creditcontracts.CreditOrderView, creditcontracts.PageResult, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, creditcontracts.PageResult{}, err
|
||||
}
|
||||
resp, err := c.rpc.ListCreditOrders(ctx, &pb.ListCreditOrdersRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
Page: int32(req.Page),
|
||||
PageSize: int32(req.PageSize),
|
||||
Status: req.Status,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, creditcontracts.PageResult{}, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, creditcontracts.PageResult{}, errors.New("tokenstore zrpc service returned empty list credit orders response")
|
||||
}
|
||||
return creditOrdersFromPB(resp.Items), creditPageFromPB(resp.Page), nil
|
||||
}
|
||||
|
||||
func (c *Client) GetCreditOrder(ctx context.Context, actorUserID uint64, orderID uint64) (*creditcontracts.CreditOrderView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetCreditOrder(ctx, &pb.GetCreditOrderRequest{
|
||||
ActorUserId: actorUserID,
|
||||
OrderId: orderID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty get credit order response")
|
||||
}
|
||||
order := creditOrderFromPB(resp.Order)
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (c *Client) MockPaidCreditOrder(ctx context.Context, req creditcontracts.MockPaidCreditOrderRequest) (*creditcontracts.CreditOrderView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.MockPaidCreditOrder(ctx, &pb.MockPaidCreditOrderRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
OrderId: req.OrderID,
|
||||
MockChannel: req.MockChannel,
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty mock paid credit order response")
|
||||
}
|
||||
order := creditOrderFromPB(resp.Order)
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListCreditTransactions(ctx context.Context, req creditcontracts.ListCreditTransactionsRequest) ([]creditcontracts.CreditTransactionView, creditcontracts.PageResult, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, creditcontracts.PageResult{}, err
|
||||
}
|
||||
resp, err := c.rpc.ListCreditTransactions(ctx, &pb.ListCreditTransactionsRequest{
|
||||
ActorUserId: req.ActorUserID,
|
||||
Page: int32(req.Page),
|
||||
PageSize: int32(req.PageSize),
|
||||
Source: req.Source,
|
||||
Direction: req.Direction,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, creditcontracts.PageResult{}, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, creditcontracts.PageResult{}, errors.New("tokenstore zrpc service returned empty list credit transactions response")
|
||||
}
|
||||
return creditTransactionsFromPB(resp.Items), creditPageFromPB(resp.Page), nil
|
||||
}
|
||||
|
||||
func (c *Client) ListCreditPriceRules(ctx context.Context, req creditcontracts.ListCreditPriceRulesRequest) ([]creditcontracts.CreditPriceRuleView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.ListCreditPriceRules(ctx, &pb.ListCreditPriceRulesRequest{
|
||||
Scene: req.Scene,
|
||||
ProviderName: req.ProviderName,
|
||||
ModelName: req.ModelName,
|
||||
Status: req.Status,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty list credit price rules response")
|
||||
}
|
||||
return creditPriceRulesFromPB(resp.Items), nil
|
||||
}
|
||||
|
||||
func (c *Client) ListCreditRewardRules(ctx context.Context, req creditcontracts.ListCreditRewardRulesRequest) ([]creditcontracts.CreditRewardRuleView, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.ListCreditRewardRules(ctx, &pb.ListCreditRewardRulesRequest{
|
||||
Source: req.Source,
|
||||
Status: req.Status,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("tokenstore zrpc service returned empty list credit reward rules response")
|
||||
}
|
||||
return creditRewardRulesFromPB(resp.Items), nil
|
||||
}
|
||||
|
||||
func creditBalanceSnapshotFromPB(snapshot *pb.CreditBalanceSnapshotView) creditcontracts.CreditBalanceSnapshot {
|
||||
if snapshot == nil {
|
||||
return creditcontracts.CreditBalanceSnapshot{}
|
||||
}
|
||||
return creditcontracts.CreditBalanceSnapshot{
|
||||
UserID: snapshot.UserId,
|
||||
Balance: snapshot.Balance,
|
||||
TotalRecharged: snapshot.TotalRecharged,
|
||||
TotalRewarded: snapshot.TotalRewarded,
|
||||
TotalConsumed: snapshot.TotalConsumed,
|
||||
IsBlocked: snapshot.IsBlocked,
|
||||
SnapshotSource: snapshot.SnapshotSource,
|
||||
UpdatedAt: snapshot.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func creditConsumptionDashboardFromPB(view *pb.CreditConsumptionDashboardView) creditcontracts.CreditConsumptionDashboardView {
|
||||
if view == nil {
|
||||
return creditcontracts.CreditConsumptionDashboardView{}
|
||||
}
|
||||
return creditcontracts.CreditConsumptionDashboardView{
|
||||
Period: view.Period,
|
||||
CreditConsumed: view.CreditConsumed,
|
||||
TokenConsumed: view.TokenConsumed,
|
||||
}
|
||||
}
|
||||
|
||||
func creditProductFromPB(product *pb.CreditProductView) creditcontracts.CreditProductView {
|
||||
if product == nil {
|
||||
return creditcontracts.CreditProductView{}
|
||||
}
|
||||
return creditcontracts.CreditProductView{
|
||||
ProductID: product.ProductId,
|
||||
Name: product.Name,
|
||||
Description: product.Description,
|
||||
CreditAmount: product.CreditAmount,
|
||||
PriceCent: product.PriceCent,
|
||||
OriginalPriceCent: product.OriginalPriceCent,
|
||||
PriceText: product.PriceText,
|
||||
Currency: product.Currency,
|
||||
Badge: product.Badge,
|
||||
Status: product.Status,
|
||||
SortOrder: int(product.SortOrder),
|
||||
}
|
||||
}
|
||||
|
||||
func creditProductsFromPB(items []*pb.CreditProductView) []creditcontracts.CreditProductView {
|
||||
if len(items) == 0 {
|
||||
return []creditcontracts.CreditProductView{}
|
||||
}
|
||||
result := make([]creditcontracts.CreditProductView, 0, len(items))
|
||||
for _, item := range items {
|
||||
result = append(result, creditProductFromPB(item))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func creditOrderFromPB(order *pb.CreditOrderView) creditcontracts.CreditOrderView {
|
||||
if order == nil {
|
||||
return creditcontracts.CreditOrderView{}
|
||||
}
|
||||
return creditcontracts.CreditOrderView{
|
||||
OrderID: order.OrderId,
|
||||
OrderNo: order.OrderNo,
|
||||
Status: order.Status,
|
||||
ProductSnapshot: order.ProductSnapshot,
|
||||
ProductName: order.ProductName,
|
||||
Quantity: int(order.Quantity),
|
||||
CreditAmount: order.CreditAmount,
|
||||
AmountCent: order.AmountCent,
|
||||
PriceText: order.PriceText,
|
||||
Currency: order.Currency,
|
||||
PaymentMode: order.PaymentMode,
|
||||
CreatedAt: order.CreatedAt,
|
||||
PaidAt: stringPtrFromNonEmpty(order.PaidAt),
|
||||
CreditedAt: stringPtrFromNonEmpty(order.CreditedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func creditOrdersFromPB(items []*pb.CreditOrderView) []creditcontracts.CreditOrderView {
|
||||
if len(items) == 0 {
|
||||
return []creditcontracts.CreditOrderView{}
|
||||
}
|
||||
result := make([]creditcontracts.CreditOrderView, 0, len(items))
|
||||
for _, item := range items {
|
||||
result = append(result, creditOrderFromPB(item))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func creditTransactionFromPB(item *pb.CreditTransactionView) creditcontracts.CreditTransactionView {
|
||||
if item == nil {
|
||||
return creditcontracts.CreditTransactionView{}
|
||||
}
|
||||
var orderID *uint64
|
||||
if item.OrderId > 0 {
|
||||
value := item.OrderId
|
||||
orderID = &value
|
||||
}
|
||||
return creditcontracts.CreditTransactionView{
|
||||
TransactionID: item.TransactionId,
|
||||
EventID: item.EventId,
|
||||
Source: item.Source,
|
||||
SourceLabel: item.SourceLabel,
|
||||
Direction: item.Direction,
|
||||
Amount: item.Amount,
|
||||
BalanceAfter: item.BalanceAfter,
|
||||
Status: item.Status,
|
||||
Description: item.Description,
|
||||
MetadataJSON: item.MetadataJson,
|
||||
CreatedAt: item.CreatedAt,
|
||||
OrderID: orderID,
|
||||
}
|
||||
}
|
||||
|
||||
func creditTransactionsFromPB(items []*pb.CreditTransactionView) []creditcontracts.CreditTransactionView {
|
||||
if len(items) == 0 {
|
||||
return []creditcontracts.CreditTransactionView{}
|
||||
}
|
||||
result := make([]creditcontracts.CreditTransactionView, 0, len(items))
|
||||
for _, item := range items {
|
||||
result = append(result, creditTransactionFromPB(item))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func creditPriceRuleFromPB(item *pb.CreditPriceRuleView) creditcontracts.CreditPriceRuleView {
|
||||
if item == nil {
|
||||
return creditcontracts.CreditPriceRuleView{}
|
||||
}
|
||||
return creditcontracts.CreditPriceRuleView{
|
||||
RuleID: item.RuleId,
|
||||
Scene: item.Scene,
|
||||
ProviderName: item.ProviderName,
|
||||
ModelName: item.ModelName,
|
||||
InputPriceMicros: item.InputPriceMicros,
|
||||
OutputPriceMicros: item.OutputPriceMicros,
|
||||
CachedPriceMicros: item.CachedPriceMicros,
|
||||
ReasoningPriceMicros: item.ReasoningPriceMicros,
|
||||
CreditPerYuan: item.CreditPerYuan,
|
||||
Status: item.Status,
|
||||
Priority: int(item.Priority),
|
||||
Description: item.Description,
|
||||
}
|
||||
}
|
||||
|
||||
func creditPriceRulesFromPB(items []*pb.CreditPriceRuleView) []creditcontracts.CreditPriceRuleView {
|
||||
if len(items) == 0 {
|
||||
return []creditcontracts.CreditPriceRuleView{}
|
||||
}
|
||||
result := make([]creditcontracts.CreditPriceRuleView, 0, len(items))
|
||||
for _, item := range items {
|
||||
result = append(result, creditPriceRuleFromPB(item))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func creditRewardRuleFromPB(item *pb.CreditRewardRuleView) creditcontracts.CreditRewardRuleView {
|
||||
if item == nil {
|
||||
return creditcontracts.CreditRewardRuleView{}
|
||||
}
|
||||
return creditcontracts.CreditRewardRuleView{
|
||||
RuleID: item.RuleId,
|
||||
Source: item.Source,
|
||||
Name: item.Name,
|
||||
Amount: item.Amount,
|
||||
Status: item.Status,
|
||||
Description: item.Description,
|
||||
}
|
||||
}
|
||||
|
||||
func creditRewardRulesFromPB(items []*pb.CreditRewardRuleView) []creditcontracts.CreditRewardRuleView {
|
||||
if len(items) == 0 {
|
||||
return []creditcontracts.CreditRewardRuleView{}
|
||||
}
|
||||
result := make([]creditcontracts.CreditRewardRuleView, 0, len(items))
|
||||
for _, item := range items {
|
||||
result = append(result, creditRewardRuleFromPB(item))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func creditPageFromPB(page *pb.PageResponse) creditcontracts.PageResult {
|
||||
if page == nil {
|
||||
return creditcontracts.PageResult{}
|
||||
}
|
||||
return creditcontracts.PageResult{
|
||||
Page: int(page.Page),
|
||||
PageSize: int(page.PageSize),
|
||||
Total: int(page.Total),
|
||||
HasMore: page.HasMore,
|
||||
}
|
||||
}
|
||||
@@ -138,50 +138,6 @@ func (c *Client) ValidateAccessToken(ctx context.Context, accessToken string) (*
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) CheckTokenQuota(ctx context.Context, userID int) (*contracts.CheckTokenQuotaResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.CheckTokenQuota(ctx, &pb.CheckTokenQuotaRequest{
|
||||
UserId: int64(userID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("userauth zrpc service returned empty quota response")
|
||||
}
|
||||
return &contracts.CheckTokenQuotaResponse{
|
||||
Allowed: resp.Allowed,
|
||||
TokenLimit: int(resp.TokenLimit),
|
||||
TokenUsage: int(resp.TokenUsage),
|
||||
LastResetAt: timeFromUnixNano(resp.LastResetAtUnixNano),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) AdjustTokenUsage(ctx context.Context, req contracts.AdjustTokenUsageRequest) (*contracts.CheckTokenQuotaResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.AdjustTokenUsage(ctx, &pb.AdjustTokenUsageRequest{
|
||||
EventId: req.EventID,
|
||||
UserId: int64(req.UserID),
|
||||
TokenDelta: int64(req.TokenDelta),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("userauth zrpc service returned empty adjust response")
|
||||
}
|
||||
return &contracts.CheckTokenQuotaResponse{
|
||||
Allowed: resp.Allowed,
|
||||
TokenLimit: int(resp.TokenLimit),
|
||||
TokenUsage: int(resp.TokenUsage),
|
||||
LastResetAt: timeFromUnixNano(resp.LastResetAtUnixNano),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("userauth zrpc client is not initialized")
|
||||
|
||||
Reference in New Issue
Block a user