feat: 迁移plant

This commit is contained in:
Blizzard
2026-05-23 13:55:05 +08:00
parent a93477ea8e
commit ae6d03d351
228 changed files with 25296 additions and 917 deletions
+7
View File
@@ -16,6 +16,13 @@ SystemRpc:
- 192.168.100.127:2379 - 192.168.100.127:2379
Key: system.rpc Key: system.rpc
# 各业务 RPC(新增小程序时在此追加)
PlantRpc:
Etcd:
Hosts:
- 192.168.100.127:2379
Key: plant.rpc
# Redis(验证码存储,DB2 # Redis(验证码存储,DB2
Redis: Redis:
Host: 192.168.100.127:6379 Host: 192.168.100.127:6379
+4 -1
View File
@@ -12,7 +12,10 @@ type Config struct {
AccessExpire int64 AccessExpire int64
} }
SystemRpc zrpc.RpcClientConf SystemRpc zrpc.RpcClientConf
Redis struct { // 各业务 RPC(可选,新增小程序时在此追加)
PlantRpc zrpc.RpcClientConf `json:",optional"`
// RadioRpc zrpc.RpcClientConf `json:",optional"` // 待接入
Redis struct {
Host string Host string
Pass string Pass string
DB int `json:",optional"` DB int `json:",optional"`
@@ -22,6 +22,12 @@ func MiniLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return return
} }
// 从请求头读取 clientId,优先级高于 body
// 前端统一在请求头设置 X-Client-Id: plant_mini / radio_mini 等
if clientId := r.Header.Get("X-Client-Id"); clientId != "" {
req.ClientId = clientId
}
l := auth.NewMiniLoginLogic(r.Context(), svcCtx) l := auth.NewMiniLoginLogic(r.Context(), svcCtx)
resp, err := l.MiniLogin(&req) resp, err := l.MiniLogin(&req)
if err != nil { if err != nil {
@@ -13,11 +13,24 @@ import (
"sundynix-micro-go/app/auth/api/internal/svc" "sundynix-micro-go/app/auth/api/internal/svc"
"sundynix-micro-go/app/auth/api/internal/types" "sundynix-micro-go/app/auth/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
sysPb "sundynix-micro-go/app/system/rpc/system" sysPb "sundynix-micro-go/app/system/rpc/system"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
) )
// clientId 常量 — 新增小程序时在此添加
const (
ClientIdPlant = "sundynix-plant" // 植物小程序
// ClientIdRadio = "radio_mini" // 电台小程序(待接入)
)
// MiniAppAdditionalInfo 小程序客户端扩展信息(存储在 additional_info JSON 字段中)
type MiniAppAdditionalInfo struct {
AppId string `json:"appId"`
AppSecret string `json:"appSecret"`
}
type MiniLoginLogic struct { type MiniLoginLogic struct {
logx.Logger logx.Logger
ctx context.Context ctx context.Context
@@ -43,14 +56,30 @@ type WxCode2SessionResp struct {
} }
func (l *MiniLoginLogic) MiniLogin(req *types.MiniLoginReq) (resp *types.LoginResp, err error) { func (l *MiniLoginLogic) MiniLogin(req *types.MiniLoginReq) (resp *types.LoginResp, err error) {
// 1. 调用微信接口获取openid和session_key // 1. 根据 clientId 查询客户端配置,从 additional_info 中动态读取 appId/appSecret
// TODO: 从配置中获取AppId和AppSecret,当前先用固定值 clientResp, err := l.svcCtx.SystemRpc.GetClientById(l.ctx, &sysPb.GetClientByIdReq{
appID := "wxb463820bf36dd5d6" ClientId: req.ClientId,
appSecret := "731784a74c76c6d31fa00bb847af2c7d" })
if err != nil {
l.Errorf("[MiniLogin] 查询客户端失败: clientId=%s, err=%v", req.ClientId, err)
return nil, fmt.Errorf("无效的客户端: %s", req.ClientId)
}
// 2. 解析 additional_info 获取微信凭证
var miniInfo MiniAppAdditionalInfo
if err = json.Unmarshal([]byte(clientResp.Client.AdditionalInfo), &miniInfo); err != nil {
l.Errorf("[MiniLogin] 解析客户端 additional_info 失败: clientId=%s, info=%s, err=%v",
req.ClientId, clientResp.Client.AdditionalInfo, err)
return nil, fmt.Errorf("客户端配置格式错误,请检查 additional_info")
}
if miniInfo.AppId == "" || miniInfo.AppSecret == "" {
return nil, fmt.Errorf("客户端 %s 未配置 appId 或 appSecret", req.ClientId)
}
// 3. 调用微信 code2session 接口
params := url.Values{} params := url.Values{}
params.Set("appid", appID) params.Set("appid", miniInfo.AppId)
params.Set("secret", appSecret) params.Set("secret", miniInfo.AppSecret)
params.Set("js_code", req.Code) params.Set("js_code", req.Code)
params.Set("grant_type", "authorization_code") params.Set("grant_type", "authorization_code")
fullURL := "https://api.weixin.qq.com/sns/jscode2session?" + params.Encode() fullURL := "https://api.weixin.qq.com/sns/jscode2session?" + params.Encode()
@@ -83,7 +112,7 @@ func (l *MiniLoginLogic) MiniLogin(req *types.MiniLoginReq) (resp *types.LoginRe
return nil, fmt.Errorf("openid为空") return nil, fmt.Errorf("openid为空")
} }
// 2. 通过 user-rpc 创建或获取用户 // 4. 通过 system-rpc 创建或获取基础用户
createResp, err := l.svcCtx.SystemRpc.CreateUser(l.ctx, &sysPb.CreateUserReq{ createResp, err := l.svcCtx.SystemRpc.CreateUser(l.ctx, &sysPb.CreateUserReq{
Name: "", Name: "",
OpenId: wxResp.Openid, OpenId: wxResp.Openid,
@@ -95,7 +124,33 @@ func (l *MiniLoginLogic) MiniLogin(req *types.MiniLoginReq) (resp *types.LoginRe
return nil, fmt.Errorf("登录失败") return nil, fmt.Errorf("登录失败")
} }
// 3. 生成JWT Token(复用统一的 generateToken 函数) userId := createResp.User.Id
// 5. 异步初始化各业务服务的用户扩展表
// 新增小程序:在 switch 里加一个 case 即可
go func(uid, clientId string) {
bgCtx := context.Background()
switch clientId {
case ClientIdPlant:
if l.svcCtx.PlantRpc == nil {
l.Errorf("[MiniLogin] PlantRpc 未配置,跳过 plant profile 初始化")
return
}
if _, err := l.svcCtx.PlantRpc.GetUserProfile(bgCtx, &plantPb.GetProfileReq{
UserId: uid,
}); err != nil {
l.Errorf("[MiniLogin] 初始化 plant profile 失败: userId=%s, err=%v", uid, err)
} else {
l.Infof("[MiniLogin] plant profile 初始化成功: userId=%s", uid)
}
// case ClientIdRadio:
// l.svcCtx.RadioRpc.GetUserProfile(bgCtx, &radioPb.GetProfileReq{UserId: uid})
default:
// 未知 clientId 或无需扩展表的场景,跳过
}
}(userId, req.ClientId)
// 6. 生成JWT Token
token, err := generateToken(l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, createResp.User) token, err := generateToken(l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, createResp.User)
if err != nil { if err != nil {
l.Errorf("生成Token失败: %v", err) l.Errorf("生成Token失败: %v", err)
+13 -1
View File
@@ -2,6 +2,7 @@ package svc
import ( import (
"sundynix-micro-go/app/auth/api/internal/config" "sundynix-micro-go/app/auth/api/internal/config"
"sundynix-micro-go/app/plant/rpc/plantservice"
"sundynix-micro-go/app/system/rpc/systemservice" "sundynix-micro-go/app/system/rpc/systemservice"
"sundynix-micro-go/common/utils/captcha" "sundynix-micro-go/common/utils/captcha"
@@ -13,6 +14,9 @@ import (
type ServiceContext struct { type ServiceContext struct {
Config config.Config Config config.Config
SystemRpc systemservice.SystemService SystemRpc systemservice.SystemService
// 各业务 RPC(可选,新增小程序时在此追加)
PlantRpc plantservice.PlantService
// RadioRpc radioservice.RadioService
} }
func NewServiceContext(c config.Config) *ServiceContext { func NewServiceContext(c config.Config) *ServiceContext {
@@ -25,8 +29,16 @@ func NewServiceContext(c config.Config) *ServiceContext {
captcha.InitWithRedis(rdb) captcha.InitWithRedis(rdb)
logx.Infof("验证码存储已切换至 Redis (DB%d)", c.Redis.DB) logx.Infof("验证码存储已切换至 Redis (DB%d)", c.Redis.DB)
return &ServiceContext{ svc := &ServiceContext{
Config: c, Config: c,
SystemRpc: systemservice.NewSystemService(zrpc.MustNewClient(c.SystemRpc)), SystemRpc: systemservice.NewSystemService(zrpc.MustNewClient(c.SystemRpc)),
} }
// 可选: PlantRpc(配置了才连接,避免强依赖)
if c.PlantRpc.Etcd.Key != "" || len(c.PlantRpc.Endpoints) > 0 {
svc.PlantRpc = plantservice.NewPlantService(zrpc.MustNewClient(c.PlantRpc))
logx.Info("PlantRpc 已连接")
}
return svc
} }
+24 -2
View File
@@ -6,7 +6,7 @@ Host: 0.0.0.0
Port: 9004 Port: 9004
Auth: Auth:
AccessSecret: sundynix-jwt-secret-2024 AccessSecret: 9149f2eb-d517-4a50-a03a-231dbcf0d872
AccessExpire: 604800 AccessExpire: 604800
PlantRpc: PlantRpc:
@@ -19,10 +19,32 @@ UserRpc:
Etcd: Etcd:
Hosts: Hosts:
- 192.168.100.127:2379 - 192.168.100.127:2379
Key: user.rpc Key: system.rpc
FileRpc: FileRpc:
Etcd: Etcd:
Hosts: Hosts:
- 192.168.100.127:2379 - 192.168.100.127:2379
Key: file.rpc Key: file.rpc
DB:
DataSource: root:root@tcp(192.168.100.127:3307)/sundynix_micro_go?charset=utf8mb4&parseTime=True&loc=Local
# 百度 AI 植物识别(可选,未配置时 OCR 接口返回错误提示)
BaiduOcr:
ApiKey: hpBfjwy8ifv3qswYGYjUCNKN
SecretKey: i5aXZdM4XZVuDroBslL0f3uIuwbAyXFS
# OpenAI-compatible AI/RAG 配置。未配置 ChatApiUrl/ChatApiKey 时,AI 问答返回明确错误。
Ai:
ChatApiUrl:
ChatApiKey:
ChatModelName:
EmbeddingApiUrl:
EmbeddingApiKey:
EmbeddingModelName:
QdrantUrl:
QdrantApiKey:
QdrantCollection:
VectorDimension: 0
DailyQuota: 20
+21 -3
View File
@@ -1,6 +1,3 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package config package config
import ( import (
@@ -17,4 +14,25 @@ type Config struct {
PlantRpc zrpc.RpcClientConf PlantRpc zrpc.RpcClientConf
UserRpc zrpc.RpcClientConf UserRpc zrpc.RpcClientConf
FileRpc zrpc.RpcClientConf FileRpc zrpc.RpcClientConf
DB struct {
DataSource string
}
// 百度 OCR 植物识别
BaiduOcr struct {
ApiKey string
SecretKey string
} `json:",optional"`
Ai struct {
ChatApiUrl string `json:",optional"`
ChatApiKey string `json:",optional"`
ChatModelName string `json:",optional"`
EmbeddingApiUrl string `json:",optional"`
EmbeddingApiKey string `json:",optional"`
EmbeddingModelName string `json:",optional"`
QdrantUrl string `json:",optional"`
QdrantApiKey string `json:",optional"`
QdrantCollection string `json:",optional"`
VectorDimension int `json:",optional"`
DailyQuota int64 `json:",optional"`
} `json:",optional"`
} }
@@ -23,11 +23,11 @@ func AiChatHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := ai.NewAiChatLogic(r.Context(), svcCtx) l := ai.NewAiChatLogic(r.Context(), svcCtx)
err := l.AiChat(&req) resp, err := l.AiChat(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, map[string]string{"answer": resp})
} }
} }
} }
@@ -0,0 +1,25 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package ai
import (
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/ai"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/common/response"
)
// 清空聊天历史
func ClearAiChatHistoryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := ai.NewClearAiChatHistoryLogic(r.Context(), svcCtx)
err := l.ClearAiChatHistory()
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package ai
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/ai"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除聊天历史
func DeleteAiChatHistoryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := ai.NewDeleteAiChatHistoryLogic(r.Context(), svcCtx)
err := l.DeleteAiChatHistory(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -15,11 +15,11 @@ import (
func GetAiChatHistoryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { func GetAiChatHistoryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
l := ai.NewGetAiChatHistoryLogic(r.Context(), svcCtx) l := ai.NewGetAiChatHistoryLogic(r.Context(), svcCtx)
err := l.GetAiChatHistory() resp, err := l.GetAiChatHistory()
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -0,0 +1,20 @@
package ai
import (
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/ai"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/common/response"
)
func GetAiChatQuotaHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := ai.NewGetAiChatQuotaLogic(r.Context(), svcCtx)
resp, err := l.GetAiChatQuota()
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,29 @@
package banner
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/banner"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 创建Banner
func CreateBannerHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CreateBannerReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := banner.NewCreateBannerLogic(r.Context(), svcCtx)
err := l.CreateBanner(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,29 @@
package banner
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/banner"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除Banner
func DeleteBannerHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := banner.NewDeleteBannerLogic(r.Context(), svcCtx)
err := l.DeleteBanner(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,22 @@
package banner
import (
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/banner"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/common/response"
)
// 启用的Banner列表(客户端)
func GetActiveBannerListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := banner.NewGetActiveBannerListLogic(r.Context(), svcCtx)
resp, err := l.GetActiveBannerList()
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,29 @@
package banner
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/banner"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// Banner列表
func GetBannerListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.BannerListReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := banner.NewGetBannerListLogic(r.Context(), svcCtx)
resp, err := l.GetBannerList(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,29 @@
package banner
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/banner"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 更新Banner
func UpdateBannerHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateBannerReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := banner.NewUpdateBannerLogic(r.Context(), svcCtx)
err := l.UpdateBanner(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -8,18 +8,21 @@ import (
"sundynix-micro-go/app/plant/api/internal/logic/callback" "sundynix-micro-go/app/plant/api/internal/logic/callback"
"sundynix-micro-go/app/plant/api/internal/svc" "sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/common/response"
) )
// 微信支付回调 // 微信支付回调
// 注意:微信要求必须返回 200 OK,否则会持续重试,此处不走统一 response 包装
func WechatPayCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { func WechatPayCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
l := callback.NewWechatPayCallbackLogic(r.Context(), svcCtx) l := callback.NewWechatPayCallbackLogic(r.Context(), svcCtx)
err := l.WechatPayCallback() if err := l.WechatPayCallback(r); err != nil {
if err != nil { w.Header().Set("Content-Type", "application/json")
response.Fail(w, err.Error()) w.WriteHeader(http.StatusBadRequest)
} else { _, _ = w.Write([]byte(`{"code":"FAIL","message":"处理失败"}`))
response.Ok(w) return
} }
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"code":"SUCCESS","message":"成功"}`))
} }
} }
@@ -0,0 +1,27 @@
package complete
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/complete"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func CompleteTaskHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CompleteTaskApiReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := complete.NewCompleteTaskLogic(r.Context(), svcCtx)
resp, err := l.CompleteTask(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,27 @@
package complete
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/complete"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetAiChatHistoryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.PageReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := complete.NewGetAiChatHistoryLogic(r.Context(), svcCtx)
resp, err := l.GetAiChatHistory(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,20 @@
package complete
import (
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/complete"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/common/response"
)
func GetBadgeConfigTreeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := complete.NewGetBadgeConfigTreeLogic(r.Context(), svcCtx)
resp, err := l.GetBadgeConfigTree()
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,27 @@
package complete
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/complete"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetExchangeItemDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdPathReq
if err := httpx.ParsePath(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := complete.NewGetExchangeItemDetailLogic(r.Context(), svcCtx)
resp, err := l.GetExchangeItemDetail(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,27 @@
package complete
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/complete"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetLevelConfigDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdPathReq
if err := httpx.ParsePath(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := complete.NewGetLevelConfigDetailLogic(r.Context(), svcCtx)
resp, err := l.GetLevelConfigDetail(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,27 @@
package complete
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/complete"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetWikiClassDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdPathReq
if err := httpx.ParsePath(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := complete.NewGetWikiClassDetailLogic(r.Context(), svcCtx)
resp, err := l.GetWikiClassDetail(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package config
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/config"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 创建徽章配置
func CreateBadgeConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CreateBadgeConfigReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := config.NewCreateBadgeConfigLogic(r.Context(), svcCtx)
err := l.CreateBadgeConfig(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package config
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/config"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 创建等级配置
func CreateLevelConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CreateLevelConfigReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := config.NewCreateLevelConfigLogic(r.Context(), svcCtx)
err := l.CreateLevelConfig(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package config
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/config"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除徽章配置
func DeleteBadgeConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := config.NewDeleteBadgeConfigLogic(r.Context(), svcCtx)
err := l.DeleteBadgeConfig(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package config
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/config"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除等级配置
func DeleteLevelConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := config.NewDeleteLevelConfigLogic(r.Context(), svcCtx)
err := l.DeleteLevelConfig(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -23,11 +23,11 @@ func GetBadgeConfigListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := config.NewGetBadgeConfigListLogic(r.Context(), svcCtx) l := config.NewGetBadgeConfigListLogic(r.Context(), svcCtx)
err := l.GetBadgeConfigList(&req) resp, err := l.GetBadgeConfigList(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -23,11 +23,11 @@ func GetLevelConfigListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := config.NewGetLevelConfigListLogic(r.Context(), svcCtx) l := config.NewGetLevelConfigListLogic(r.Context(), svcCtx)
err := l.GetLevelConfigList(&req) resp, err := l.GetLevelConfigList(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package config
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/config"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 更新徽章配置
func UpdateBadgeConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateBadgeConfigReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := config.NewUpdateBadgeConfigLogic(r.Context(), svcCtx)
err := l.UpdateBadgeConfig(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package config
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/config"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 更新等级配置
func UpdateLevelConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateLevelConfigReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := config.NewUpdateLevelConfigLogic(r.Context(), svcCtx)
err := l.UpdateLevelConfig(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package exchange
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/exchange"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 创建兑换商品
func CreateExchangeItemHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CreateExchangeItemReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := exchange.NewCreateExchangeItemLogic(r.Context(), svcCtx)
err := l.CreateExchangeItem(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package exchange
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/exchange"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除兑换商品
func DeleteExchangeItemHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := exchange.NewDeleteExchangeItemLogic(r.Context(), svcCtx)
err := l.DeleteExchangeItem(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -23,11 +23,11 @@ func GetExchangeItemListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := exchange.NewGetExchangeItemListLogic(r.Context(), svcCtx) l := exchange.NewGetExchangeItemListLogic(r.Context(), svcCtx)
err := l.GetExchangeItemList(&req) resp, err := l.GetExchangeItemList(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -0,0 +1,27 @@
package exchange
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/exchange"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetExchangeOrderListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ExchangeOrderListReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := exchange.NewGetExchangeOrderListLogic(r.Context(), svcCtx)
resp, err := l.GetExchangeOrderList(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,27 @@
package exchange
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/exchange"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetMyExchangeOrdersHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ExchangeOrderListReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := exchange.NewGetMyExchangeOrdersLogic(r.Context(), svcCtx)
resp, err := l.GetMyExchangeOrders(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package exchange
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/exchange"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 更新兑换商品
func UpdateExchangeItemHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateExchangeItemReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := exchange.NewUpdateExchangeItemLogic(r.Context(), svcCtx)
err := l.UpdateExchangeItem(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package exchange
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/exchange"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 更新订单状态
func UpdateExchangeOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateExchangeOrderReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := exchange.NewUpdateExchangeOrderLogic(r.Context(), svcCtx)
err := l.UpdateExchangeOrder(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,894 @@
package legacy
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
filePb "sundynix-micro-go/app/file/rpc/file"
"sundynix-micro-go/app/plant/api/internal/logic/complete"
plantLogic "sundynix-micro-go/app/plant/api/internal/logic/myPlant"
postLogic "sundynix-micro-go/app/plant/api/internal/logic/post"
topicLogic "sundynix-micro-go/app/plant/api/internal/logic/topic"
wikiLogic "sundynix-micro-go/app/plant/api/internal/logic/wiki"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantModel "sundynix-micro-go/app/plant/model"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
"sundynix-micro-go/common/response"
"github.com/zeromicro/go-zero/rest/httpx"
"gorm.io/gorm"
)
func idFromQuery(r *http.Request) string {
if id := r.URL.Query().Get("id"); id != "" {
return id
}
if id := r.URL.Query().Get("wikiId"); id != "" {
return id
}
if id := r.URL.Query().Get("postId"); id != "" {
return id
}
if id := r.URL.Query().Get("itemId"); id != "" {
return id
}
return r.URL.Query().Get("classId")
}
func fileListByIDs(r *http.Request, svcCtx *svc.ServiceContext, ids []string) []map[string]interface{} {
if len(ids) == 0 {
return []map[string]interface{}{}
}
resp, err := svcCtx.FileRpc.GetFilesByIds(r.Context(), &filePb.GetFilesByIdsReq{Ids: ids})
if err != nil {
return []map[string]interface{}{}
}
list := make([]map[string]interface{}, 0, len(resp.Files))
for _, f := range resp.Files {
list = append(list, map[string]interface{}{
"id": f.Id, "name": f.Name, "url": f.Url, "tag": f.Tag,
"key": f.Key, "suffix": f.Suffix, "md5": f.Md5, "createdAt": f.CreatedAt,
})
}
return list
}
func PlantDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var myPlant plantModel.MyPlant
if err := svcCtx.DB.
Preload("CarePlans").
Preload("CareRecords", func(db *gorm.DB) *gorm.DB {
return db.Order("created_at desc")
}).
Preload("GrowthRecords", func(db *gorm.DB) *gorm.DB {
return db.Order("created_at desc")
}).
Where("id = ?", idFromQuery(r)).First(&myPlant).Error; err != nil {
response.Fail(w, err.Error())
return
}
// 查图片(本地关联表 + FileRpc)
imgList := queryImagesByPlant(svcCtx, r.Context(), myPlant.ID)
// 成长记录图片
growthImgMap := queryGrowthImages(svcCtx, r.Context(), myPlant.GrowthRecords)
response.OkWithData(w, map[string]interface{}{
"plant": toPlantMap(myPlant),
"imgList": imgList,
"carePlans": toPlanMapList(myPlant.CarePlans),
"careRecords": toRecordMapList(myPlant.CareRecords),
"careTasks": nil,
"growthRecords": toGrowthMapList(myPlant.GrowthRecords, growthImgMap),
})
}
}
func DeletePlanHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := plantLogic.NewDeleteCarePlanLogic(r.Context(), svcCtx)
if err := l.DeleteCarePlan(&types.IdsReq{Ids: []string{idFromQuery(r)}}); err != nil {
response.Fail(w, err.Error())
return
}
response.Ok(w)
}
}
func WikiDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
resp, err := svcCtx.PlantRpc.GetWikiDetail(r.Context(), &plantPb.IdReq{Id: idFromQuery(r)})
if err != nil {
response.Fail(w, err.Error())
return
}
if resp != nil && resp.Wiki != nil {
// 通过 FileRpc 获取完整图片信息
imgList := fetchFileMap(svcCtx, r.Context(), resp.Wiki.OssIds)
response.OkWithData(w, map[string]interface{}{
"wiki": resp.Wiki, "imgList": imgListToList(imgList, resp.Wiki.OssIds),
"classIds": resp.Wiki.ClassIds, "relatedWikiIds": resp.Wiki.RelatedWikiIds,
})
return
}
response.OkWithData(w, resp)
}
}
func WikiPageHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.WikiListReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
resp, err := svcCtx.PlantRpc.GetWikiList(r.Context(), &plantPb.WikiListReq{
Current: int32(req.Current),
PageSize: int32(req.PageSize),
Name: req.Name,
ClassId: req.ClassId,
IsHot: int32(req.IsHot),
})
if err != nil {
response.Fail(w, err.Error())
return
}
// 查询所有 wiki 的图片
var wikiIds []string
for _, w := range resp.List {
wikiIds = append(wikiIds, w.Id)
}
// 查本地关联表获取 OSS ID
type rel struct {
WikiID string `gorm:"column:wiki_id"`
OssID string `gorm:"column:oss_id"`
}
var rels []rel
if len(wikiIds) > 0 {
svcCtx.DB.Table("sundynix_plant_wiki_oss").
Where("wiki_id IN ?", wikiIds).
Find(&rels)
}
wikiOssMap := make(map[string][]string)
var allOssIds []string
for _, r := range rels {
wikiOssMap[r.WikiID] = append(wikiOssMap[r.WikiID], r.OssID)
allOssIds = append(allOssIds, r.OssID)
}
// 通过 FileRpc 获取图片信息
fileMap := fetchFileMap(svcCtx, r.Context(), allOssIds)
// 组装返回
var list []map[string]interface{}
for _, w := range resp.List {
ossIds := wikiOssMap[w.Id]
imgList := imgListToList(fileMap, ossIds)
hasStarVal := 0
if w.IsStar {
hasStarVal = 1
}
list = append(list, map[string]interface{}{
"id": w.Id, "name": w.Name, "latinName": w.LatinName,
"aliases": w.Aliases, "genus": w.Genus, "difficulty": w.Difficulty,
"isHot": w.IsHot, "growthHabit": w.GrowthHabit,
"lightIntensity": w.LightIntensity, "classId": w.ClassId,
"createdAt": w.CreatedAt, "hasStar": hasStarVal,
"imgList": imgList,
})
}
if list == nil {
list = []map[string]interface{}{}
}
response.OkWithData(w, map[string]interface{}{
"list": list, "total": resp.Total,
})
}
}
// imgListToList 将 fileMap 按顺序转为列表
func imgListToList(fileMap map[string]map[string]interface{}, ossIds []string) []map[string]interface{} {
var list []map[string]interface{}
for _, id := range ossIds {
if img, ok := fileMap[id]; ok {
list = append(list, img)
}
}
if list == nil {
list = []map[string]interface{}{}
}
return list
}
func WikiStarHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := wikiLogic.NewToggleWikiStarLogic(r.Context(), svcCtx)
if err := l.ToggleWikiStar(&types.IdReq{Id: idFromQuery(r)}); err != nil {
response.Fail(w, err.Error())
return
}
response.Ok(w)
}
}
func TopicDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := topicLogic.NewGetTopicDetailLogic(r.Context(), svcCtx)
resp, err := l.GetTopicDetail(&types.IdPathReq{Id: idFromQuery(r)})
if err != nil {
response.Fail(w, err.Error())
return
}
response.OkWithData(w, resp)
}
}
func LikePostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := postLogic.NewLikePostLogic(r.Context(), svcCtx)
if err := l.LikePost(&types.IdReq{Id: idFromQuery(r)}); err != nil {
response.Fail(w, err.Error())
return
}
response.Ok(w)
}
}
func StarPostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := postLogic.NewStarPostLogic(r.Context(), svcCtx)
if err := l.StarPost(&types.IdReq{Id: idFromQuery(r)}); err != nil {
response.Fail(w, err.Error())
return
}
response.Ok(w)
}
}
func ExchangeItemDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := complete.NewGetExchangeItemDetailLogic(r.Context(), svcCtx)
resp, err := l.GetExchangeItemDetail(&types.IdPathReq{Id: idFromQuery(r)})
if err != nil {
response.Fail(w, err.Error())
return
}
response.OkWithData(w, resp)
}
}
func PostPageHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.PostListReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
userId := fmt.Sprintf("%v", r.Context().Value("userId"))
db := svcCtx.DB.Model(&plantModel.Post{})
if req.Keyword != "" {
db = db.Where("title like ? OR content like ?", "%"+req.Keyword+"%", "%"+req.Keyword+"%")
}
var total int64
db.Count(&total)
pageSize := req.PageSize
if pageSize <= 0 {
pageSize = 20
}
page := req.Current
if page <= 0 {
page = 1
}
offset := (page - 1) * pageSize
var posts []*plantModel.Post
if err := db.
Preload("CommentList", func(db *gorm.DB) *gorm.DB {
return db.Order("created_at asc")
}).
Preload("LikeList").
Limit(pageSize).Offset(offset).Order("created_at desc").Find(&posts).Error; err != nil {
response.Fail(w, err.Error())
return
}
// 组装完整响应
list := buildPostListResponse(svcCtx, r.Context(), posts, userId)
response.OkWithData(w, map[string]interface{}{
"list": list, "total": total, "page": page, "pageSize": pageSize,
})
}
}
func MyPostPageHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.PostListReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
userId := fmt.Sprintf("%v", r.Context().Value("userId"))
db := svcCtx.DB.Model(&plantModel.Post{}).Where("user_id = ?", userId)
var total int64
db.Count(&total)
pageSize := req.PageSize
if pageSize <= 0 {
pageSize = 20
}
page := req.Current
if page <= 0 {
page = 1
}
offset := (page - 1) * pageSize
var posts []*plantModel.Post
if err := db.
Preload("CommentList", func(db *gorm.DB) *gorm.DB {
return db.Order("created_at asc")
}).
Preload("LikeList").
Limit(pageSize).Offset(offset).Order("created_at desc").Find(&posts).Error; err != nil {
response.Fail(w, err.Error())
return
}
list := buildPostListResponse(svcCtx, r.Context(), posts, userId)
response.OkWithData(w, map[string]interface{}{
"list": list, "total": total, "page": page, "pageSize": pageSize,
})
}
}
// ========== Post 列表辅助函数 ==========
// buildPostListResponse 组装完整帖子列表响应
func buildPostListResponse(svcCtx *svc.ServiceContext, ctx context.Context, posts []*plantModel.Post, userId string) []map[string]interface{} {
if len(posts) == 0 {
return []map[string]interface{}{}
}
var postIds []string
for _, p := range posts {
postIds = append(postIds, p.ID)
}
// 1. 查帖子图片(本地关联表 + FileRpc)
postImgMap := queryPostImages(svcCtx, ctx, postIds)
// 2. 查用户信息
allUserIds := collectPostUserIds(posts)
userMap := queryUserMapV2(svcCtx, allUserIds)
// 3. 查当前用户点赞/收藏状态
likedSet, starredSet := queryLikeStarStatus(svcCtx, userId, postIds)
// 4. 组装
var list []map[string]interface{}
for _, p := range posts {
item := map[string]interface{}{
"id": p.ID, "title": p.Title, "content": p.Content,
"userId": p.UserID, "location": p.Location,
"viewCount": p.ViewCount, "commentCount": p.CommentCount,
"likeCount": p.LikeCount, "starCount": p.StarCount,
"hasReviewed": p.HasReviewed,
"createdAt": p.CreatedAt.Format(time.RFC3339),
"updatedAt": p.UpdatedAt.Format(time.RFC3339),
"createdAtStr": p.CreatedAt.Format("2006-01-02 15:04:05"),
"hasLiked": 0, "hasStar": 0,
"imgList": postImgMap[p.ID],
"publisher": buildPublisherInfo(userMap, p.UserID),
"commentList": buildCommentList(userMap, p.CommentList),
"likeList": buildLikeList(userMap, p.LikeList),
"starList": []map[string]interface{}{},
}
if likedSet[p.ID] {
item["hasLiked"] = 1
}
if starredSet[p.ID] {
item["hasStar"] = 1
}
list = append(list, item)
}
return list
}
func collectPostUserIds(posts []*plantModel.Post) []string {
set := make(map[string]bool)
for _, p := range posts {
set[p.UserID] = true
for _, c := range p.CommentList {
set[c.UserID] = true
}
for _, l := range p.LikeList {
set[l.UserID] = true
}
}
var ids []string
for id := range set {
ids = append(ids, id)
}
return ids
}
// queryPostImages 查询帖子图片
func queryPostImages(svcCtx *svc.ServiceContext, ctx context.Context, postIds []string) map[string][]map[string]interface{} {
type rel struct {
PostID string `gorm:"column:post_id"`
OssID string `gorm:"column:oss_id"`
}
var rels []rel
svcCtx.DB.Table("sundynix_plant_post_oss").
Where("post_id IN ?", postIds).
Find(&rels)
var allOssIds []string
pidMap := make(map[string][]string)
for _, r := range rels {
pidMap[r.PostID] = append(pidMap[r.PostID], r.OssID)
allOssIds = append(allOssIds, r.OssID)
}
// 通过 FileRpc 获取文件信息
fileInfos := fetchFileMap(svcCtx, ctx, allOssIds)
result := make(map[string][]map[string]interface{})
for pid, ids := range pidMap {
var imgs []map[string]interface{}
for _, oid := range ids {
if info, ok := fileInfos[oid]; ok {
imgs = append(imgs, info)
}
}
if imgs == nil {
imgs = []map[string]interface{}{}
}
result[pid] = imgs
}
// 没有图片的帖子也返回空数组
for _, pid := range postIds {
if _, ok := result[pid]; !ok {
result[pid] = []map[string]interface{}{}
}
}
return result
}
// fetchFileMap 通过 FileRpc 获取文件信息
func fetchFileMap(svcCtx *svc.ServiceContext, ctx context.Context, ids []string) map[string]map[string]interface{} {
result := make(map[string]map[string]interface{})
if len(ids) == 0 {
return result
}
resp, err := svcCtx.FileRpc.GetFilesByIds(ctx, &filePb.GetFilesByIdsReq{Ids: ids})
if err != nil || resp == nil {
return result
}
for _, f := range resp.Files {
result[f.Id] = map[string]interface{}{
"id": f.Id, "name": f.Name, "url": f.Url, "tag": f.Tag,
"key": f.Key, "suffix": f.Suffix, "md5": f.Md5,
"createdAt": unixToTimeStr(f.CreatedAt),
"updatedAt": unixToTimeStr(f.CreatedAt),
"createdAtStr": unixToTimeStrShort(f.CreatedAt),
}
}
return result
}
func unixToTimeStr(ts int64) string {
if ts == 0 {
return ""
}
return time.Unix(ts, 0).Format(time.RFC3339)
}
func unixToTimeStrShort(ts int64) string {
if ts == 0 {
return ""
}
return time.Unix(ts, 0).Format("2006-01-02 15:04:05")
}
// queryUserMapV2 查询用户信息
func queryUserMapV2(svcCtx *svc.ServiceContext, ids []string) map[string]map[string]interface{} {
result := make(map[string]map[string]interface{})
if len(ids) == 0 {
return result
}
type userRow struct {
ID string `gorm:"column:id"`
NickName string `gorm:"column:nick_name"`
Name string `gorm:"column:name"`
AvatarID string `gorm:"column:avatar_id"`
}
var rows []userRow
svcCtx.DB.Table("sundynix_user").Where("id IN ?", ids).Find(&rows)
var avatarIds []string
for _, row := range rows {
if row.AvatarID != "" {
avatarIds = append(avatarIds, row.AvatarID)
}
}
// 头像通过 FileRpc 获取
avatarMap := fetchFileMap(svcCtx, context.Background(), avatarIds)
for _, row := range rows {
avatarData := map[string]interface{}{}
if av, ok := avatarMap[row.AvatarID]; ok {
avatarData = av
}
result[row.ID] = map[string]interface{}{
"id": row.ID, "nickName": row.NickName, "name": row.Name,
"avatarId": row.AvatarID, "avatar": avatarData,
}
}
return result
}
// queryLikeStarStatus 查询当前用户的点赞/收藏状态
func queryLikeStarStatus(svcCtx *svc.ServiceContext, userId string, postIds []string) (likedSet, starredSet map[string]bool) {
likedSet = make(map[string]bool)
starredSet = make(map[string]bool)
if len(postIds) == 0 {
return
}
type rel struct {
PostID string `gorm:"column:post_id"`
}
var likes []rel
svcCtx.DB.Table("sundynix_plant_post_like").
Where("post_id IN ? AND user_id = ?", postIds, userId).Find(&likes)
for _, l := range likes {
likedSet[l.PostID] = true
}
var stars []rel
svcCtx.DB.Table("sundynix_plant_user_star").
Where("target_id IN ? AND user_id = ? AND type = 'post'", postIds, userId).Find(&stars)
for _, s := range stars {
starredSet[s.PostID] = true
}
return
}
func buildPublisherInfo(userMap map[string]map[string]interface{}, userId string) map[string]interface{} {
if u, ok := userMap[userId]; ok {
return u
}
return map[string]interface{}{
"id": userId, "nickName": "", "name": "", "avatarId": "", "avatar": map[string]interface{}{},
}
}
func buildCommentList(userMap map[string]map[string]interface{}, comments []*plantModel.PostComment) []map[string]interface{} {
var list []map[string]interface{}
for _, c := range comments {
list = append(list, map[string]interface{}{
"id": c.ID, "postId": c.PostID, "userId": c.UserID,
"content": c.Content, "parentId": c.ParentID,
"createdAt": c.CreatedAt.Format(time.RFC3339),
"updatedAt": c.UpdatedAt.Format(time.RFC3339),
"createdAtStr": c.CreatedAt.Format("2006-01-02 15:04:05"),
"commentator": buildPublisherInfo(userMap, c.UserID),
})
}
if list == nil {
list = []map[string]interface{}{}
}
return list
}
func buildLikeList(userMap map[string]map[string]interface{}, likes []*plantModel.PostLike) []map[string]interface{} {
var list []map[string]interface{}
for _, l := range likes {
list = append(list, map[string]interface{}{
"id": l.ID, "postId": l.PostID, "userId": l.UserID,
"liker": buildPublisherInfo(userMap, l.UserID),
})
}
if list == nil {
list = []map[string]interface{}{}
}
return list
}
// ========== Plant Detail 辅助函数 ==========
func queryImagesByPlant(svcCtx *svc.ServiceContext, ctx context.Context, plantID string) []map[string]interface{} {
type rel struct {
OssID string `gorm:"column:sundynix_oss_id"`
}
var rels []rel
svcCtx.DB.Table("sundynix_plant_my_plant_oss").
Where("sundynix_my_plant_id = ?", plantID).
Order("sundynix_oss_id asc").
Find(&rels)
var ids []string
for _, r := range rels {
ids = append(ids, r.OssID)
}
fileMap := fetchFileMap(svcCtx, ctx, ids)
var result []map[string]interface{}
for _, id := range ids {
if f, ok := fileMap[id]; ok {
result = append(result, f)
}
}
if result == nil {
result = []map[string]interface{}{}
}
return result
}
func queryGrowthImages(svcCtx *svc.ServiceContext, ctx context.Context, records []*plantModel.GrowthRecord) map[string][]map[string]interface{} {
if len(records) == 0 {
return nil
}
var ids []string
for _, gr := range records {
ids = append(ids, gr.ID)
}
type rel struct {
GrowthRecordID string `gorm:"column:growth_record_id"`
OssID string `gorm:"column:oss_id"`
}
var rels []rel
svcCtx.DB.Table("sundynix_plant_growth_record_oss").
Where("growth_record_id IN ?", ids).
Find(&rels)
var allOssIds []string
gidMap := make(map[string][]string)
for _, r := range rels {
gidMap[r.GrowthRecordID] = append(gidMap[r.GrowthRecordID], r.OssID)
allOssIds = append(allOssIds, r.OssID)
}
fileMap := fetchFileMap(svcCtx, ctx, allOssIds)
result := make(map[string][]map[string]interface{})
for gid, ossIds := range gidMap {
var imgs []map[string]interface{}
for _, oid := range ossIds {
if f, ok := fileMap[oid]; ok {
imgs = append(imgs, f)
}
}
result[gid] = imgs
}
return result
}
func toPlantMap(p plantModel.MyPlant) map[string]interface{} {
return map[string]interface{}{
"id": p.ID, "createdAt": p.CreatedAt.Format(time.RFC3339),
"updatedAt": p.UpdatedAt.Format(time.RFC3339), "createdAtStr": p.CreatedAt.Format("2006-01-02 15:04:05"),
"userId": p.UserID, "name": p.Name, "plantTime": p.PlantTime.Format(time.RFC3339),
"status": p.Status, "placement": p.Placement,
"potMaterial": p.PotMaterial, "potSize": p.PotSize,
"sunlight": p.Sunlight, "plantingMaterial": p.PlantingMaterial,
}
}
func toPlanMapList(plans []*plantModel.CarePlan) []map[string]interface{} {
var list []map[string]interface{}
for _, p := range plans {
list = append(list, map[string]interface{}{
"id": p.ID, "createdAt": p.CreatedAt.Format(time.RFC3339),
"updatedAt": p.UpdatedAt.Format(time.RFC3339), "createdAtStr": p.CreatedAt.Format("2006-01-02 15:04:05"),
"userId": p.UserID, "plantId": p.PlantID, "name": p.Name, "icon": p.Icon,
"period": p.Period, "targetAction": p.TargetAction,
})
}
if list == nil {
list = []map[string]interface{}{}
}
return list
}
func toRecordMapList(records []*plantModel.CareRecord) []map[string]interface{} {
var list []map[string]interface{}
for _, r := range records {
list = append(list, map[string]interface{}{
"id": r.ID, "createdAt": r.CreatedAt.Format(time.RFC3339),
"updatedAt": r.UpdatedAt.Format(time.RFC3339), "createdAtStr": r.CreatedAt.Format("2006-01-02 15:04:05"),
"userId": r.UserID, "plantId": r.PlantID, "planId": r.PlanID,
"name": r.Name, "remark": r.Remark, "icon": r.Icon,
})
}
if list == nil {
list = []map[string]interface{}{}
}
return list
}
func toGrowthMapList(records []*plantModel.GrowthRecord, imgMap map[string][]map[string]interface{}) []map[string]interface{} {
var list []map[string]interface{}
for _, gr := range records {
imgs := imgMap[gr.ID]
if imgs == nil {
imgs = []map[string]interface{}{}
}
list = append(list, map[string]interface{}{
"id": gr.ID, "createdAt": gr.CreatedAt.Format(time.RFC3339),
"updatedAt": gr.UpdatedAt.Format(time.RFC3339), "createdAtStr": gr.CreatedAt.Format("2006-01-02 15:04:05"),
"plantId": gr.PlantID, "userId": gr.UserID, "name": gr.Name,
"tag": gr.Tag, "desc": gr.Desc, "content": gr.Content,
"imgList": imgs,
})
}
if list == nil {
list = []map[string]interface{}{}
}
return list
}
// queryOssList 批量查询 Oss 图片信息(供 WikiDetailHandler 使用)
func queryOssList(svcCtx *svc.ServiceContext, ossIds []string) []map[string]interface{} {
if len(ossIds) == 0 {
return []map[string]interface{}{}
}
type OssRow struct {
ID string `gorm:"column:id"`
Name string `gorm:"column:name"`
Url string `gorm:"column:url"`
Tag string `gorm:"column:tag"`
Key string `gorm:"column:key"`
Suffix string `gorm:"column:suffix"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
var rows []OssRow
svcCtx.DB.Table("sundynix_oss").Where("id IN ?", ossIds).Find(&rows)
ossMap := make(map[string]OssRow)
for _, row := range rows {
ossMap[row.ID] = row
}
var result []map[string]interface{}
for _, id := range ossIds {
if row, ok := ossMap[id]; ok {
result = append(result, map[string]interface{}{
"id": row.ID, "name": row.Name, "url": row.Url, "tag": row.Tag,
"key": row.Key, "suffix": row.Suffix,
"createdAt": row.CreatedAt.Format(time.RFC3339),
"updatedAt": row.UpdatedAt.Format(time.RFC3339),
"createdAtStr": row.CreatedAt.Format("2006-01-02 15:04:05"),
})
}
}
return result
}
func AiChatSyncHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
resp, err := svcCtx.PlantRpc.SyncAllWikiVector(r.Context(), &plantPb.PageReq{})
if err != nil {
response.Fail(w, err.Error())
return
}
response.OkWithMsg(w, resp.Msg)
}
}
func WikiSyncQdrantHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
wikiID := idFromQuery(r)
if wikiID == "" {
var req types.IdReq
_ = httpx.Parse(r, &req)
wikiID = req.Id
}
if wikiID == "" {
response.Fail(w, "wikiId 不能为空")
return
}
if _, err := svcCtx.PlantRpc.SyncWikiVector(r.Context(), &plantPb.SyncWikiVectorReq{WikiId: wikiID}); err != nil {
response.Fail(w, err.Error())
return
}
response.Ok(w)
}
}
func WikiDeleteQdrantHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
wikiID := idFromQuery(r)
if wikiID == "" {
var req types.IdReq
_ = httpx.Parse(r, &req)
wikiID = req.Id
}
if wikiID == "" {
response.Fail(w, "wikiId 不能为空")
return
}
if _, err := svcCtx.PlantRpc.DeleteWikiVector(r.Context(), &plantPb.SyncWikiVectorReq{WikiId: wikiID}); err != nil {
response.Fail(w, err.Error())
return
}
response.Ok(w)
}
}
func WikiUploadImgHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
response.FailWithCode(w, 409, "设计/百科图片上传已迁移到 file-api,请先调用文件服务上传,再将返回的文件 id 作为 ossIds 传给 plant")
}
}
func BadgeConfigDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
resp, err := svcCtx.PlantRpc.GetBadgeConfigDetail(r.Context(), &plantPb.IdReq{Id: idFromQuery(r)})
if err != nil {
response.Fail(w, err.Error())
return
}
response.OkWithData(w, resp)
}
}
func BadgeConfigDeleteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, err := svcCtx.PlantRpc.DeleteBadgeConfig(r.Context(), &plantPb.IdsReq{Ids: []string{idFromQuery(r)}}); err != nil {
response.Fail(w, err.Error())
return
}
response.Ok(w)
}
}
func LevelConfigDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
resp, err := svcCtx.PlantRpc.GetLevelConfigDetail(r.Context(), &plantPb.IdReq{Id: idFromQuery(r)})
if err != nil {
response.Fail(w, err.Error())
return
}
response.OkWithData(w, resp)
}
}
func MediaCheckCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var payload struct {
TraceID string `json:"traceId"`
PostID string `json:"postId"`
OssID string `json:"ossId"`
UserID string `json:"userId"`
Status int32 `json:"status"`
Type int32 `json:"type"`
ErrMsg string `json:"errMsg"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
response.Fail(w, err.Error())
return
}
if _, err := svcCtx.PlantRpc.MediaCheckCallback(r.Context(), &plantPb.MediaCheckCallbackReq{
TraceId: payload.TraceID,
PostId: payload.PostID,
OssId: payload.OssID,
UserId: payload.UserID,
Status: payload.Status,
Type: payload.Type,
ErrMsg: payload.ErrMsg,
}); err != nil {
response.Fail(w, err.Error())
return
}
response.Ok(w)
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package myPlant
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/myPlant"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除养护计划
func DeleteCarePlanHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := myPlant.NewDeleteCarePlanLogic(r.Context(), svcCtx)
err := l.DeleteCarePlan(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,20 @@
package myPlant
import (
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/myPlant"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/common/response"
)
func GetTodayTaskListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := myPlant.NewGetTodayTaskListLogic(r.Context(), svcCtx)
resp, err := l.GetTodayTaskList()
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,30 @@
package myPlant
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/myPlant"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 快捷养护
func QuickCareHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.QuickCareReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := myPlant.NewQuickCareLogic(r.Context(), svcCtx)
err := l.QuickCare(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package ocr
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/ocr"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除识别记录
func DeleteClassifyLogHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := ocr.NewDeleteClassifyLogLogic(r.Context(), svcCtx)
err := l.DeleteClassifyLog(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,20 @@
package ocr
import (
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/ocr"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/common/response"
)
func GetMyClassifyLogHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := ocr.NewGetMyClassifyLogLogic(r.Context(), svcCtx)
resp, err := l.GetMyClassifyLog()
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -23,11 +23,11 @@ func OcrClassifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := ocr.NewOcrClassifyLogic(r.Context(), svcCtx) l := ocr.NewOcrClassifyLogic(r.Context(), svcCtx)
err := l.OcrClassify(&req) resp, err := l.OcrClassify(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -23,11 +23,11 @@ func GetPostDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := post.NewGetPostDetailLogic(r.Context(), svcCtx) l := post.NewGetPostDetailLogic(r.Context(), svcCtx)
err := l.GetPostDetail(&req) resp, err := l.GetPostDetail(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -23,11 +23,11 @@ func GetPostListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := post.NewGetPostListLogic(r.Context(), svcCtx) l := post.NewGetPostListLogic(r.Context(), svcCtx)
err := l.GetPostList(&req) resp, err := l.GetPostList(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -0,0 +1,27 @@
package post
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/post"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetMyPostListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.PostListReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := post.NewGetMyPostListLogic(r.Context(), svcCtx)
resp, err := l.GetMyPostList(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package post
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/post"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 收藏帖子
func StarPostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := post.NewStarPostLogic(r.Context(), svcCtx)
err := l.StarPost(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
+356 -12
View File
@@ -7,9 +7,12 @@ import (
"net/http" "net/http"
ai "sundynix-micro-go/app/plant/api/internal/handler/ai" ai "sundynix-micro-go/app/plant/api/internal/handler/ai"
banner "sundynix-micro-go/app/plant/api/internal/handler/banner"
callback "sundynix-micro-go/app/plant/api/internal/handler/callback" callback "sundynix-micro-go/app/plant/api/internal/handler/callback"
complete "sundynix-micro-go/app/plant/api/internal/handler/complete"
config "sundynix-micro-go/app/plant/api/internal/handler/config" config "sundynix-micro-go/app/plant/api/internal/handler/config"
exchange "sundynix-micro-go/app/plant/api/internal/handler/exchange" exchange "sundynix-micro-go/app/plant/api/internal/handler/exchange"
legacy "sundynix-micro-go/app/plant/api/internal/handler/legacy"
myPlant "sundynix-micro-go/app/plant/api/internal/handler/myPlant" myPlant "sundynix-micro-go/app/plant/api/internal/handler/myPlant"
ocr "sundynix-micro-go/app/plant/api/internal/handler/ocr" ocr "sundynix-micro-go/app/plant/api/internal/handler/ocr"
post "sundynix-micro-go/app/plant/api/internal/handler/post" post "sundynix-micro-go/app/plant/api/internal/handler/post"
@@ -36,6 +39,24 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/ai/history", Path: "/ai/history",
Handler: ai.GetAiChatHistoryHandler(serverCtx), Handler: ai.GetAiChatHistoryHandler(serverCtx),
}, },
{
// 清空聊天历史
Method: http.MethodPost,
Path: "/ai/history/clear",
Handler: ai.ClearAiChatHistoryHandler(serverCtx),
},
{
// 删除聊天历史
Method: http.MethodPost,
Path: "/ai/history/delete",
Handler: ai.DeleteAiChatHistoryHandler(serverCtx),
},
{
// 今日AI额度
Method: http.MethodGet,
Path: "/ai/quota",
Handler: ai.GetAiChatQuotaHandler(serverCtx),
},
}, },
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"), rest.WithPrefix("/api/plant"),
@@ -49,6 +70,12 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/callback/wechatpay", Path: "/callback/wechatpay",
Handler: callback.WechatPayCallbackHandler(serverCtx), Handler: callback.WechatPayCallbackHandler(serverCtx),
}, },
{
// 微信媒体安全回调
Method: http.MethodPost,
Path: "/callback/mediaCheck",
Handler: legacy.MediaCheckCallbackHandler(serverCtx),
},
}, },
rest.WithPrefix("/api/plant"), rest.WithPrefix("/api/plant"),
) )
@@ -56,16 +83,40 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes( server.AddRoutes(
[]rest.Route{ []rest.Route{
{ {
// 徽章配置列表 // AI聊天历史
Method: http.MethodPost, Method: http.MethodPost,
Path: "/config/badge/list", Path: "/ai/history",
Handler: config.GetBadgeConfigListHandler(serverCtx), Handler: complete.GetAiChatHistoryHandler(serverCtx),
}, },
{ {
// 等级配置列表 // 徽章配置树
Method: http.MethodGet,
Path: "/config/badge/tree",
Handler: complete.GetBadgeConfigTreeHandler(serverCtx),
},
{
// 等级配置详情
Method: http.MethodGet,
Path: "/config/level/:id",
Handler: complete.GetLevelConfigDetailHandler(serverCtx),
},
{
// 兑换商品详情
Method: http.MethodGet,
Path: "/exchange/item/:id",
Handler: complete.GetExchangeItemDetailHandler(serverCtx),
},
{
// 完成养护任务
Method: http.MethodPost, Method: http.MethodPost,
Path: "/config/level/list", Path: "/my/completeTask",
Handler: config.GetLevelConfigListHandler(serverCtx), Handler: complete.CompleteTaskHandler(serverCtx),
},
{
// 百科分类详情
Method: http.MethodGet,
Path: "/wiki/class/:id",
Handler: complete.GetWikiClassDetailHandler(serverCtx),
}, },
}, },
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
@@ -74,6 +125,85 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes( server.AddRoutes(
[]rest.Route{ []rest.Route{
{
// 创建徽章配置
Method: http.MethodPost,
Path: "/config/badge/create",
Handler: config.CreateBadgeConfigHandler(serverCtx),
},
{Method: http.MethodPost, Path: "/config/badge/add", Handler: config.CreateBadgeConfigHandler(serverCtx)},
{
// 删除徽章配置
Method: http.MethodPost,
Path: "/config/badge/delete",
Handler: config.DeleteBadgeConfigHandler(serverCtx),
},
{Method: http.MethodGet, Path: "/config/badge/delete", Handler: legacy.BadgeConfigDeleteHandler(serverCtx)},
{Method: http.MethodGet, Path: "/config/badge/find", Handler: legacy.BadgeConfigDetailHandler(serverCtx)},
{
// 徽章配置列表
Method: http.MethodPost,
Path: "/config/badge/list",
Handler: config.GetBadgeConfigListHandler(serverCtx),
},
{
// 更新徽章配置
Method: http.MethodPost,
Path: "/config/badge/update",
Handler: config.UpdateBadgeConfigHandler(serverCtx),
},
{
// 创建等级配置
Method: http.MethodPost,
Path: "/config/level/create",
Handler: config.CreateLevelConfigHandler(serverCtx),
},
{Method: http.MethodPost, Path: "/config/level/add", Handler: config.CreateLevelConfigHandler(serverCtx)},
{
// 删除等级配置
Method: http.MethodPost,
Path: "/config/level/delete",
Handler: config.DeleteLevelConfigHandler(serverCtx),
},
{
// 等级配置列表
Method: http.MethodPost,
Path: "/config/level/list",
Handler: config.GetLevelConfigListHandler(serverCtx),
},
{Method: http.MethodGet, Path: "/config/level/list", Handler: config.GetLevelConfigListHandler(serverCtx)},
{Method: http.MethodGet, Path: "/config/level/detail", Handler: legacy.LevelConfigDetailHandler(serverCtx)},
{
// 更新等级配置
Method: http.MethodPost,
Path: "/config/level/update",
Handler: config.UpdateLevelConfigHandler(serverCtx),
},
},
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"),
)
server.AddRoutes(
[]rest.Route{
{
// 创建兑换商品
Method: http.MethodPost,
Path: "/exchange/item/create",
Handler: exchange.CreateExchangeItemHandler(serverCtx),
},
{
// 删除兑换商品
Method: http.MethodPost,
Path: "/exchange/item/delete",
Handler: exchange.DeleteExchangeItemHandler(serverCtx),
},
{
// 更新兑换商品
Method: http.MethodPost,
Path: "/exchange/item/update",
Handler: exchange.UpdateExchangeItemHandler(serverCtx),
},
{ {
// 兑换商品列表 // 兑换商品列表
Method: http.MethodPost, Method: http.MethodPost,
@@ -81,11 +211,29 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Handler: exchange.GetExchangeItemListHandler(serverCtx), Handler: exchange.GetExchangeItemListHandler(serverCtx),
}, },
{ {
// 兑换商品 // 我的兑换记录
Method: http.MethodPost,
Path: "/exchange/myOrders",
Handler: exchange.GetMyExchangeOrdersHandler(serverCtx),
},
{
// 发起兑换
Method: http.MethodPost, Method: http.MethodPost,
Path: "/exchange/order", Path: "/exchange/order",
Handler: exchange.CreateExchangeOrderHandler(serverCtx), Handler: exchange.CreateExchangeOrderHandler(serverCtx),
}, },
{
// 管理端订单列表
Method: http.MethodPost,
Path: "/exchange/order/list",
Handler: exchange.GetExchangeOrderListHandler(serverCtx),
},
{
// 更新订单状态
Method: http.MethodPost,
Path: "/exchange/order/update",
Handler: exchange.UpdateExchangeOrderHandler(serverCtx),
},
}, },
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"), rest.WithPrefix("/api/plant"),
@@ -119,10 +267,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
}, },
{ {
// 删除植物 // 删除植物
Method: http.MethodDelete, Method: http.MethodPost,
Path: "/my/delete", Path: "/my/delete",
Handler: myPlant.DeletePlantHandler(serverCtx), Handler: myPlant.DeletePlantHandler(serverCtx),
}, },
{
// 删除养护计划
Method: http.MethodPost,
Path: "/my/deletePlan",
Handler: myPlant.DeleteCarePlanHandler(serverCtx),
},
{ {
// 添加成长记录 // 添加成长记录
Method: http.MethodPost, Method: http.MethodPost,
@@ -135,12 +289,24 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/my/list", Path: "/my/list",
Handler: myPlant.GetMyPlantListHandler(serverCtx), Handler: myPlant.GetMyPlantListHandler(serverCtx),
}, },
{
// 今日养护任务
Method: http.MethodGet,
Path: "/my/todayTask",
Handler: myPlant.GetTodayTaskListHandler(serverCtx),
},
{ {
// 更新植物 // 更新植物
Method: http.MethodPut, Method: http.MethodPost,
Path: "/my/update", Path: "/my/update",
Handler: myPlant.UpdatePlantHandler(serverCtx), Handler: myPlant.UpdatePlantHandler(serverCtx),
}, },
{
// 快捷养护
Method: http.MethodPost,
Path: "/my/quickCare",
Handler: myPlant.QuickCareHandler(serverCtx),
},
}, },
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"), rest.WithPrefix("/api/plant"),
@@ -154,6 +320,18 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/ocr/classify", Path: "/ocr/classify",
Handler: ocr.OcrClassifyHandler(serverCtx), Handler: ocr.OcrClassifyHandler(serverCtx),
}, },
{
// 删除识别记录
Method: http.MethodPost,
Path: "/ocr/deleteLog",
Handler: ocr.DeleteClassifyLogHandler(serverCtx),
},
{
// 我的识别记录
Method: http.MethodGet,
Path: "/ocr/myLog",
Handler: ocr.GetMyClassifyLogHandler(serverCtx),
},
}, },
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"), rest.WithPrefix("/api/plant"),
@@ -181,7 +359,7 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
}, },
{ {
// 删除帖子 // 删除帖子
Method: http.MethodDelete, Method: http.MethodPost,
Path: "/post/delete", Path: "/post/delete",
Handler: post.DeletePostHandler(serverCtx), Handler: post.DeletePostHandler(serverCtx),
}, },
@@ -197,6 +375,18 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/post/list", Path: "/post/list",
Handler: post.GetPostListHandler(serverCtx), Handler: post.GetPostListHandler(serverCtx),
}, },
{
// 我的帖子
Method: http.MethodPost,
Path: "/post/my",
Handler: post.GetMyPostListHandler(serverCtx),
},
{
// 收藏帖子
Method: http.MethodPost,
Path: "/post/star",
Handler: post.StarPostHandler(serverCtx),
},
}, },
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"), rest.WithPrefix("/api/plant"),
@@ -204,6 +394,12 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes( server.AddRoutes(
[]rest.Route{ []rest.Route{
{
// 话题详情
Method: http.MethodGet,
Path: "/topic/:id",
Handler: topic.GetTopicDetailHandler(serverCtx),
},
{ {
// 创建话题 // 创建话题
Method: http.MethodPost, Method: http.MethodPost,
@@ -212,7 +408,7 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
}, },
{ {
// 删除话题 // 删除话题
Method: http.MethodDelete, Method: http.MethodPost,
Path: "/topic/delete", Path: "/topic/delete",
Handler: topic.DeleteTopicHandler(serverCtx), Handler: topic.DeleteTopicHandler(serverCtx),
}, },
@@ -222,6 +418,12 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/topic/list", Path: "/topic/list",
Handler: topic.GetTopicListHandler(serverCtx), Handler: topic.GetTopicListHandler(serverCtx),
}, },
{
// 更新话题
Method: http.MethodPost,
Path: "/topic/update",
Handler: topic.UpdateTopicHandler(serverCtx),
},
}, },
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"), rest.WithPrefix("/api/plant"),
@@ -229,15 +431,28 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes( server.AddRoutes(
[]rest.Route{ []rest.Route{
{
// 我的徽章
Method: http.MethodGet,
Path: "/profile/badge",
Handler: userProfile.GetMyBadgesHandler(serverCtx),
},
{ {
// 获取用户资料 // 获取用户资料
Method: http.MethodGet, Method: http.MethodGet,
Path: "/profile/info", Path: "/profile/info",
Handler: userProfile.GetUserProfileHandler(serverCtx), Handler: userProfile.GetUserProfileHandler(serverCtx),
}, },
{Method: http.MethodGet, Path: "/profile/detail", Handler: userProfile.GetUserProfileHandler(serverCtx)},
{
// 我的收藏
Method: http.MethodPost,
Path: "/profile/star",
Handler: userProfile.GetMyStarsHandler(serverCtx),
},
{ {
// 更新用户资料 // 更新用户资料
Method: http.MethodPut, Method: http.MethodPost,
Path: "/profile/update", Path: "/profile/update",
Handler: userProfile.UpdateUserProfileHandler(serverCtx), Handler: userProfile.UpdateUserProfileHandler(serverCtx),
}, },
@@ -260,12 +475,36 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/wiki/class/create", Path: "/wiki/class/create",
Handler: wiki.CreateWikiClassHandler(serverCtx), Handler: wiki.CreateWikiClassHandler(serverCtx),
}, },
{
// 删除百科分类
Method: http.MethodPost,
Path: "/wiki/class/delete",
Handler: wiki.DeleteWikiClassHandler(serverCtx),
},
{ {
// 百科分类列表 // 百科分类列表
Method: http.MethodGet, Method: http.MethodGet,
Path: "/wiki/class/list", Path: "/wiki/class/list",
Handler: wiki.GetWikiClassListHandler(serverCtx), Handler: wiki.GetWikiClassListHandler(serverCtx),
}, },
{
// 更新百科分类
Method: http.MethodPost,
Path: "/wiki/class/update",
Handler: wiki.UpdateWikiClassHandler(serverCtx),
},
{
// 创建百科
Method: http.MethodPost,
Path: "/wiki/create",
Handler: wiki.CreateWikiHandler(serverCtx),
},
{
// 删除百科
Method: http.MethodPost,
Path: "/wiki/delete",
Handler: wiki.DeleteWikiHandler(serverCtx),
},
{ {
// 百科列表 // 百科列表
Method: http.MethodPost, Method: http.MethodPost,
@@ -278,6 +517,111 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/wiki/star", Path: "/wiki/star",
Handler: wiki.ToggleWikiStarHandler(serverCtx), Handler: wiki.ToggleWikiStarHandler(serverCtx),
}, },
{
// 更新百科
Method: http.MethodPost,
Path: "/wiki/update",
Handler: wiki.UpdateWikiHandler(serverCtx),
},
},
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"),
)
server.AddRoutes(
[]rest.Route{
{
// 创建Banner
Method: http.MethodPost,
Path: "/banner/create",
Handler: banner.CreateBannerHandler(serverCtx),
},
{
// 删除Banner
Method: http.MethodPost,
Path: "/banner/delete",
Handler: banner.DeleteBannerHandler(serverCtx),
},
{
// 更新Banner
Method: http.MethodPost,
Path: "/banner/update",
Handler: banner.UpdateBannerHandler(serverCtx),
},
{
// Banner列表(管理端)
Method: http.MethodPost,
Path: "/banner/list",
Handler: banner.GetBannerListHandler(serverCtx),
},
{
// 启用的Banner列表(客户端)
Method: http.MethodGet,
Path: "/banner/activeList",
Handler: banner.GetActiveBannerListHandler(serverCtx),
},
},
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"),
)
server.AddRoutes(
[]rest.Route{
{Method: http.MethodPost, Path: "/add", Handler: myPlant.CreatePlantHandler(serverCtx)},
{Method: http.MethodPost, Path: "/page", Handler: myPlant.GetMyPlantListHandler(serverCtx)},
{Method: http.MethodGet, Path: "/detail", Handler: legacy.PlantDetailHandler(serverCtx)},
{Method: http.MethodPost, Path: "/update", Handler: myPlant.UpdatePlantHandler(serverCtx)},
{Method: http.MethodPost, Path: "/deletePlant", Handler: myPlant.DeletePlantHandler(serverCtx)},
{Method: http.MethodPost, Path: "/deletePlan", Handler: myPlant.DeleteCarePlanHandler(serverCtx)},
{Method: http.MethodPost, Path: "/plan/add", Handler: myPlant.AddCarePlanHandler(serverCtx)},
{Method: http.MethodGet, Path: "/plan/delete", Handler: legacy.DeletePlanHandler(serverCtx)},
{Method: http.MethodGet, Path: "/todayTask", Handler: myPlant.GetTodayTaskListHandler(serverCtx)},
{Method: http.MethodPost, Path: "/completeTask", Handler: complete.CompleteTaskHandler(serverCtx)},
{Method: http.MethodPost, Path: "/growth/add", Handler: myPlant.AddGrowthRecordHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki/add", Handler: wiki.CreateWikiHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki/page", Handler: legacy.WikiPageHandler(serverCtx)},
{Method: http.MethodGet, Path: "/wiki/detail", Handler: legacy.WikiDetailHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki/uploadImg", Handler: legacy.WikiUploadImgHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki/sync-qdrant", Handler: legacy.WikiSyncQdrantHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki/delete-qdrant", Handler: legacy.WikiDeleteQdrantHandler(serverCtx)},
{Method: http.MethodGet, Path: "/wiki/star", Handler: legacy.WikiStarHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki-class/add", Handler: wiki.CreateWikiClassHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki-class/update", Handler: wiki.UpdateWikiClassHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki-class/page", Handler: wiki.GetWikiClassListHandler(serverCtx)},
{Method: http.MethodPost, Path: "/wiki-class/delete", Handler: wiki.DeleteWikiClassHandler(serverCtx)},
{Method: http.MethodGet, Path: "/wiki-class/list", Handler: wiki.GetWikiClassListHandler(serverCtx)},
{Method: http.MethodGet, Path: "/wiki-class/detail", Handler: complete.GetWikiClassDetailHandler(serverCtx)},
{Method: http.MethodPost, Path: "/post/publish", Handler: post.CreatePostHandler(serverCtx)},
{Method: http.MethodPost, Path: "/post/page", Handler: legacy.PostPageHandler(serverCtx)},
{Method: http.MethodPost, Path: "/post/myPost", Handler: legacy.MyPostPageHandler(serverCtx)},
{Method: http.MethodGet, Path: "/post/like", Handler: legacy.LikePostHandler(serverCtx)},
{Method: http.MethodGet, Path: "/post/star", Handler: legacy.StarPostHandler(serverCtx)},
{Method: http.MethodPost, Path: "/topic/add", Handler: topic.CreateTopicHandler(serverCtx)},
{Method: http.MethodPost, Path: "/topic/page", Handler: topic.GetTopicListHandler(serverCtx)},
{Method: http.MethodGet, Path: "/topic/detail", Handler: legacy.TopicDetailHandler(serverCtx)},
{Method: http.MethodPost, Path: "/classify/plant", Handler: ocr.OcrClassifyHandler(serverCtx)},
{Method: http.MethodPost, Path: "/classify/myClassifyLog", Handler: ocr.GetMyClassifyLogHandler(serverCtx)},
{Method: http.MethodPost, Path: "/classify/deleteClassifyLog", Handler: ocr.DeleteClassifyLogHandler(serverCtx)},
{Method: http.MethodGet, Path: "/exchange/list", Handler: exchange.GetExchangeItemListHandler(serverCtx)},
{Method: http.MethodGet, Path: "/exchange/detail", Handler: legacy.ExchangeItemDetailHandler(serverCtx)},
{Method: http.MethodPost, Path: "/exchange/redeem", Handler: exchange.CreateExchangeOrderHandler(serverCtx)},
{Method: http.MethodGet, Path: "/exchange/orders", Handler: exchange.GetMyExchangeOrdersHandler(serverCtx)},
{Method: http.MethodPost, Path: "/exchange/item/list", Handler: exchange.GetExchangeItemListHandler(serverCtx)},
{Method: http.MethodGet, Path: "/chat/history", Handler: ai.GetAiChatHistoryHandler(serverCtx)},
{Method: http.MethodPost, Path: "/chat/history/delete", Handler: ai.DeleteAiChatHistoryHandler(serverCtx)},
{Method: http.MethodPost, Path: "/chat/history/clear", Handler: ai.ClearAiChatHistoryHandler(serverCtx)},
{Method: http.MethodGet, Path: "/chat/quota", Handler: ai.GetAiChatQuotaHandler(serverCtx)},
{Method: http.MethodPost, Path: "/chat/sync", Handler: legacy.AiChatSyncHandler(serverCtx)},
// 快捷养护(旧版兼容)
{Method: http.MethodPost, Path: "/quickCare", Handler: myPlant.QuickCareHandler(serverCtx)},
}, },
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithPrefix("/api/plant"), rest.WithPrefix("/api/plant"),
@@ -15,11 +15,11 @@ import (
func GetTopicListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { func GetTopicListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
l := topic.NewGetTopicListLogic(r.Context(), svcCtx) l := topic.NewGetTopicListLogic(r.Context(), svcCtx)
err := l.GetTopicList() resp, err := l.GetTopicList()
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -0,0 +1,27 @@
package topic
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/topic"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetTopicDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdPathReq
if err := httpx.ParsePath(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := topic.NewGetTopicDetailLogic(r.Context(), svcCtx)
resp, err := l.GetTopicDetail(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package topic
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/topic"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 更新话题
func UpdateTopicHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateTopicReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := topic.NewUpdateTopicLogic(r.Context(), svcCtx)
err := l.UpdateTopic(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -15,11 +15,11 @@ import (
func GetUserProfileHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { func GetUserProfileHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
l := userProfile.NewGetUserProfileLogic(r.Context(), svcCtx) l := userProfile.NewGetUserProfileLogic(r.Context(), svcCtx)
err := l.GetUserProfile() resp, err := l.GetUserProfile()
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -0,0 +1,20 @@
package userProfile
import (
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/userProfile"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/common/response"
)
func GetMyBadgesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := userProfile.NewGetMyBadgesLogic(r.Context(), svcCtx)
resp, err := l.GetMyBadges()
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,27 @@
package userProfile
import (
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"sundynix-micro-go/app/plant/api/internal/logic/userProfile"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
func GetMyStarsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.PageReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := userProfile.NewGetMyStarsLogic(r.Context(), svcCtx)
resp, err := l.GetMyStars(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.OkWithData(w, resp)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package wiki
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/wiki"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 创建百科
func CreateWikiHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CreateWikiReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := wiki.NewCreateWikiLogic(r.Context(), svcCtx)
err := l.CreateWiki(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package wiki
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/wiki"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除百科分类
func DeleteWikiClassHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := wiki.NewDeleteWikiClassLogic(r.Context(), svcCtx)
err := l.DeleteWikiClass(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package wiki
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/wiki"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 删除百科
func DeleteWikiHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.IdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := wiki.NewDeleteWikiLogic(r.Context(), svcCtx)
err := l.DeleteWiki(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -15,11 +15,11 @@ import (
func GetWikiClassListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { func GetWikiClassListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
l := wiki.NewGetWikiClassListLogic(r.Context(), svcCtx) l := wiki.NewGetWikiClassListLogic(r.Context(), svcCtx)
err := l.GetWikiClassList() resp, err := l.GetWikiClassList()
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -23,11 +23,11 @@ func GetWikiDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := wiki.NewGetWikiDetailLogic(r.Context(), svcCtx) l := wiki.NewGetWikiDetailLogic(r.Context(), svcCtx)
err := l.GetWikiDetail(&req) resp, err := l.GetWikiDetail(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -23,11 +23,11 @@ func GetWikiListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
} }
l := wiki.NewGetWikiListLogic(r.Context(), svcCtx) l := wiki.NewGetWikiListLogic(r.Context(), svcCtx)
err := l.GetWikiList(&req) resp, err := l.GetWikiList(&req)
if err != nil { if err != nil {
response.Fail(w, err.Error()) response.Fail(w, err.Error())
} else { } else {
response.Ok(w) response.OkWithData(w, resp)
} }
} }
} }
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package wiki
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/wiki"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 更新百科分类
func UpdateWikiClassHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateWikiClassReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := wiki.NewUpdateWikiClassLogic(r.Context(), svcCtx)
err := l.UpdateWikiClass(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package wiki
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"sundynix-micro-go/app/plant/api/internal/logic/wiki"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/common/response"
)
// 更新百科
func UpdateWikiHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateWikiReq
if err := httpx.Parse(r, &req); err != nil {
response.Fail(w, err.Error())
return
}
l := wiki.NewUpdateWikiLogic(r.Context(), svcCtx)
err := l.UpdateWiki(&req)
if err != nil {
response.Fail(w, err.Error())
} else {
response.Ok(w)
}
}
}
@@ -5,6 +5,7 @@ package ai
import ( import (
"context" "context"
"fmt"
"sundynix-micro-go/app/plant/api/internal/svc" "sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types" "sundynix-micro-go/app/plant/api/internal/types"
@@ -27,8 +28,8 @@ func NewAiChatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AiChatLogi
} }
} }
func (l *AiChatLogic) AiChat(req *types.AiChatReq) error { func (l *AiChatLogic) AiChat(req *types.AiChatReq) (string, error) {
// todo: add your logic here and delete this line l.Logger.Infof("AI chat request: %s", req.Question)
userID := fmt.Sprintf("%v", l.ctx.Value("userId"))
return nil return ChatCompletion(l.ctx, l.svcCtx, userID, req.Question)
} }
@@ -0,0 +1,25 @@
package ai
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type ClearAiChatHistoryLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewClearAiChatHistoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClearAiChatHistoryLogic {
return &ClearAiChatHistoryLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *ClearAiChatHistoryLogic) ClearAiChatHistory() error {
userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
_, err := l.svcCtx.PlantRpc.ClearAiChatHistory(l.ctx, &plantPb.GetProfileReq{UserId: userId})
return err
}
@@ -0,0 +1,24 @@
package ai
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type DeleteAiChatHistoryLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteAiChatHistoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteAiChatHistoryLogic {
return &DeleteAiChatHistoryLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *DeleteAiChatHistoryLogic) DeleteAiChatHistory(req *types.IdsReq) error {
_, err := l.svcCtx.PlantRpc.DeleteAiChatHistory(l.ctx, &plantPb.IdsReq{Ids: req.Ids})
return err
}
@@ -5,6 +5,7 @@ package ai
import ( import (
"context" "context"
"fmt"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc" "sundynix-micro-go/app/plant/api/internal/svc"
@@ -25,8 +26,10 @@ func NewGetAiChatHistoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *
} }
} }
func (l *GetAiChatHistoryLogic) GetAiChatHistory() error { // GetAiChatHistory TODO: 完善 AI 聊天历史查询
// todo: add your logic here and delete this line func (l *GetAiChatHistoryLogic) GetAiChatHistory() (interface{}, error) {
userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
return nil l.Logger.Infof("get ai chat history for user: %s", userId)
// 待实现:从 sundynix_ai_chat_history 表分页查询
return map[string]interface{}{"list": []interface{}{}}, nil
} }
@@ -0,0 +1,24 @@
package ai
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type GetAiChatQuotaLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetAiChatQuotaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAiChatQuotaLogic {
return &GetAiChatQuotaLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetAiChatQuotaLogic) GetAiChatQuota() (*plantPb.AiQuotaResp, error) {
userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
return l.svcCtx.PlantRpc.GetAiChatQuota(l.ctx, &plantPb.GetProfileReq{UserId: userId})
}
+246
View File
@@ -0,0 +1,246 @@
package ai
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sundynix-micro-go/app/plant/api/internal/svc"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type chatRequest struct {
Model string `json:"model,omitempty"`
Messages []chatMessage `json:"messages"`
Stream bool `json:"stream"`
}
func chatModel(svcCtx *svc.ServiceContext) string {
if svcCtx.Config.Ai.ChatModelName != "" {
return svcCtx.Config.Ai.ChatModelName
}
return "gpt-4o-mini"
}
func requestBody(svcCtx *svc.ServiceContext, question string, stream bool) ([]byte, error) {
systemPrompt := "你是一个专业的植物百科助手。回答规则:基于知识库信息回答,不够则结合通用知识;不要使用 Markdown;用纯文本分段;回答简洁专业、条理清晰。"
if ctxText := retrieveRAGContext(context.Background(), svcCtx, question); ctxText != "" {
systemPrompt += "\n--- 知识库 ---\n" + ctxText + "\n--------------"
}
return json.Marshal(chatRequest{
Model: chatModel(svcCtx),
Messages: []chatMessage{
{Role: "system", Content: systemPrompt},
{Role: "user", Content: question},
},
Stream: stream,
})
}
func retrieveRAGContext(ctx context.Context, svcCtx *svc.ServiceContext, question string) string {
c := svcCtx.Config.Ai
if c.EmbeddingApiUrl == "" || c.EmbeddingApiKey == "" || c.QdrantUrl == "" || c.QdrantCollection == "" {
return ""
}
body, _ := json.Marshal(map[string]interface{}{
"model": c.EmbeddingModelName,
"input": question,
})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.EmbeddingApiUrl, bytes.NewReader(body))
if err != nil {
return ""
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.EmbeddingApiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return ""
}
defer resp.Body.Close()
var emb struct {
Data []struct {
Embedding []float32 `json:"embedding"`
} `json:"data"`
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 || json.NewDecoder(resp.Body).Decode(&emb) != nil || len(emb.Data) == 0 {
return ""
}
searchBody, _ := json.Marshal(map[string]interface{}{
"vector": emb.Data[0].Embedding,
"limit": 3,
"with_payload": true,
})
searchReq, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(c.QdrantUrl, "/")+"/collections/"+c.QdrantCollection+"/points/search", bytes.NewReader(searchBody))
if err != nil {
return ""
}
searchReq.Header.Set("Content-Type", "application/json")
if c.QdrantApiKey != "" {
searchReq.Header.Set("api-key", c.QdrantApiKey)
}
searchResp, err := http.DefaultClient.Do(searchReq)
if err != nil {
return ""
}
defer searchResp.Body.Close()
var parsed struct {
Result []struct {
Payload map[string]interface{} `json:"payload"`
} `json:"result"`
}
if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 || json.NewDecoder(searchResp.Body).Decode(&parsed) != nil {
return ""
}
var b strings.Builder
for _, item := range parsed.Result {
if text, ok := item.Payload["full_text"].(string); ok && text != "" {
b.WriteString(text)
b.WriteString("\n")
}
}
return b.String()
}
func newChatRequest(ctx context.Context, svcCtx *svc.ServiceContext, body []byte) (*http.Request, error) {
if svcCtx.Config.Ai.ChatApiUrl == "" || svcCtx.Config.Ai.ChatApiKey == "" {
return nil, errors.New("AI/RAG 未配置 ChatApiUrl 或 ChatApiKey")
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, svcCtx.Config.Ai.ChatApiUrl, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+svcCtx.Config.Ai.ChatApiKey)
return req, nil
}
func SaveHistory(ctx context.Context, svcCtx *svc.ServiceContext, userID, question, answer string) {
if userID == "" || question == "" || answer == "" {
return
}
_, _ = svcCtx.PlantRpc.SaveAiChatHistory(ctx, &plantPb.SaveAiChatHistoryReq{
UserId: userID, Question: question, Answer: answer,
})
}
func ChatCompletion(ctx context.Context, svcCtx *svc.ServiceContext, userID, question string) (string, error) {
if err := ensureQuota(ctx, svcCtx, userID); err != nil {
return "", err
}
body, err := requestBody(svcCtx, question, false)
if err != nil {
return "", err
}
req, err := newChatRequest(ctx, svcCtx, body)
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return "", fmt.Errorf("AI 请求失败: %s %s", resp.Status, strings.TrimSpace(string(raw)))
}
var parsed struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {
return "", err
}
if len(parsed.Choices) == 0 || parsed.Choices[0].Message.Content == "" {
return "", errors.New("AI 响应为空")
}
answer := parsed.Choices[0].Message.Content
SaveHistory(ctx, svcCtx, userID, question, answer)
return answer, nil
}
func StreamChat(ctx context.Context, svcCtx *svc.ServiceContext, userID, question string, w io.Writer) error {
if err := ensureQuota(ctx, svcCtx, userID); err != nil {
return err
}
body, err := requestBody(svcCtx, question, true)
if err != nil {
return err
}
req, err := newChatRequest(ctx, svcCtx, body)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("AI 请求失败: %s %s", resp.Status, strings.TrimSpace(string(raw)))
}
var answer strings.Builder
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
_, _ = fmt.Fprintln(w, line)
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
}
if !strings.HasPrefix(line, "data: ") {
continue
}
data := strings.TrimSpace(strings.TrimPrefix(line, "data: "))
if data == "[DONE]" {
continue
}
var chunk struct {
Choices []struct {
Delta struct {
Content string `json:"content"`
} `json:"delta"`
} `json:"choices"`
}
if json.Unmarshal([]byte(data), &chunk) == nil && len(chunk.Choices) > 0 {
answer.WriteString(chunk.Choices[0].Delta.Content)
}
}
if err := scanner.Err(); err != nil {
return err
}
SaveHistory(ctx, svcCtx, userID, question, answer.String())
return nil
}
func ensureQuota(ctx context.Context, svcCtx *svc.ServiceContext, userID string) error {
if userID == "" {
return nil
}
quota, err := svcCtx.PlantRpc.GetAiChatQuota(ctx, &plantPb.GetProfileReq{UserId: userID})
if err != nil {
return err
}
if quota.Limit > 0 && quota.Remaining <= 0 {
return fmt.Errorf("今日问答次数已达上限(%d次),明天再来吧", quota.Limit)
}
return nil
}
@@ -0,0 +1,38 @@
package banner
import (
"context"
"fmt"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantModel "sundynix-micro-go/app/plant/model"
"github.com/zeromicro/go-zero/core/logx"
)
type CreateBannerLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateBannerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateBannerLogic {
return &CreateBannerLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *CreateBannerLogic) CreateBanner(req *types.CreateBannerReq) error {
userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
_ = userId
banner := plantModel.Banner{
Title: req.Title,
ImageID: req.ImageId,
Sort: req.Sort,
IsActive: req.IsActive,
TargetURL: req.TargetUrl,
}
if banner.IsActive == 0 {
banner.IsActive = 1
}
return l.svcCtx.DB.Create(&banner).Error
}
@@ -0,0 +1,26 @@
package banner
import (
"context"
"sundynix-micro-go/app/plant/api/internal/types"
plantModel "sundynix-micro-go/app/plant/model"
"sundynix-micro-go/app/plant/api/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type DeleteBannerLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteBannerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteBannerLogic {
return &DeleteBannerLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *DeleteBannerLogic) DeleteBanner(req *types.IdReq) error {
return l.svcCtx.DB.Where("id = ?", req.Id).Delete(&plantModel.Banner{}).Error
}
@@ -0,0 +1,88 @@
package banner
import (
"context"
"sundynix-micro-go/app/file/rpc/fileservice"
"sundynix-micro-go/app/plant/api/internal/svc"
plantModel "sundynix-micro-go/app/plant/model"
"github.com/zeromicro/go-zero/core/logx"
)
type GetActiveBannerListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetActiveBannerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetActiveBannerListLogic {
return &GetActiveBannerListLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetActiveBannerListLogic) GetActiveBannerList() (interface{}, error) {
var list []plantModel.Banner
l.svcCtx.DB.Model(&plantModel.Banner{}).
Where("is_active = 1").
Order("sort asc, created_at desc").
Find(&list)
// Collect image IDs for batch fetch
var imageIds []string
for _, item := range list {
if item.ImageID != "" {
imageIds = append(imageIds, item.ImageID)
}
}
// Fetch image URLs from file service
imageUrlMap := make(map[string]string)
if len(imageIds) > 0 {
resp, err := l.svcCtx.FileRpc.GetFilesByIds(l.ctx, &fileservice.GetFilesByIdsReq{Ids: imageIds})
if err != nil {
logx.Errorf("Fetch banner image files failed: %v", err)
} else if resp != nil {
for _, f := range resp.Files {
if f != nil && f.Url != "" {
imageUrlMap[f.Id] = f.Url
}
}
}
}
type BannerItem struct {
Id string `json:"id"`
Title string `json:"title"`
ImageId string `json:"imageId"`
ImageUrl string `json:"imageUrl"`
Sort int `json:"sort"`
IsActive int `json:"isActive"`
TargetUrl string `json:"targetUrl"`
CreatedAt string `json:"createdAt"`
}
var result []BannerItem
for _, item := range list {
imageUrl := ""
if u, ok := imageUrlMap[item.ImageID]; ok {
imageUrl = u
}
createdAt := ""
if !item.CreatedAt.IsZero() {
createdAt = item.CreatedAt.Format("2006-01-02 15:04:05")
}
result = append(result, BannerItem{
Id: item.ID,
Title: item.Title,
ImageId: item.ImageID,
ImageUrl: imageUrl,
Sort: item.Sort,
IsActive: item.IsActive,
TargetUrl: item.TargetURL,
CreatedAt: createdAt,
})
}
return map[string]interface{}{
"list": result,
}, nil
}
@@ -0,0 +1,78 @@
package banner
import (
"context"
"math"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantModel "sundynix-micro-go/app/plant/model"
"github.com/zeromicro/go-zero/core/logx"
)
type GetBannerListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetBannerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBannerListLogic {
return &GetBannerListLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetBannerListLogic) GetBannerList(req *types.BannerListReq) (interface{}, error) {
db := l.svcCtx.DB.Model(&plantModel.Banner{})
if req.Title != "" {
db = db.Where("title LIKE ?", "%"+req.Title+"%")
}
if req.IsActive > 0 {
db = db.Where("is_active = ?", req.IsActive)
}
var total int64
db.Count(&total)
pageSize := req.PageSize
if pageSize <= 0 {
pageSize = 10
}
current := req.Current
if current <= 0 {
current = 1
}
offset := (current - 1) * pageSize
var list []plantModel.Banner
db.Order("sort asc, created_at desc").Limit(pageSize).Offset(offset).Find(&list)
type BannerItem struct {
Id string `json:"id"`
Title string `json:"title"`
ImageId string `json:"imageId"`
Sort int `json:"sort"`
IsActive int `json:"isActive"`
TargetUrl string `json:"targetUrl"`
CreatedAt string `json:"createdAt"`
}
var result []BannerItem
for _, item := range list {
result = append(result, BannerItem{
Id: item.ID,
Title: item.Title,
ImageId: item.ImageID,
Sort: item.Sort,
IsActive: item.IsActive,
TargetUrl: item.TargetURL,
CreatedAt: item.CreatedAt.Format("2006-01-02 15:04:05"),
})
}
return map[string]interface{}{
"list": result,
"total": total,
"page": current,
"pageSize": pageSize,
"totalPage": math.Ceil(float64(total) / float64(pageSize)),
}, nil
}
@@ -0,0 +1,41 @@
package banner
import (
"context"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantModel "sundynix-micro-go/app/plant/model"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateBannerLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateBannerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateBannerLogic {
return &UpdateBannerLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *UpdateBannerLogic) UpdateBanner(req *types.UpdateBannerReq) error {
updates := map[string]interface{}{}
if req.Title != "" {
updates["title"] = req.Title
}
if req.ImageId != "" {
updates["image_id"] = req.ImageId
}
if req.Sort != 0 {
updates["sort"] = req.Sort
}
if req.IsActive != 0 {
updates["is_active"] = req.IsActive
}
if req.TargetUrl != "" {
updates["target_url"] = req.TargetUrl
}
return l.svcCtx.DB.Model(&plantModel.Banner{}).Where("id = ?", req.Id).Updates(updates).Error
}
@@ -5,6 +5,9 @@ package callback
import ( import (
"context" "context"
"encoding/json"
"io"
"net/http"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc" "sundynix-micro-go/app/plant/api/internal/svc"
@@ -25,8 +28,52 @@ func NewWechatPayCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext)
} }
} }
func (l *WechatPayCallbackLogic) WechatPayCallback() error { // wechatNotify 微信支付回调通知结构
// todo: add your logic here and delete this line type wechatNotify struct {
Id string `json:"id"`
EventType string `json:"event_type"`
Summary string `json:"summary"`
ResourceType string `json:"resource_type"`
Resource struct {
Algorithm string `json:"algorithm"`
Ciphertext string `json:"ciphertext"`
AssociatedData string `json:"associated_data"`
Nonce string `json:"nonce"`
} `json:"resource"`
}
// WechatPayCallback 微信支付回调处理
// TODO: 接入 wechatpay-go SDK 完成验签 + 解密 + 订单状态更新
//
// 完整接入步骤:
// 1. go get github.com/wechatpay-apiv3/wechatpay-go
// 2. 在 config 中添加 WechatPay{ MchId, MchAPIv3Key, PrivateKeyPath, PublicKeyId, PublicKeyPath }
// 3. 使用 notify.NewRSANotifyHandler 验签解密
// 4. 解析 payments.Transaction 后根据 TradeState == "SUCCESS" 更新 sundynix_exchange_order 状态
func (l *WechatPayCallbackLogic) WechatPayCallback(r *http.Request) error {
// 1. 读取请求体
body, err := io.ReadAll(r.Body)
if err != nil {
l.Logger.Errorf("[微信支付回调] 读取请求体失败: %v", err)
return err
}
defer r.Body.Close()
// 2. 解析通知基本结构(不验签,记录日志)
var notify wechatNotify
if err = json.Unmarshal(body, &notify); err != nil {
l.Logger.Errorf("[微信支付回调] 解析通知失败: %v, body: %s", err, string(body))
return err
}
l.Logger.Infof("[微信支付回调] 收到通知 id=%s, event=%s, summary=%s",
notify.Id, notify.EventType, notify.Summary)
// TODO: 完成验签 + 解密 + 业务处理
// if notify.EventType == "TRANSACTION.SUCCESS" {
// transaction := decrypt(notify.Resource, mchAPIv3Key)
// updateOrderStatus(transaction.OutTradeNo, "SUCCESS")
// }
return nil return nil
} }
@@ -0,0 +1,28 @@
package complete
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type CompleteTaskLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCompleteTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CompleteTaskLogic {
return &CompleteTaskLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *CompleteTaskLogic) CompleteTask(req *types.CompleteTaskApiReq) (*plantPb.TaskCompletionResult, error) {
userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
return l.svcCtx.PlantRpc.CompleteTask(l.ctx, &plantPb.CompleteTaskReq{
UserId: userId, TaskId: req.TaskId, Remark: req.Remark,
})
}
@@ -0,0 +1,28 @@
package complete
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type GetAiChatHistoryLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetAiChatHistoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAiChatHistoryLogic {
return &GetAiChatHistoryLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetAiChatHistoryLogic) GetAiChatHistory(req *types.PageReq) (*plantPb.AiChatHistoryResp, error) {
userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
return l.svcCtx.PlantRpc.GetAiChatHistory(l.ctx, &plantPb.AiChatHistoryReq{
UserId: userId, Current: int32(req.Current), PageSize: int32(req.PageSize),
})
}
@@ -0,0 +1,23 @@
package complete
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type GetBadgeConfigTreeLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetBadgeConfigTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBadgeConfigTreeLogic {
return &GetBadgeConfigTreeLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetBadgeConfigTreeLogic) GetBadgeConfigTree() (*plantPb.BadgeConfigTreeResp, error) {
return l.svcCtx.PlantRpc.GetBadgeConfigTree(l.ctx, &plantPb.IdReq{})
}
@@ -0,0 +1,24 @@
package complete
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type GetExchangeItemDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetExchangeItemDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetExchangeItemDetailLogic {
return &GetExchangeItemDetailLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetExchangeItemDetailLogic) GetExchangeItemDetail(req *types.IdPathReq) (*plantPb.ExchangeItemInfo, error) {
return l.svcCtx.PlantRpc.GetExchangeItemDetail(l.ctx, &plantPb.IdReq{Id: req.Id})
}
@@ -0,0 +1,24 @@
package complete
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type GetLevelConfigDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetLevelConfigDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLevelConfigDetailLogic {
return &GetLevelConfigDetailLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetLevelConfigDetailLogic) GetLevelConfigDetail(req *types.IdPathReq) (*plantPb.LevelConfigInfo, error) {
return l.svcCtx.PlantRpc.GetLevelConfigDetail(l.ctx, &plantPb.IdReq{Id: req.Id})
}
@@ -0,0 +1,24 @@
package complete
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type GetWikiClassDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetWikiClassDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWikiClassDetailLogic {
return &GetWikiClassDetailLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetWikiClassDetailLogic) GetWikiClassDetail(req *types.IdPathReq) (*plantPb.WikiClassInfo, error) {
return l.svcCtx.PlantRpc.GetWikiClassDetail(l.ctx, &plantPb.IdReq{Id: req.Id})
}
@@ -0,0 +1,28 @@
package config
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type CreateBadgeConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateBadgeConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateBadgeConfigLogic {
return &CreateBadgeConfigLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *CreateBadgeConfigLogic) CreateBadgeConfig(req *types.CreateBadgeConfigReq) error {
_, err := l.svcCtx.PlantRpc.CreateBadgeConfig(l.ctx, &plantPb.CreateBadgeConfigReq{
Name: req.Name, Description: req.Description, Dimension: req.Dimension,
GroupId: req.GroupId, Tier: int32(req.Tier), TargetAction: req.TargetAction,
Threshold: req.Threshold, RewardSunlight: req.RewardSunlight, IconId: req.IconId, Sort: int32(req.Sort),
})
return err
}
@@ -0,0 +1,26 @@
package config
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type CreateLevelConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateLevelConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLevelConfigLogic {
return &CreateLevelConfigLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *CreateLevelConfigLogic) CreateLevelConfig(req *types.CreateLevelConfigReq) error {
_, err := l.svcCtx.PlantRpc.CreateLevelConfig(l.ctx, &plantPb.CreateLevelConfigReq{
Level: int32(req.Level), Title: req.Title, MinSunlight: req.MinSunlight, Perks: req.Perks,
})
return err
}
@@ -0,0 +1,24 @@
package config
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type DeleteBadgeConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteBadgeConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteBadgeConfigLogic {
return &DeleteBadgeConfigLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *DeleteBadgeConfigLogic) DeleteBadgeConfig(req *types.IdsReq) error {
_, err := l.svcCtx.PlantRpc.DeleteBadgeConfig(l.ctx, &plantPb.IdsReq{Ids: req.Ids})
return err
}
@@ -0,0 +1,24 @@
package config
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type DeleteLevelConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteLevelConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteLevelConfigLogic {
return &DeleteLevelConfigLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *DeleteLevelConfigLogic) DeleteLevelConfig(req *types.IdsReq) error {
_, err := l.svcCtx.PlantRpc.DeleteLevelConfig(l.ctx, &plantPb.IdsReq{Ids: req.Ids})
return err
}
@@ -8,6 +8,7 @@ import (
"sundynix-micro-go/app/plant/api/internal/svc" "sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types" "sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/app/plant/rpc/plant"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
) )
@@ -27,8 +28,17 @@ func NewGetBadgeConfigListLogic(ctx context.Context, svcCtx *svc.ServiceContext)
} }
} }
func (l *GetBadgeConfigListLogic) GetBadgeConfigList(req *types.BadgeConfigListReq) error { func (l *GetBadgeConfigListLogic) GetBadgeConfigList(req *types.BadgeConfigListReq) (interface{}, error) {
// todo: add your logic here and delete this line result, err := l.svcCtx.PlantRpc.GetBadgeConfigList(l.ctx, &plant.BadgeConfigListReq{
Current: int32(req.Current),
return nil PageSize: int32(req.PageSize),
Dimension: req.Dimension,
})
if err != nil {
return nil, err
}
return map[string]interface{}{
"list": result.List,
"total": result.Total,
}, nil
} }
@@ -8,6 +8,7 @@ import (
"sundynix-micro-go/app/plant/api/internal/svc" "sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types" "sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/app/plant/rpc/plant"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
) )
@@ -27,8 +28,15 @@ func NewGetLevelConfigListLogic(ctx context.Context, svcCtx *svc.ServiceContext)
} }
} }
func (l *GetLevelConfigListLogic) GetLevelConfigList(req *types.LevelConfigListReq) error { func (l *GetLevelConfigListLogic) GetLevelConfigList(req *types.LevelConfigListReq) (interface{}, error) {
// todo: add your logic here and delete this line result, err := l.svcCtx.PlantRpc.GetLevelConfigList(l.ctx, &plant.PageReq{
Current: int32(req.Current),
return nil PageSize: int32(req.PageSize),
})
if err != nil {
return nil, err
}
return map[string]interface{}{
"list": result.List,
}, nil
} }
@@ -0,0 +1,28 @@
package config
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type UpdateBadgeConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateBadgeConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateBadgeConfigLogic {
return &UpdateBadgeConfigLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *UpdateBadgeConfigLogic) UpdateBadgeConfig(req *types.UpdateBadgeConfigReq) error {
_, err := l.svcCtx.PlantRpc.UpdateBadgeConfig(l.ctx, &plantPb.UpdateBadgeConfigReq{
Id: req.Id, Name: req.Name, Description: req.Description, Dimension: req.Dimension,
GroupId: req.GroupId, Tier: int32(req.Tier), TargetAction: req.TargetAction,
Threshold: req.Threshold, RewardSunlight: req.RewardSunlight, IconId: req.IconId, Sort: int32(req.Sort),
})
return err
}
@@ -0,0 +1,26 @@
package config
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type UpdateLevelConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateLevelConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLevelConfigLogic {
return &UpdateLevelConfigLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *UpdateLevelConfigLogic) UpdateLevelConfig(req *types.UpdateLevelConfigReq) error {
_, err := l.svcCtx.PlantRpc.UpdateLevelConfig(l.ctx, &plantPb.UpdateLevelConfigReq{
Id: req.Id, Level: int32(req.Level), Title: req.Title, MinSunlight: req.MinSunlight, Perks: req.Perks,
})
return err
}
@@ -5,9 +5,11 @@ package exchange
import ( import (
"context" "context"
"fmt"
"sundynix-micro-go/app/plant/api/internal/svc" "sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types" "sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/app/plant/rpc/plant"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
) )
@@ -28,7 +30,14 @@ func NewCreateExchangeOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext
} }
func (l *CreateExchangeOrderLogic) CreateExchangeOrder(req *types.ExchangeOrderReq) error { func (l *CreateExchangeOrderLogic) CreateExchangeOrder(req *types.ExchangeOrderReq) error {
// todo: add your logic here and delete this line userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
_, err := l.svcCtx.PlantRpc.CreateExchangeOrder(l.ctx, &plant.CreateExchangeOrderReq{
return nil UserId: userId,
ItemId: req.ItemId,
Quantity: int32(req.Quantity),
RecipientName: req.RecipientName,
Phone: req.Phone,
Address: req.Address,
})
return err
} }
@@ -0,0 +1,40 @@
package exchange
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type CreateExchangeItemLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateExchangeItemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateExchangeItemLogic {
return &CreateExchangeItemLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *CreateExchangeItemLogic) CreateExchangeItem(req *types.CreateExchangeItemReq) error {
desc := req.Desc
if desc == "" {
desc = req.Description
}
imgID := req.ImgId
if imgID == "" {
imgID = req.ImageId
}
cost := req.Cost
if cost == 0 {
cost = req.CostSunlight
}
_, err := l.svcCtx.PlantRpc.CreateExchangeItem(l.ctx, &plantPb.CreateExchangeItemReq{
Name: req.Name, Desc: desc, ImgId: imgID, Cost: cost, Stock: int32(req.Stock),
Type: req.Type, CostSunlight: req.CostSunlight, LimitPerUser: int32(req.LimitPerUser),
Sort: int32(req.Sort), StartTime: req.StartTime, EndTime: req.EndTime, ImageId: req.ImageId,
})
return err
}
@@ -0,0 +1,24 @@
package exchange
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type DeleteExchangeItemLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteExchangeItemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteExchangeItemLogic {
return &DeleteExchangeItemLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *DeleteExchangeItemLogic) DeleteExchangeItem(req *types.IdsReq) error {
_, err := l.svcCtx.PlantRpc.DeleteExchangeItem(l.ctx, &plantPb.IdsReq{Ids: req.Ids})
return err
}
@@ -8,6 +8,7 @@ import (
"sundynix-micro-go/app/plant/api/internal/svc" "sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types" "sundynix-micro-go/app/plant/api/internal/types"
"sundynix-micro-go/app/plant/rpc/plant"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
) )
@@ -27,8 +28,16 @@ func NewGetExchangeItemListLogic(ctx context.Context, svcCtx *svc.ServiceContext
} }
} }
func (l *GetExchangeItemListLogic) GetExchangeItemList(req *types.ExchangeItemListReq) error { func (l *GetExchangeItemListLogic) GetExchangeItemList(req *types.ExchangeItemListReq) (interface{}, error) {
// todo: add your logic here and delete this line result, err := l.svcCtx.PlantRpc.GetExchangeItemList(l.ctx, &plant.ExchangeItemListReq{
Current: int32(req.Current),
return nil PageSize: int32(req.PageSize),
})
if err != nil {
return nil, err
}
return map[string]interface{}{
"list": result.List,
"total": result.Total,
}, nil
} }
@@ -0,0 +1,25 @@
package exchange
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type GetExchangeOrderListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetExchangeOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetExchangeOrderListLogic {
return &GetExchangeOrderListLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetExchangeOrderListLogic) GetExchangeOrderList(req *types.ExchangeOrderListReq) (*plantPb.ExchangeOrderListResp, error) {
return l.svcCtx.PlantRpc.GetExchangeOrderList(l.ctx, &plantPb.ExchangeOrderListReq{
UserId: req.UserId, Current: int32(req.Current), PageSize: int32(req.PageSize), Status: int32(req.Status),
})
}
@@ -0,0 +1,27 @@
package exchange
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type GetMyExchangeOrdersLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetMyExchangeOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMyExchangeOrdersLogic {
return &GetMyExchangeOrdersLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetMyExchangeOrdersLogic) GetMyExchangeOrders(req *types.ExchangeOrderListReq) (*plantPb.ExchangeOrderListResp, error) {
userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
return l.svcCtx.PlantRpc.GetMyExchangeOrders(l.ctx, &plantPb.ExchangeOrderListReq{
UserId: userId, Current: int32(req.Current), PageSize: int32(req.PageSize), Status: int32(req.Status),
})
}
@@ -0,0 +1,41 @@
package exchange
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type UpdateExchangeItemLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateExchangeItemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateExchangeItemLogic {
return &UpdateExchangeItemLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *UpdateExchangeItemLogic) UpdateExchangeItem(req *types.UpdateExchangeItemReq) error {
desc := req.Desc
if desc == "" {
desc = req.Description
}
imgID := req.ImgId
if imgID == "" {
imgID = req.ImageId
}
cost := req.Cost
if cost == 0 {
cost = req.CostSunlight
}
_, err := l.svcCtx.PlantRpc.UpdateExchangeItem(l.ctx, &plantPb.UpdateExchangeItemReq{
Id: req.Id, Name: req.Name, Desc: desc, ImgId: imgID,
Cost: cost, Stock: int32(req.Stock), Status: int32(req.Status),
Type: req.Type, CostSunlight: req.CostSunlight, LimitPerUser: int32(req.LimitPerUser),
Sort: int32(req.Sort), StartTime: req.StartTime, EndTime: req.EndTime, ImageId: req.ImageId,
})
return err
}
@@ -0,0 +1,26 @@
package exchange
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"sundynix-micro-go/app/plant/api/internal/svc"
"sundynix-micro-go/app/plant/api/internal/types"
plantPb "sundynix-micro-go/app/plant/rpc/plant"
)
type UpdateExchangeOrderLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateExchangeOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateExchangeOrderLogic {
return &UpdateExchangeOrderLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *UpdateExchangeOrderLogic) UpdateExchangeOrder(req *types.UpdateExchangeOrderReq) error {
_, err := l.svcCtx.PlantRpc.UpdateExchangeOrder(l.ctx, &plantPb.UpdateExchangeOrderReq{
Id: req.Id, Status: int32(req.Status), TrackingNo: req.TrackingNo, Remark: req.Remark,
})
return err
}
@@ -21,10 +21,35 @@ func NewCreatePlantLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Creat
func (l *CreatePlantLogic) CreatePlant(req *types.CreatePlantReq) error { func (l *CreatePlantLogic) CreatePlant(req *types.CreatePlantReq) error {
userId := fmt.Sprintf("%v", l.ctx.Value("userId")) userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
_, err := l.svcCtx.PlantRpc.CreatePlant(l.ctx, &plant.CreatePlantReq{ imgIds := req.ImgIds
if len(imgIds) == 0 {
imgIds = req.OssIds
}
resp, err := l.svcCtx.PlantRpc.CreatePlant(l.ctx, &plant.CreatePlantReq{
UserId: userId, Name: req.Name, PlantTime: req.PlantTime, Placement: req.Placement, UserId: userId, Name: req.Name, PlantTime: req.PlantTime, Placement: req.Placement,
PotMaterial: req.PotMaterial, PotSize: req.PotSize, Sunlight: req.Sunlight, PotMaterial: req.PotMaterial, PotSize: req.PotSize, Sunlight: req.Sunlight,
PlantingMaterial: req.PlantingMaterial, ImgIds: req.ImgIds, PlantingMaterial: req.PlantingMaterial, ImgIds: imgIds,
}) })
return err if err != nil {
return err
}
if resp == nil || resp.Msg == "" || resp.Msg == "ok" {
return nil
}
for _, planReq := range req.CarePlans {
if planReq.Name == "" || planReq.Period <= 0 {
continue
}
if _, err = l.svcCtx.PlantRpc.AddCarePlan(l.ctx, &plant.AddCarePlanReq{
UserId: userId,
PlantId: resp.Msg,
Name: planReq.Name,
Icon: planReq.Icon,
TargetAction: planReq.TargetAction,
Period: int32(planReq.Period),
}); err != nil {
return err
}
}
return nil
} }

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